fix(dataconn): #1026 the fake origin snapshots every item an Add carries (Two_demands_of_one_node flake)

Two_demands_of_one_node_in_one_cohort_both_renew_from_one_tick failed intermittently on merged master (a 60 s hang in
NextPublishedRenewal). Reproduced under CPU load (14 busy cores: 4 of 6 runs failed) with a failure dump of the
renewal state. Every failure showed the same thing, and it was not a deadlock: both renewals had committed
(RenewalStarted+2, RenewalSucceeded+2, joined=1, no claim left in _overlapRenewals), both demands were valid on the
same successor, but the cohort's attempt then ended "Renewal snapshot did not establish a complete baseline" and the
stream reopened (opens 2), with only one rebind snapshot ever published.

Cause: the test fixture. FakeSubscriptions answered an Add of several items with a snapshot value for the FIRST item
only. Whether the two demands' rebinds are re-added by one Add command or two depends on timing (they are batched
when both RenewedEvents are handled before the cohort flushes); in one command the second item had no baseline, which
the consumer treats as a failed renewal (by design), and the reopened stream's recovery Add again valued one item.
A real origin sends a value for every ready item of a snapshot. The fake now does the same (EmitValueCore takes the
handle; EmitValue/EmitValueWithoutSourceTimestamp keep the first-added item).

Tests: The_fake_origin_snapshots_every_item_one_add_command_carries (fails on the old fixture); the flaky test also
asserts the renewal kept the physical stream (Opens 1) and, on timeout, throws a dump of the published updates,
counter deltas, demand bindings and pending overlap claims instead of a bare 60 s cancellation.

