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:
Joseph Doherty
2026-11-24 10:43:04 -05:00
parent 6c94a2ec0e
commit 16166c21e5
10 changed files with 274 additions and 14 deletions
@@ -302,6 +302,118 @@ public sealed class ConditionStateNodeManagerTests : IDisposable
await host.DisposeAsync();
}
/// <summary>Review S3a: a condition materialised and activated between the key enumeration and slice 1's hold is in
/// no slice, and its records are after the snapshot's START cursor — the slice watermark alone would hide them.</summary>
[Fact]
public async Task S3a_A_condition_materialised_after_the_enumeration_is_covered_by_deltas_after_the_start_cursor()
{
var (host, nm, sink) = await BootAsync();
MaterialiseAll(nm);
nm.CompleteAddressSpaceApply();
const string Late = Device + "/Late";
nm.OnConditionSnapshotKeysEnumerated = () =>
{
nm.MaterialiseAlarmCondition(Late, Device, "Late", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
nm.WriteAlarmCondition(Late, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
};
var slices = nm.SnapshotConditions((_, _) => true);
slices.SelectMany(x => x.Records).ShouldNotContain(r => r.ConditionId == Late);
slices.ShouldAllBe(x => x.StartCursor == slices[0].StartCursor);
var late = sink.Records.Where(r => r.ConditionId == Late).ToList();
late.ShouldNotBeEmpty();
late.ShouldAllBe(r => r.Version > slices[0].StartCursor);
late.ShouldAllBe(r => r.Version <= slices[0].Watermark); // why the start cursor is needed
await host.DisposeAsync();
}
/// <summary>Review S3b: readiness is cut with the snapshot — a rebuild that straddles a multi-slice snapshot (even one
/// that completes before the last hold) makes it incomplete; one inside a single apply generation is complete.</summary>
[Fact]
public async Task S3b_A_rebuild_straddling_a_multi_slice_snapshot_makes_it_incomplete()
{
var (host, nm, _) = await BootAsync();
MaterialiseAll(nm);
ConditionSnapshotSlice.IsCompleteSnapshot(nm.SnapshotConditions((_, _) => true, 1)).ShouldBeFalse(); // not applied yet
nm.CompleteAddressSpaceApply();
ConditionSnapshotSlice.IsCompleteSnapshot(nm.SnapshotConditions((_, _) => true, 1)).ShouldBeTrue();
var holds = 0;
nm.OnConditionSnapshotHold = _ =>
{
if (++holds != 1) return;
nm.RebuildAddressSpace();
MaterialiseAll(nm);
nm.CompleteAddressSpaceApply();
};
var slices = nm.SnapshotConditions((_, _) => true, maxConditionsPerHold: 1);
slices.Count.ShouldBe(3);
slices.ShouldAllBe(x => x.ApplyComplete); // each hold alone looks ready …
ConditionSnapshotSlice.IsCompleteSnapshot(slices).ShouldBeFalse(); // … but the cut spans two generations
await host.DisposeAsync();
}
/// <summary>Review S3c: a caller's per-hold maximum is clamped to <see cref="OtOpcUaNodeManager.MaxConditionsPerHoldLimit"/>.</summary>
[Fact]
public async Task S3c_MaxConditions_per_hold_is_clamped()
{
var (host, nm, _) = await BootAsync();
nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw);
for (var i = 0; i <= OtOpcUaNodeManager.MaxConditionsPerHoldLimit; i++)
nm.MaterialiseAlarmCondition($"{Device}/C{i:00000}", Device, $"C{i:00000}", "OffNormalAlarm", 500, AddressSpaceRealm.Raw, isNative: true);
var holds = new List<int>();
nm.OnConditionSnapshotHold = holds.Add;
nm.SnapshotConditions((_, _) => true, maxConditionsPerHold: int.MaxValue);
holds.ShouldBe([OtOpcUaNodeManager.MaxConditionsPerHoldLimit, 1]);
await host.DisposeAsync();
}
/// <summary>Review S4: a failed/degraded rebuild apply neither emits removal records for the conditions it did not
/// re-materialise nor flips readiness; the next successful apply completes it.</summary>
[Fact]
public async Task S4_A_failed_rebuild_apply_emits_no_removals_and_keeps_readiness_withheld()
{
var (host, nm, sink) = await BootAsync();
MaterialiseAll(nm);
nm.CompleteAddressSpaceApply();
nm.RebuildAddressSpace();
nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw);
nm.MaterialiseAlarmCondition(Native, Device, "TankHi", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
var before = sink.Records.Count;
nm.CompleteAddressSpaceApply(succeeded: false); // the pass threw before re-creating Native2 and the scripted one
sink.Records.Skip(before).ShouldNotContain(r => r.Removed);
sink.ApplyComplete.ShouldBe(false);
nm.IsConditionApplyComplete.ShouldBeFalse();
nm.CompleteAddressSpaceApply(succeeded: true); // a later successful apply (that also dropped them)
sink.Records.Skip(before).Where(r => r.Removed).Select(r => r.ConditionId).ShouldBe([Native2, Scripted], ignoreOrder: true);
sink.ApplyComplete.ShouldBe(true);
await host.DisposeAsync();
}
/// <summary>Review nit: a timed shelve's absolute expiry rides the record (A2 projects the remaining time).</summary>
[Fact]
public async Task A_timed_shelve_record_carries_its_UnshelveTime()
{
var (host, nm, sink) = await BootAsync();
MaterialiseAll(nm);
var at = DateTime.UtcNow.AddMinutes(5);
nm.WriteAlarmCondition(Scripted, State(true, false) with { Shelving = AlarmShelvingKind.Timed, UnshelveAtUtc = at },
DateTime.UtcNow, AddressSpaceRealm.Uns);
sink.Records.Last().ShouldSatisfyAllConditions(
r => r.Shelving.ShouldBe(AlarmShelvingKind.Timed), r => r.UnshelveTimeUtc.ShouldBe(at));
nm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns);
sink.Records.Last().UnshelveTimeUtc.ShouldBeNull();
AssertParity(nm, sink);
await host.DisposeAsync();
}
// ---------------------------------------------------------------- helpers
private static void MaterialiseAll(OtOpcUaNodeManager nm)
@@ -148,6 +148,27 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase
cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>Review S4: a throwing apply completes with <c>succeeded: false</c> (the node manager then keeps the
/// rebuild's readiness withheld and emits no removals); a clean one with <c>true</c>.</summary>
[Fact]
public void A_throwing_apply_completes_the_address_space_apply_as_failed()
{
var sink = new OrderSink();
var fail = true;
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance),
new OpcUaPublishActor.TestHooks { BeforePlan = () => { if (fail) throw new InvalidOperationException("boom"); } }));
actor.Tell(Rebuild());
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
AwaitAssert(() => sink.Completions.ShouldBe([false]), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
fail = false;
actor.Tell(Rebuild());
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
AwaitAssert(() => sink.Completions.ShouldBe([false, true]), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
}
private IActorRef Spawn(OrderSink sink, ManualResetEventSlim gate) =>
Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance),
@@ -238,6 +259,14 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase
lock (_gate) _conditions.Add(alarmNodeId);
}
public List<bool> Completions { get { lock (_gate) return [.. _completions]; } }
private readonly List<bool> _completions = new();
public void CompleteAddressSpaceApply(bool succeeded)
{
lock (_gate) _completions.Add(succeeded);
}
public void RebuildAddressSpace()
{
lock (_gate) { _conditions.Clear(); _known.Clear(); }