fix(grpc-data): bound the unknown-mapping hold of imported conditions (#933)

A key no known mapping lists was kept stale for as long as ANY mapping of the
connection was unknown; a durably Denied/Unavailable mapping therefore kept
retired conditions forever. Scoping the hold to mappings that could list the
key is not provable on the consumer (placements are origin deploy-time config;
a dropped key may have moved into the unknown mapping's root), so the hold is
time-boxed per key: ProjectedConditionOptions.MaxUnknownHold (20 min) — past it
the key is removed (+ RefreshRequired at the sink), never known-inactive. The
since-time survives stream ends and hand-overs; the earliest expiry shares the
loop's retry timer. DataConnections.md: lifetime rule + troubleshooting row.
This commit is contained in:
Joseph Doherty
2026-11-25 10:56:23 -05:00
parent 179881f45c
commit 2eb31f62d2
4 changed files with 100 additions and 7 deletions
+7
View File
@@ -453,6 +453,12 @@ refresh, EventIds) is documented in [Alarm tracking § Imported conditions](Alar
- An in-stream re-snapshot is buffered. The live set and the nodes stay untouched until `snapshot_complete`.
- A condition is removed only when a **complete** snapshot no longer lists it (and no other mapping lists it), or when a
`removed` record arrives. An incomplete snapshot removes nothing. It marks the unlisted keys stale (`BadNoCommunication`).
- That hold is bounded per key (#933). A key no known mapping lists, kept stale because another mapping of the connection
is unknown (`Unavailable`, `Denied`, retrying), is removed after `ProjectedConditionOptions.MaxUnknownHold` (20 min,
fixed): a removal with `RefreshRequired`, never "known inactive". If the unknown mapping later lists it, it is re-created
(new EventIds). The hold cannot be narrowed to "mappings whose scope could list the key": an origin deploy can move a
condition's placements into the unknown mapping's root, so the consumer cannot prove it. 20 min outlasts the transient
retry cycle (snapshot timeout × 8) and the first two re-checks of a definitive refusal (`LongRetryDelay` 5 min, then 10).
7. **Known state (T2 invariant).** *The consumer never retires or clears an alarm that is active at the origin.*
- A record with `state_known = false` never changes the consumer's last state.
- A condition first seen unknown is materialised with `Quality = UncertainInitialValue` until a known record arrives.
@@ -631,6 +637,7 @@ status and diagnostic), and each snapshot barrier (per-mapping status, record co
| `ConditionCapacity` | The listing's `total` against the mapping's or export's `MaxConditions`, and the host caps. Narrow the remote root or raise the limits. |
| Conditions `Uncertain` | The origin has not established their state: a scripted alarm has not completed an evaluation; a native driver has not signalled (see `…conditions.unsignalled`). |
| Conditions `BadNoCommunication` | Stream down longer than `ConditionStaleTimeoutMilliseconds`, or the mapping was incomplete at the last barrier. |
| A retired condition stays `BadNoCommunication` while another mapping of the connection is `Unavailable` / `Denied` | Expected for up to `MaxUnknownHold` (20 min, #933): the unknown mapping might still list it, so it is held (T2). After that it is removed with `RefreshRequired` (logged Warning "held past MaxUnknownHold", naming the unknown mappings). Fix the unknown mapping (its refusal is on the AdminUI mappings line) to settle it sooner. |
| Ack answers `BadEventIdUnknown` | The client holds an old EventId (superseded occurrence, or an origin restart that re-announced a different time). ConditionRefresh and ack with the new EventId. |
| Ack answers "OutcomeUnknown" | Check the origin's audit log (`ZB.MOM.WW.OtOpcUa.DataConnections.Audit`) for the operation and watch the condition's events. Never replay blindly. |
| All `ConditionId`s changed | `ConditionKeySecret` was rotated or differs between the origin pair members, or the connection was re-created under a new id. |
@@ -254,6 +254,9 @@ public sealed partial class ProjectedConditionAccess
private Dictionary<string, HashSet<string>> _lastListed = new(StringComparer.OrdinalIgnoreCase);
/// <summary>A4 review r1 S4: per materialised key, the mapping that chose its SourceName and that name. Owned by the loop.</summary>
private Dictionary<string, (string MappingId, string SourceName)> _sourceNames = new(StringComparer.Ordinal);
/// <summary>#933: materialised keys no known mapping lists, held stale while another mapping is unknown → since when
/// (kept across stream ends and hand-overs, so a flapping stream cannot restart the bound). Owned by the loop.</summary>
private Dictionary<string, DateTimeOffset> _heldSince = new(StringComparer.Ordinal);
/// <summary>
/// A4 review r2 S3: this runner took over a set HELD across an undecided deploy. During the hold nothing imported was
@@ -340,6 +343,9 @@ public sealed partial class ProjectedConditionAccess
_sourceNames = previous._sourceNames;
previous._sourceNames = new Dictionary<string, (string, string)>(StringComparer.Ordinal);
foreach (var key in _sourceNames.Keys.Where(k => !_materialised.Contains(k)).ToArray()) _sourceNames.Remove(key);
_heldSince = previous._heldSince;
previous._heldSince = new Dictionary<string, DateTimeOffset>(StringComparer.Ordinal);
foreach (var key in _heldSince.Keys.Where(k => !_materialised.Contains(k)).ToArray()) _heldSince.Remove(key);
Volatile.Write(ref _materialisedCount, _materialised.Count);
Volatile.Write(ref _unknownCount, _unknownKeys.Count);
_predecessor = null;
@@ -415,6 +421,7 @@ public sealed partial class ProjectedConditionAccess
_unknownKeys.Clear();
_lastListed.Clear();
_sourceNames.Clear();
_heldSince.Clear();
Volatile.Write(ref _materialisedCount, 0);
Volatile.Write(ref _unknownCount, 0);
_owner._ledger.ResetClaims(ConnectionId);
@@ -550,12 +557,14 @@ public sealed partial class ProjectedConditionAccess
retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
retryArmedFor = null;
await RetryDueAsync(connection, states, context, snapshotTimeout).ConfigureAwait(false);
ExpireHeld(states);
}
foreach (var s in states)
if (s.RetryDue is null && s.Status is ProjectedConditionMappingStatus.Unavailable or ProjectedConditionMappingStatus.ConditionCapacity)
ScheduleRetry(s, snapshotTimeout);
var due = states.Where(x => x.RetryDue is not null).Select(x => x.RetryDue!.Value).DefaultIfEmpty().Min();
DateTimeOffset? wanted = states.Any(x => x.RetryDue is not null) ? due : null;
// #933: the earliest held-key expiry shares the retry timer (the loop re-checks both when it fires).
DateTimeOffset? wanted = states.Where(x => x.RetryDue is not null).Select(x => (DateTimeOffset?)x.RetryDue!.Value)
.Append(HeldExpiry()).Where(x => x is not null).Min();
if (wanted != retryArmedFor)
{
retryTimer?.Dispose(); retryTimer = null;
@@ -717,6 +726,20 @@ public sealed partial class ProjectedConditionAccess
}
}
/// <summary>#933: when the oldest held key reaches <c>MaxUnknownHold</c> (null when nothing is held).</summary>
private DateTimeOffset? HeldExpiry() => _heldSince.Count == 0 ? null : _heldSince.Values.Min() + _owner._options.MaxUnknownHold;
/// <summary>#933 (on the loop): re-decides the held keys whose bound passed — removed if still unlisted.</summary>
private void ExpireHeld(MappingState[] states)
{
if (_heldSince.Count == 0) return;
var now = _owner._clock.GetUtcNow();
var keys = _heldSince.Where(x => now - x.Value >= _owner._options.MaxUnknownHold).Select(x => x.Key).ToHashSet(StringComparer.Ordinal);
// Never leave an expired entry behind (it would re-arm the shared timer at once): a key no longer materialised goes.
foreach (var key in keys.Where(k => !_materialised.Contains(k)).ToArray()) { _heldSince.Remove(key); keys.Remove(key); }
if (keys.Count > 0) Reconcile(states, keys, full: false);
}
private void CountItem(MappingState state, bool open)
{
if (state.ItemCounted == open) return;
@@ -950,7 +973,8 @@ public sealed partial class ProjectedConditionAccess
/// Publishes <paramref name="keys"/> across the connection's committed sets. <paramref name="full"/> also re-diffs
/// everything materialised against the union (the barrier, a swap, a capacity reset, a late completion).
/// A key no contributing mapping lists is removed only when every mapping's set is known; while any is unknown
/// (Unavailable, not yet complete) it is kept with <c>BadNoCommunication</c> (unknown ≠ gone, §5.1 T2, B2).
/// (Unavailable, not yet complete) it is kept with <c>BadNoCommunication</c> (unknown ≠ gone, §5.1 T2, B2) — for at
/// most <c>MaxUnknownHold</c> per key (#933), then removed.
/// </summary>
/// <returns>How many conditions were removed (#931 N7: a removal already carries RefreshRequired to their holders).</returns>
private int Reconcile(MappingState[] states, HashSet<string> keys, bool full)
@@ -963,22 +987,34 @@ public sealed partial class ProjectedConditionAccess
foreach (var key in _materialised) if (!listed.Contains(key)) keys.Add(key);
}
var unknown = states.Any(x => !x.Known);
var now = _owner._clock.GetUtcNow();
var updates = new List<ImportedConditionUpdate>();
var removals = new List<string>();
var stale = new List<string>();
var expired = 0;
foreach (var key in keys)
{
var update = Merge(states, key);
if (update is not null)
{
updates.Add(update); _materialised.Add(key);
updates.Add(update); _materialised.Add(key); _heldSince.Remove(key);
if (update.State.StateKnown) _unknownKeys.Remove(key); else _unknownKeys.Add(key);
continue;
}
if (!_materialised.Contains(key)) continue;
if (unknown) stale.Add(key);
else { _materialised.Remove(key); _unknownKeys.Remove(key); _sourceNames.Remove(key); removals.Add(key); }
if (unknown)
{
// #933: the hold is bounded per key (MaxUnknownHold) — a durably Unavailable / Denied mapping no longer
// keeps a retired condition forever. Past the bound it is removed (+ RefreshRequired), never known-inactive.
if (!_heldSince.TryGetValue(key, out var since)) _heldSince[key] = since = now;
if (now - since < _owner._options.MaxUnknownHold) { stale.Add(key); continue; }
expired++;
}
_materialised.Remove(key); _unknownKeys.Remove(key); _sourceNames.Remove(key); _heldSince.Remove(key); removals.Add(key);
}
if (expired > 0)
_owner._log.LogWarning("Imported conditions: connection {Connection} removed {Count} condition(s) held past MaxUnknownHold ({Hold}) while mapping(s) {Mappings} stayed unknown",
ConnectionId, expired, _owner._options.MaxUnknownHold, string.Join(", ", states.Where(x => !x.Known).Select(x => x.MappingId + "=" + x.Status)));
Volatile.Write(ref _unknownCount, _unknownKeys.Count);
Volatile.Write(ref _materialisedCount, _materialised.Count);
if (removals.Count > 0) { sink.RemoveConditions(ConnectionId, removals); _owner.Diagnostics.ConsumerRefreshRequired(ConnectionId); }
@@ -986,7 +1022,7 @@ public sealed partial class ProjectedConditionAccess
if (updates.Count > 0) sink.ApplyConditions(updates);
// #931 N5: the held keys no contributing mapping lists are charged on top of the claims (counted on a full re-diff).
if (full) _unlisted = _materialised.Count(k => !listed!.Contains(k));
else _unlisted = Math.Min(_unlisted, _materialised.Count);
else _unlisted = Math.Max(0, Math.Min(_unlisted - expired, _materialised.Count)); // #933: expired keys were unlisted
if (!_owner._ledger.SetMaterialised(ConnectionId, _materialised.Count, _unlisted))
_owner._log.LogWarning("Imported conditions: connection {Connection} holds {Count} condition(s) and the node is over its host condition caps",
ConnectionId, _materialised.Count);
@@ -124,6 +124,19 @@ public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedC
/// </summary>
public TimeSpan MaxHold { get; init; } = TimeSpan.FromMinutes(5);
/// <summary>
/// #933: the longest a materialised condition that no KNOWN mapping lists is kept (<c>BadNoCommunication</c>) because
/// another mapping of the connection is unknown (Unavailable, Denied, retrying). Past it the condition is removed — a
/// removal with RefreshRequired, never "known inactive" (§5.1 T2) — and re-created if the unknown mapping lists it again.
/// Scoping the hold to "mappings that could list the key" is not provable on the consumer: a mapping lists a key when the
/// origin's CURRENT catalog places the condition under that mapping's root, and placements are origin deploy-time
/// configuration (a dropped key may have moved into the unknown mapping's scope). The default (20 min) is ~4× the longest
/// transient retry cycle at the default 30 s snapshot timeout (× 8 = 4 min, + the retry's own timeout) and spans the first
/// two in-stream re-checks of a definitive refusal (<see cref="LongRetryDelay"/> 5 min, then 10 min), so a transient
/// outage or a corrected grant never removes anything; only a durable one does.
/// </summary>
public TimeSpan MaxUnknownHold { get; init; } = TimeSpan.FromMinutes(20);
public static ProjectedConditionOptions Default { get; } =
new(TimeSpan.FromSeconds(30), 122_500, DefaultMaxImportedConditionBytes, TimeSpan.FromSeconds(1));
}
@@ -1097,6 +1097,43 @@ public sealed class GrpcDataProjectedConditionAccessTests
await f.WaitAsync(() => f.Access.ChargedConditions == 0);
}
// ---------------------------------------------------------------------------------------------------------------------
// Follow-ups #933 / #934 (A4 review)
// ---------------------------------------------------------------------------------------------------------------------
[Fact]
public async Task Issue933_a_key_held_for_a_durably_denied_mapping_is_removed_past_MaxUnknownHold_not_kept_forever()
{
var hold = TimeSpan.FromSeconds(1.5);
await using var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = TimeSpan.FromMinutes(5), MaxUnknownHold = hold },
("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack(DataItemStatus.Denied, "map-b"); // durable: retried only on the 5 min long timer
stream.Begin("map-a", total: 1);
stream.Records("map-a", Record(Key("x"), 3));
stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
// map-a retires x; map-b is unknown, so x is held stale (T2) — the stale mark is the must-arrive control.
stream.Records("map-a", Record(Key("x"), 4, removed: true));
await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
var heldAt = DateTime.UtcNow;
f.Sink.Removed.ShouldBeEmpty("within the bound an unknown mapping still holds the key");
// …and past the bound it is removed (+ RefreshRequired at the sink), on the open stream, with no frame to prompt it.
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
(DateTime.UtcNow - heldAt).ShouldBeGreaterThan(hold - TimeSpan.FromMilliseconds(200), "not before MaxUnknownHold");
f.Sink.Removed.Count(k => k == Key("x")).ShouldBe(1);
f.Sink.Live.ShouldNotContain(Key("x"));
f.Access.MappingStatuses(Connection)!["map-b"].ShouldBe(ProjectedConditionMappingStatus.Unavailable, "still unknown");
(await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(200))).ShouldBeNull("the stream is kept");
// A later listing re-creates it (the removal was a removal, not a verdict on the condition's state).
stream.Records("map-a", Record(Key("x"), 5, message: "back"));
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
}
private sealed class Fixture : IAsyncDisposable
{
internal static readonly DataView DefaultRawPlacement =