fix(grpc-data): A1 review S3 + S4 + nits — snapshot start cursor, readiness cut with the snapshot, failed applies
- S3a: SnapshotConditions reads a start cursor under Lock before enumerating keys; every slice carries it, so a condition materialised and activated between the enumeration and slice 1's hold is covered by deltas after it. - S3b: each hold captures the apply generation (bumped when a rebuild begins) and the complete flag; slices carry them and ConditionSnapshotSlice.IsCompleteSnapshot / ConditionStateHub.IsSnapshotCompleteFor detect a rebuild that straddles a multi-slice snapshot. An empty scope still takes one hold. - S3c: maxConditionsPerHold is clamped to MaxConditionsPerHoldLimit (5,000). - S4: CompleteAddressSpaceApply(bool succeeded) (new default sink member, forwarded by the deferred and SDK sinks); the publish actor passes !Degraded. A failed/degraded rebuild keeps readiness false and its pending removals, emitting no removal records; the next successful apply completes it. - Nits: ConditionStateRecord.UnshelveTimeUtc (timed-shelve expiry); ConditionStateHub.Read has a bounded default.
This commit is contained in:
@@ -88,6 +88,9 @@ public sealed class DeferredAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgical
|
||||
/// <inheritdoc />
|
||||
public void CompleteAddressSpaceApply() => _inner.CompleteAddressSpaceApply();
|
||||
|
||||
/// <inheritdoc />
|
||||
public void CompleteAddressSpaceApply(bool succeeded) => _inner.CompleteAddressSpaceApply(succeeded);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void MarkConditionsKnown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
|
||||
=> _inner.MarkConditionsKnown(source, conditionIds, realm);
|
||||
|
||||
@@ -213,6 +213,15 @@ public interface IOpcUaAddressSpaceSink
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="CompleteAddressSpaceApply()"/> with the apply's outcome (A1 review S4): <paramref name="succeeded"/>
|
||||
/// is false for a throwing or degraded apply, and an SDK-backed sink then keeps a rebuild's condition-set
|
||||
/// readiness withheld and emits no removal records for conditions the failed pass did not re-materialise. The
|
||||
/// default forwards to the parameterless overload.
|
||||
/// </summary>
|
||||
/// <param name="succeeded">Whether the apply completed cleanly.</param>
|
||||
void CompleteAddressSpaceApply(bool succeeded) => CompleteAddressSpaceApply();
|
||||
|
||||
/// <summary>
|
||||
/// A1 (plan §5.1 T1/T2): the state of <paramref name="conditionIds"/> has been ESTABLISHED by
|
||||
/// <paramref name="source"/> (a driver's <c>InitialAlarmStateDelivered</c>, its backstop timer, or a scripted
|
||||
|
||||
@@ -39,6 +39,8 @@ public readonly record struct ConditionActivationMarker(string Incarnation, ulon
|
||||
/// <param name="Activation">The origin-owned activation marker (T3).</param>
|
||||
/// <param name="Comment">The condition's Comment text, if any.</param>
|
||||
/// <param name="ClientUserId">Who left that comment, if recorded.</param>
|
||||
/// <param name="UnshelveTimeUtc">For a timed shelve, the absolute UTC expiry (A2 projects the remaining time from it);
|
||||
/// otherwise null.</param>
|
||||
public sealed record ConditionStateRecord(
|
||||
AddressSpaceRealm Realm,
|
||||
string ConditionId,
|
||||
@@ -59,7 +61,8 @@ public sealed record ConditionStateRecord(
|
||||
bool Retain,
|
||||
ConditionActivationMarker Activation,
|
||||
string? Comment = null,
|
||||
string? ClientUserId = null);
|
||||
string? ClientUserId = null,
|
||||
DateTime? UnshelveTimeUtc = null);
|
||||
|
||||
/// <summary>
|
||||
/// The node manager's SDK-free delta callback (plan §5.1). Implemented by the Runtime's <c>ConditionStateHub</c>.
|
||||
@@ -95,4 +98,34 @@ public interface IConditionStateSink
|
||||
/// </summary>
|
||||
/// <param name="Watermark">The sink's watermark taken under the same hold.</param>
|
||||
/// <param name="Records">The copied records (each carries <see cref="Watermark"/> as its version).</param>
|
||||
public sealed record ConditionSnapshotSlice(long Watermark, IReadOnlyList<ConditionStateRecord> Records);
|
||||
/// <param name="StartCursor">
|
||||
/// The watermark read BEFORE the snapshot enumerated its keys (the same for every slice of one snapshot). A condition
|
||||
/// no slice holds — materialised after the enumeration — is covered by its deltas after this cursor.
|
||||
/// </param>
|
||||
/// <param name="ApplyGeneration">The node manager's apply generation (bumped when a rebuild begins) under this hold.</param>
|
||||
/// <param name="ApplyComplete">Whether the address-space apply was complete under this hold.</param>
|
||||
public sealed record ConditionSnapshotSlice(
|
||||
long Watermark,
|
||||
IReadOnlyList<ConditionStateRecord> Records,
|
||||
long StartCursor = 0,
|
||||
long ApplyGeneration = 0,
|
||||
bool ApplyComplete = false)
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether the slices form a complete snapshot of the condition SET: every hold saw a completed apply of ONE
|
||||
/// generation (review S3b — readiness atomic with the cut). False when a rebuild began during, or straddled, a
|
||||
/// multi-slice snapshot: the caller retakes it (and keeps sending <c>NotReady</c>). The Primary verdict is the
|
||||
/// caller's to combine.
|
||||
/// </summary>
|
||||
/// <param name="slices">One snapshot's slices.</param>
|
||||
/// <returns><see langword="true"/> when complete and consistent.</returns>
|
||||
public static bool IsCompleteSnapshot(IReadOnlyList<ConditionSnapshotSlice> slices)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(slices);
|
||||
if (slices.Count == 0) return false; // SnapshotConditions always returns at least one slice
|
||||
var generation = slices[0].ApplyGeneration;
|
||||
foreach (var s in slices)
|
||||
if (!s.ApplyComplete || s.ApplyGeneration != generation) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,12 @@ public sealed partial class OtOpcUaNodeManager
|
||||
/// <summary>The default most conditions one snapshot <c>Lock</c> hold copies (§5.5 <c>MaxConditions</c>).</summary>
|
||||
public const int DefaultMaxConditionsPerHold = 1000;
|
||||
|
||||
/// <summary>
|
||||
/// The upper bound a caller's <c>maxConditionsPerHold</c> is clamped to (review S3c): at the measured
|
||||
/// ≈ 1.7–2.9 µs per condition (§5.1) one hold stays ≈ 9–15 ms, whatever a mapping configures.
|
||||
/// </summary>
|
||||
public const int MaxConditionsPerHoldLimit = 5000;
|
||||
|
||||
/// <summary>Per-condition activation bookkeeping: the occurrence sequence plus the Active/Acked basis it was
|
||||
/// last compared against. Mutable, only touched under <c>Lock</c>.</summary>
|
||||
private sealed class ActivationEntry
|
||||
@@ -35,6 +41,11 @@ public sealed partial class OtOpcUaNodeManager
|
||||
// a consumer retire a condition that is still active at the origin).
|
||||
private readonly HashSet<RealmKey> _rebuildPendingRemoval = new();
|
||||
private bool _conditionApplyComplete;
|
||||
// Bumped when a rebuild begins; captured under each snapshot hold so a caller can detect a rebuild that
|
||||
// straddles a multi-slice snapshot (review S3b).
|
||||
private long _conditionApplyGeneration;
|
||||
// The absolute expiry of each timed-shelved condition (set by WriteAlarmCondition), for the record's UnshelveTimeUtc.
|
||||
private readonly Dictionary<RealmKey, DateTime> _conditionUnshelveAt = new();
|
||||
|
||||
/// <summary>The serving incarnation the activation markers are minted under (one per node-manager lifetime).</summary>
|
||||
internal string ConditionIncarnation { get; set; } = Guid.NewGuid().ToString("N");
|
||||
@@ -42,6 +53,9 @@ public sealed partial class OtOpcUaNodeManager
|
||||
/// <summary>Test seam: invoked after each snapshot <c>Lock</c> hold (outside it) with the records that hold copied.</summary>
|
||||
internal Action<int>? OnConditionSnapshotHold { get; set; }
|
||||
|
||||
/// <summary>Test seam: invoked after a snapshot enumerated its keys and before its first hold (outside <c>Lock</c>).</summary>
|
||||
internal Action? OnConditionSnapshotKeysEnumerated { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The SDK-free condition-state delta callback (the Runtime's <c>ConditionStateHub</c>). Null = no hub; the
|
||||
/// known flags and activation markers are still maintained. Set once at host start.
|
||||
@@ -149,29 +163,45 @@ public sealed partial class OtOpcUaNodeManager
|
||||
/// snapshot defines the SET), never more than <paramref name="maxConditionsPerHold"/> per <c>Lock</c> hold.
|
||||
/// Each slice carries the sink's watermark taken under the same hold, so a delta is either inside the slice or
|
||||
/// after its watermark. A consumer must register for deltas before snapshotting.
|
||||
/// <para>Review S3: every slice also carries <see cref="ConditionSnapshotSlice.StartCursor"/> — the watermark
|
||||
/// read under <c>Lock</c> BEFORE the keys are enumerated — so a condition materialised (and activated) after
|
||||
/// that point, which no slice holds, is covered by the deltas after the start cursor; and the apply generation +
|
||||
/// complete flag captured under that slice's hold, so a caller can tell a snapshot cut during or across a
|
||||
/// rebuild (<see cref="ConditionSnapshotSlice.IsCompleteSnapshot"/>).</para>
|
||||
/// </summary>
|
||||
/// <param name="scope">Realm + id filter (an export's root); evaluated outside <c>Lock</c>.</param>
|
||||
/// <param name="maxConditionsPerHold">The most conditions one hold copies (≥ 1).</param>
|
||||
/// <param name="maxConditionsPerHold">The most conditions one hold copies (≥ 1; clamped to
|
||||
/// <see cref="MaxConditionsPerHoldLimit"/>).</param>
|
||||
/// <returns>The slices in ascending (realm, id) order.</returns>
|
||||
public IReadOnlyList<ConditionSnapshotSlice> SnapshotConditions(
|
||||
Func<AddressSpaceRealm, string, bool> scope, int maxConditionsPerHold = DefaultMaxConditionsPerHold)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(scope);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(maxConditionsPerHold, 1);
|
||||
maxConditionsPerHold = Math.Min(maxConditionsPerHold, MaxConditionsPerHoldLimit);
|
||||
|
||||
long startCursor;
|
||||
lock (Lock) startCursor = _conditionStateSink?.Watermark ?? 0;
|
||||
|
||||
// Key enumeration and the scope filter run OFF Lock (the map is concurrent and keys are immutable); a
|
||||
// condition added after this point is not in the snapshot but its materialise record is a delta.
|
||||
var keys = _alarmConditions.Keys.Where(k => scope(k.Realm, k.Id))
|
||||
.OrderBy(k => k.Realm).ThenBy(k => k.Id, StringComparer.Ordinal).ToList();
|
||||
var slices = new List<ConditionSnapshotSlice>((keys.Count + maxConditionsPerHold - 1) / maxConditionsPerHold);
|
||||
for (var start = 0; start < keys.Count; start += maxConditionsPerHold)
|
||||
OnConditionSnapshotKeysEnumerated?.Invoke();
|
||||
// At least one hold even for an empty scope: an empty SET is a snapshot too, and its readiness must be cut.
|
||||
var sliceCount = Math.Max(1, (keys.Count + maxConditionsPerHold - 1) / maxConditionsPerHold);
|
||||
var slices = new List<ConditionSnapshotSlice>(sliceCount);
|
||||
for (var start = 0; slices.Count < sliceCount; start += maxConditionsPerHold)
|
||||
{
|
||||
var end = Math.Min(start + maxConditionsPerHold, keys.Count);
|
||||
var records = new List<ConditionStateRecord>(end - start);
|
||||
long watermark;
|
||||
long watermark, generation;
|
||||
bool applyComplete;
|
||||
lock (Lock)
|
||||
{
|
||||
watermark = _conditionStateSink?.Watermark ?? 0;
|
||||
generation = _conditionApplyGeneration;
|
||||
applyComplete = _conditionApplyComplete;
|
||||
for (var i = start; i < end; i++)
|
||||
{
|
||||
if (_alarmConditions.TryGetValue(keys[i], out var condition))
|
||||
@@ -180,7 +210,7 @@ public sealed partial class OtOpcUaNodeManager
|
||||
}
|
||||
|
||||
OnConditionSnapshotHold?.Invoke(records.Count);
|
||||
slices.Add(new ConditionSnapshotSlice(watermark, records));
|
||||
slices.Add(new ConditionSnapshotSlice(watermark, records, startCursor, generation, applyComplete));
|
||||
}
|
||||
|
||||
return slices;
|
||||
@@ -205,6 +235,7 @@ public sealed partial class OtOpcUaNodeManager
|
||||
private void ForgetConditionState(RealmKey key, AlarmConditionState condition)
|
||||
{
|
||||
_conditionStateKnown.Remove(key);
|
||||
_conditionUnshelveAt.Remove(key);
|
||||
_activation.Remove(key, out var entry);
|
||||
_conditionStateSink?.Append(BuildConditionRecord(key, condition, 0, removed: true, entry));
|
||||
}
|
||||
@@ -213,8 +244,10 @@ public sealed partial class OtOpcUaNodeManager
|
||||
private void CaptureConditionStateForRebuild()
|
||||
{
|
||||
_conditionApplyComplete = false;
|
||||
_conditionApplyGeneration++;
|
||||
_conditionStateSink?.OnApplyStateChanged(false);
|
||||
_rebuildScriptedActivation.Clear();
|
||||
_conditionUnshelveAt.Clear();
|
||||
foreach (var key in _alarmConditions.Keys)
|
||||
{
|
||||
_rebuildPendingRemoval.Add(key);
|
||||
@@ -228,8 +261,23 @@ public sealed partial class OtOpcUaNodeManager
|
||||
|
||||
/// <summary>Under <c>Lock</c>, at <c>CompleteAddressSpaceApply</c>: announce the conditions the rebuild dropped
|
||||
/// for good, forget the rebuild memory and mark the apply complete.</summary>
|
||||
private void CompleteConditionApply()
|
||||
/// <param name="succeeded">
|
||||
/// Review S4: false for a throwing or degraded apply. Then a rebuild in progress is NOT completed: readiness
|
||||
/// stays false and the pending-removal set is kept, so no removal record is emitted for a condition the failed
|
||||
/// pass simply did not re-materialise (a consumer would retire a condition that may still be active). The
|
||||
/// next successful apply completes it.
|
||||
/// </param>
|
||||
private void CompleteConditionApply(bool succeeded)
|
||||
{
|
||||
if (!succeeded)
|
||||
{
|
||||
if (!_conditionApplyComplete)
|
||||
_logger.LogWarning(
|
||||
"OtOpcUaNodeManager: the address-space apply failed or was degraded — condition snapshot readiness withheld and {Pending} pending removal(s) kept until an apply succeeds",
|
||||
_rebuildPendingRemoval.Count);
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var key in _rebuildPendingRemoval)
|
||||
{
|
||||
if (_alarmConditions.ContainsKey(key)) continue;
|
||||
@@ -305,6 +353,7 @@ public sealed partial class OtOpcUaNodeManager
|
||||
c.Retain?.Value == true,
|
||||
new ConditionActivationMarker(ConditionIncarnation, entry?.Sequence ?? 0),
|
||||
c.Comment?.Value.Text,
|
||||
c.ClientUserId?.Value);
|
||||
c.ClientUserId?.Value,
|
||||
delta.Shelving == AlarmShelvingKind.Timed && _conditionUnshelveAt.TryGetValue(key, out var unshelveAt) ? unshelveAt : null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1373,6 +1373,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
{
|
||||
condition.SetConfirmedState(SystemContext, state.Confirmed);
|
||||
}
|
||||
// A1 review nit: the absolute timed-shelve expiry rides the condition-state record (A2 projects it).
|
||||
if (state.Shelving == AlarmShelvingKind.Timed && state.UnshelveAtUtc is { } unshelveAt) _conditionUnshelveAt[key] = unshelveAt;
|
||||
else _conditionUnshelveAt.Remove(key);
|
||||
if (condition.ShelvingState is not null)
|
||||
{
|
||||
// SetShelvingState(shelved, oneShot, shelvingTime): map our 3-way kind onto the SDK's
|
||||
@@ -5683,7 +5686,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
// re-assert does), then discards whatever captured state no materialise claimed. A condition the apply
|
||||
// replaced again after restoring it is skipped: the instance reported must be the one restored.
|
||||
/// <inheritdoc cref="IOpcUaAddressSpaceSink.CompleteAddressSpaceApply"/>
|
||||
public void CompleteAddressSpaceApply()
|
||||
public void CompleteAddressSpaceApply() => CompleteAddressSpaceApply(succeeded: true);
|
||||
|
||||
/// <inheritdoc cref="IOpcUaAddressSpaceSink.CompleteAddressSpaceApply(bool)"/>
|
||||
public void CompleteAddressSpaceApply(bool succeeded)
|
||||
{
|
||||
int reported = 0, discarded;
|
||||
lock (Lock)
|
||||
@@ -5701,7 +5707,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
discarded = _rebuildCarryOver.Count;
|
||||
_restoredConditionReports.Clear();
|
||||
_rebuildCarryOver.Clear();
|
||||
CompleteConditionApply();
|
||||
CompleteConditionApply(succeeded);
|
||||
}
|
||||
|
||||
if (reported > 0 || discarded > 0)
|
||||
|
||||
@@ -141,6 +141,9 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre
|
||||
/// <inheritdoc />
|
||||
public void CompleteAddressSpaceApply() => _nodeManager.CompleteAddressSpaceApply();
|
||||
|
||||
/// <inheritdoc />
|
||||
public void CompleteAddressSpaceApply(bool succeeded) => _nodeManager.CompleteAddressSpaceApply(succeeded);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void MarkConditionsKnown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
|
||||
=> _nodeManager.MarkConditionsKnown(source, conditionIds, realm);
|
||||
|
||||
@@ -41,6 +41,9 @@ public sealed class ConditionStateHub : IConditionStateSink
|
||||
/// <summary>Default per-partition buffer capacity (records).</summary>
|
||||
public const int DefaultPartitionCapacity = 8192;
|
||||
|
||||
/// <summary>The default most records one <see cref="Read"/> returns (review nit: bounded, not <c>int.MaxValue</c>).</summary>
|
||||
public const int DefaultReadMax = 1024;
|
||||
|
||||
private sealed class Partition
|
||||
{
|
||||
public readonly object Gate = new();
|
||||
@@ -82,6 +85,16 @@ public sealed class ConditionStateHub : IConditionStateSink
|
||||
/// <summary><c>snapshot_complete</c> may be sent: apply complete AND this node is Primary.</summary>
|
||||
public bool IsSnapshotComplete => _applyComplete && _primary?.ShouldActAsPrimary == true;
|
||||
|
||||
/// <summary>
|
||||
/// <c>snapshot_complete</c> for ONE taken snapshot (review S3b): readiness read atomically with the cut — every
|
||||
/// slice's hold saw a completed apply of one generation — AND this node is Primary. Prefer this over
|
||||
/// <see cref="IsSnapshotComplete"/>, which a rebuild can flip between the read and the snapshot.
|
||||
/// </summary>
|
||||
/// <param name="slices">The snapshot's slices (<c>OtOpcUaNodeManager.SnapshotConditions</c>).</param>
|
||||
/// <returns>Whether that snapshot may be sent as complete.</returns>
|
||||
public bool IsSnapshotCompleteFor(IReadOnlyList<ConditionSnapshotSlice> slices) =>
|
||||
ConditionSnapshotSlice.IsCompleteSnapshot(slices) && _primary?.ShouldActAsPrimary == true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public long Append(ConditionStateRecord record)
|
||||
{
|
||||
@@ -134,8 +147,9 @@ public sealed class ConditionStateHub : IConditionStateSink
|
||||
/// <param name="afterVersion">The reader's cursor (the slice watermark or the last version it applied).</param>
|
||||
/// <param name="max">The most records to return.</param>
|
||||
/// <returns>The read.</returns>
|
||||
public ConditionDeltaRead Read(int partition, long afterVersion, int max = int.MaxValue)
|
||||
public ConditionDeltaRead Read(int partition, long afterVersion, int max = DefaultReadMax)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(max, 1);
|
||||
var p = _partitions[partition];
|
||||
lock (p.Gate)
|
||||
{
|
||||
@@ -160,7 +174,7 @@ public sealed class ConditionStateHub : IConditionStateSink
|
||||
var all = new List<ConditionStateRecord>();
|
||||
for (var i = 0; i < _partitions.Length; i++)
|
||||
{
|
||||
var read = Read(i, afterVersion);
|
||||
var read = Read(i, afterVersion, DefaultPartitionCapacity);
|
||||
if (read.ResetRequired) return null;
|
||||
all.AddRange(read.Records);
|
||||
}
|
||||
|
||||
@@ -1345,7 +1345,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
/// </summary>
|
||||
private void FinishRebuild(RebuildAddressSpace msg, IActorRef requester, (bool Degraded, string? Reason) outcome)
|
||||
{
|
||||
try { _sink.CompleteAddressSpaceApply(); }
|
||||
// A1 review S4: a degraded/throwing apply must not complete a rebuild's condition set (no removal records for
|
||||
// conditions it failed to re-materialise, readiness stays withheld).
|
||||
try { _sink.CompleteAddressSpaceApply(succeeded: !outcome.Degraded); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Error(ex, "OpcUaPublish: sink.CompleteAddressSpaceApply threw (correlation={Correlation})", msg.Correlation);
|
||||
|
||||
Reference in New Issue
Block a user