fix(grpc-data): a demand disposed mid-publish no longer re-publishes a fresh baseline (#920)

Root cause of the Failed_sdk_item_construction flake: a failed SDK item
construction disposes its demand while the stream pump publishes that
registration's snapshot. The duplicate-baseline check read the dying demand's
IsValid as 'cache not fresh', so the same acquisition was re-published as a new
complete baseline to every item on the node, leaving an orphan proof candidate
(and shared budget charge) the SDK never consumes. HasFreshCachedLocked no
longer depends on demand validity; Publish re-checks the demand after it.
Regression test with a pump seam: red without the fix, green with it.

Bad_null different_timestamp flake is a test race: SDK 2.0.1 delivers node
changes to items asynchronously (MonitoredNode2 channel), so the published
sample could land after the mode cycle and overwrite the injected
notification. The test now waits until the SDK queued it.
This commit is contained in:
Joseph Doherty
2026-11-28 10:10:20 -05:00
parent cb672ea060
commit 4cf06261f1
3 changed files with 94 additions and 1 deletions
@@ -19,6 +19,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
public TimeProvider Clock { get; }
internal Func<TimeSpan, TimeSpan>? RetryJitterForTests { get; set; }
internal Action? BeforeSuccessorAdoptionForTests { get; set; }
/// <summary>#920: runs on the stream pump after a publish passed its demand check, before the duplicate-baseline check.</summary>
internal Action<IProjectedDemandLease>? AfterPublishDemandCheckForTests { get; set; }
private readonly IFederatedProjectionCatalog _catalog;
private readonly IProjectedNodeLookup _nodes;
private readonly Func<string, string?> _connectionForMapping;
@@ -568,7 +570,11 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
internal bool HasFreshCachedLocked(Demand demand)
{
var sample = _cachedSample;
if (sample is null || _cachedVersion != LastVersion || !sample.SourceProof.IsValid || !demand.IsValid || !IsValid) return false;
// #920: deliberately NOT gated on demand.IsValid. This answers "is the sample already published for this version
// still fresh at this demand's age limit" — the duplicate-baseline suppression in Publish. A demand disposed
// concurrently (a failed SDK item construction) used to turn the answer into "not fresh", so a dying
// registration re-published the same acquisition as a new complete baseline to every item on the node.
if (sample is null || _cachedVersion != LastVersion || !sample.SourceProof.IsValid || !IsValid) return false;
try
{
return sample.OriginAgeBounds.Advance(_owner.Clock.GetElapsedTime(sample.ReceivedTimestamp,
@@ -1658,6 +1664,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
{
validated = false;
if (registration.Removed || !registration.Demand.IsValid || update.SourceProof is not AttemptProof proof) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishDemand); return false; }
_owner.AfterPublishDemandCheckForTests?.Invoke(registration.Demand);
var source = proof.Source;
if (!source.TryPrepareSuccessor(registration.Demand, out var successor)) return false;
try
@@ -1675,6 +1682,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
validated = update.IsCompleteSnapshot;
if (version == source.LastVersion && update.IsCompleteSnapshot && !registration.Recovery &&
source.HasFreshCachedLocked(registration.Demand)) return false;
// A demand disposed since the check above publishes nothing (it is no longer anyone's subscription).
if (!registration.Demand.IsValid) { validated = false; ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishDemand); return false; }
if (_owner._publisher.TryPublish([update]))
{
if (successor is not null)
@@ -56,6 +56,21 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
var item = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
var candidates = (System.Collections.IEnumerable)item.GetType().GetField("_candidates", flags)!.GetValue(item)!;
candidates.Cast<object>().Count().ShouldBe(scenario is "ambiguous" or "missing_timestamp" ? 2 : 1);
// #920: SDK 2.0.1 delivers a node change to its items asynchronously (MonitoredNode2's channel), so the
// sample published above can reach this item AFTER the mode cycle below — and, at queue size 1, overwrite
// the injected notification with the genuinely proven sample. Wait until the SDK has queued it, so the
// mode cycle discards it and the injected notification is the one delivered. (With two publishes the
// second may still be in flight; it is ambiguous against both candidates and denied either way.)
var lastValue = typeof(Opc.Ua.Server.MonitoredItem).GetField("m_lastValue", flags).ShouldNotBeNull();
var delivered = System.Diagnostics.Stopwatch.StartNew();
// The baseline sample shares the fake clock's timestamp, so match the status too.
static bool IsPublishedSample(Opc.Ua.DataValue value, DateTime at) =>
value.SourceTimestamp == (DateTimeUtc)at && value.StatusCode == StatusCodes.BadNoCommunication;
while (!IsPublishedSample((Opc.Ua.DataValue)lastValue.GetValue(item)!, timestamp))
{
delivered.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(10), "the SDK never queued the published sample");
await Task.Delay(10, ct);
}
item.SetMonitoringMode(MonitoringMode.Disabled);
if (scenario == "different_status")
{
@@ -111,6 +111,75 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
});
}
/// <summary>
/// #920: a subscription demand disposed while its stream pump is publishing the snapshot it asked for (a failed
/// SDK item construction disposes it on the SDK thread) must not re-publish the already-published, still-fresh
/// acquisition as a new complete baseline. It did: the duplicate-baseline check read the dying demand's validity
/// as "the cache is not fresh", so the same acquisition reached every existing item on the node again and left an
/// orphan proof candidate (and its shared budget charge) on each — no SDK notification ever consumes it, because
/// the node's value did not change.
/// </summary>
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
public async Task A_demand_disposed_mid_publish_does_not_republish_a_fresh_baseline()
{
var ct = TestContext.Current.CancellationToken;
LocalDataFixture? peer = null;
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
peer = origin; subscriptions.SampleClock = origin.Clock;
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, access, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
IProjectedDemandLease? first = null;
var armed = 0;
var disposed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
access.AfterPublishDemandCheckForTests = demand =>
{
first ??= demand;
if (ReferenceEquals(demand, first) || Interlocked.Exchange(ref armed, 0) != 1) return;
demand.Dispose();
disposed.TrySetResult();
};
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, sub, anchor, 1, 100, ct);
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
(await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.SourceVersion == 1, ct)).Snapshot.Value.ShouldBe(7);
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
var existing = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
int Candidates() => ((System.Collections.IEnumerable)existing.GetType().GetField("_candidates", flags)!.GetValue(existing)!).Cast<object>().Count();
Candidates().ShouldBe(0, "the delivered baseline consumed its candidate");
// A second item on the same node: its stream snapshot repeats the same (still fresh) acquisition, and its
// demand is disposed on the pump right after the publish passed its demand check.
Volatile.Write(ref armed, 1);
await AddComposedItem(client, sub, anchor, 2, 100, ct);
var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
await disposed.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
// The pump handles the removal only after it finished that publish, so the publish is over once it is sent.
var removed = System.Diagnostics.Stopwatch.StartNew();
while (stream.RemoveCommands == 0)
{
removed.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(10), "the disposed demand's item was never removed");
await Task.Delay(10, ct);
}
// Positive control: a third item's snapshot carries a NEW acquisition (v2) through the same in-order publisher.
subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8;
await AddComposedItem(client, sub, anchor, 3, 100, ct);
var seen = new List<ProjectedValueUpdate>();
ProjectedValueUpdate next;
do { next = await NextPublished(published.Reader, _ => true, ct); seen.Add(next); } while (next.SourceVersion != 2);
seen.Count(x => x.SourceVersion == 1).ShouldBe(0, "the disposed demand re-published the fresh v1 baseline");
Candidates().ShouldBe(1, "only the v2 baseline holds a candidate on the existing item");
}, onPublished: update => published.Writer.TryWrite(update));
}
private sealed class ThrowingSourceProof(IProjectedSamplePublicationProof inner) : IProjectedSamplePublicationProof
{
public bool IsValid => inner.IsValid;