Loops: the test 30/30 under 14-core load (was 2 of 6 passing); GrpcDataConfiguredDiscoveryWireTests 3/3 (160 each);
full Runtime.Tests (Category!=SlowUnit) 2387 passed, 0 failed.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-05 07:15:58 -05:00
parent 851b2b8c20
commit 23f7468b4b
2 changed files with 75 additions and 10 deletions
@@ -132,13 +132,73 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
(await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good);
while (published.Reader.TryRead(out _)) { }
var before = ProjectedStreamDiagnostics.Capture();
var stream = subscriptions.Opens;
await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromSeconds(9), ct, oneStep: true);
// Each registration rebinds onto the successor with its own fresh complete baseline (before the fix neither did: the
// batch waited for the joiner, the joiner for the batch's verdict). Whether the first rebind's witness is still valid
// once the second rebinds is the shared source's business, not this test's.
for (var i = 0; i < 2; i++)
await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct);
var seen = new List<string>();
var completes = 0;
using (var wait = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
wait.CancelAfter(TimeSpan.FromSeconds(20));
try
{
while (completes < 2)
{
var u = await published.Reader.ReadAsync(wait.Token);
seen.Add($"complete={u.IsCompleteSnapshot} v={u.SourceVersion} route={u.Route.GetHashCode():x} proof={u.SourceProof.GetHashCode():x} valid={u.SourceProof.IsValid} late={u.ReceivedTimestamp > original.ReceivedTimestamp}");
if (u.IsCompleteSnapshot && u.ReceivedTimestamp > original.ReceivedTimestamp) completes++;
}
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
var after = ProjectedStreamDiagnostics.Capture();
var delta = after.Where(kv => kv.Value != before.GetValueOrDefault(kv.Key)).Select(kv => $"{kv.Key}+{kv.Value - before.GetValueOrDefault(kv.Key)}");
const System.Reflection.BindingFlags f = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
var gate = typeof(ProjectedDataAccess).GetField("_sync", f)!.GetValue(access)!;
string demands, overlaps;
lock (gate)
{
demands = string.Join(" | ", ((System.Collections.IEnumerable)typeof(ProjectedDataAccess).GetField("_demands", f)!.GetValue(access)!).Cast<object>()
.Select(d => { var b = d.GetType().GetProperty("CurrentBinding", f)!.GetValue(d)!;
return $"valid={((ZB.MOM.WW.OtOpcUa.OpcUaServer.IProjectedDemandLease)d).IsValid} proof={b.GetType().GetProperty("Proof")!.GetValue(b)!.GetHashCode():x} recov={b.GetType().GetProperty("RecoveryOnly")!.GetValue(b)}"; }));
overlaps = ((System.Collections.ICollection)typeof(ProjectedDataAccess).GetField("_overlapRenewals", f)!.GetValue(access)!).Count.ToString();
}
throw new TimeoutException($"completes={completes} joined={access.OverlapRenewalsJoinedForTests} opens={subscriptions.Opens}/{stream} " +
$"overlaps={overlaps}\nseen:\n{string.Join("\n", seen)}\ndelta: {string.Join(", ", delta)}\ndemands: {demands}");
}
}
access.OverlapRenewalsJoinedForTests.ShouldBe(1, "the second demand joined the first one's renewal");
subscriptions.Opens.ShouldBe(1, "a renewal rebinds on the same physical stream; it never ends the cohort's attempt");
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
}
/// <summary>
/// #1026 (flake root cause): the fake origin must answer an Add of several items with a snapshot value for EACH, as a real
/// origin does for ready sources. It answered with the first item's only, so when both demands of one node rebound in ONE
/// Add (the renewals completed in the same batch, timing-dependent) the second had no baseline, the cohort ended its
/// attempt ("Renewal snapshot did not establish a complete baseline") and the test above waited for a snapshot that the
/// reopened stream again sent for one item only.
/// </summary>
[Fact, Trait("Issue", "1026")]
public async Task The_fake_origin_snapshots_every_item_one_add_command_carries()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(servingGeneration: 1);
var subscriptions = new FakeSubscriptions(() => origin.Serving) { SampleClock = origin.Clock };
await using var stream = await subscriptions.SubscribeAsync(ct);
var settings = new DataSubscriptionSettings(TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100),
ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataChangeTrigger.StatusValueTimestamp, null);
await stream.SendAsync(new AddSubscriptionItems("s", 1, "c1", TimeSpan.FromSeconds(5),
[new DataSubscriptionItem("a", origin.Raw, settings), new DataSubscriptionItem("b", origin.Raw, settings)]), ct);
var handles = new List<DataItemHandle>();
var acked = new List<DataItemHandle>();
await foreach (var frame in stream.ReadAllAsync(ct))
{
if (frame is DataSubscriptionAck ack) acked.AddRange(ack.Items.Select(item => item.Handle!));
else if (frame is DataSubscriptionValues { IsSnapshot: true } values) handles.AddRange(values.Items.Select(item => item.Handle));
else if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) break;
}
acked.Count.ShouldBe(2);
handles.ShouldBe(acked, ignoreOrder: true, "each added item gets its own snapshot value before the snapshot ends");
}
}
@@ -276,8 +276,13 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
Interval = items[0].Settings.PublishingInterval;
_currentHandle = acks[0].Handle;
_frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotBegin, [], serving.CatalogEpoch, serving.AuthorityEpoch, null));
// #1026: like a real origin, the snapshot carries a value for EVERY item the command added. It used to carry
// one (the first): two items re-added by one command (two demands of one node rebinding after one renewal)
// left the second without a baseline, which ends the cohort's attempt as a failed renewal.
if (owner.SampleClock is { } clock)
EmitValueCore(owner.SnapshotVersion, owner.SnapshotValue, clock.GetUtcNow(), TimeSpan.Zero, snapshot: true);
foreach (var ack in acks)
if (ack.Handle is { } snapshotHandle)
EmitValueCore(snapshotHandle, owner.SnapshotVersion, owner.SnapshotValue, clock.GetUtcNow(), TimeSpan.Zero, snapshot: true);
if (owner.HoldNextSnapshotEnd)
{
owner.HoldNextSnapshotEnd = false; _snapshotEndHeld = true;
@@ -291,19 +296,19 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
}
public void EmitValue(long version, int value, DateTimeOffset sourceTimestamp, TimeSpan age)
{
lock (_gate) EmitValueCore(version, value, sourceTimestamp, age, snapshot: false);
lock (_gate) EmitValueCore(_currentHandle!, version, value, sourceTimestamp, age, snapshot: false);
}
public void EmitValueWithoutSourceTimestamp(long version, int value, TimeSpan age)
{
lock (_gate) EmitValueCore(version, value, null, age, snapshot: false);
lock (_gate) EmitValueCore(_currentHandle!, version, value, null, age, snapshot: false);
}
private void EmitValueCore(long version, int value, DateTimeOffset? sourceTimestamp, TimeSpan age, bool snapshot)
private void EmitValueCore(DataItemHandle handle, long version, int value, DateTimeOffset? sourceTimestamp, TimeSpan age, bool snapshot)
{
var sample = new DataSample(
ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(DataValueKind.Int32, value),
0, sourceTimestamp, sourceTimestamp, serving, version);
_frames.Writer.TryWrite(new DataSubscriptionValues(_subscriptionId!, _epoch, ++_sequence, snapshot,
[new DataSubscriptionValue(_currentHandle!, sample, new(age, age), DataReadiness.Ready)]));
[new DataSubscriptionValue(handle, sample, new(age, age), DataReadiness.Ready)]));
}
private void EndSnapshot() => _frames.Writer.TryWrite(new DataSubscriptionControl(_subscriptionId!, _epoch,
++_sequence, DataStreamControlKind.SnapshotEnd, [], serving.CatalogEpoch, serving.AuthorityEpoch, null));