fix(grpc-data): #966 a modify's replacement no longer emits a live delta before its snapshot

The suspected ordering gap was real. A modify that replaces an item commits on the delivery side (the ack's
commit): the replacement enters _items (it was already registered with the delivery scheduler at staging) and its
snapshot job goes to _committedSnapshots, which only the NEXT tick moves to the pump. A tick already past that
dequeue that then reads a source change (e.g. from a sibling item on the same source, whose interest group survives
the modify) marks the source dirty. The scheduler hands it the replacement's handle, and ConsiderAsync sent the
newer value as a live delta before SnapshotBegin. The snapshot that followed carried the older captured value.

ConsiderAsync now defers an item whose interest group is not snapshot-complete. LastConsidered is left unchanged,
and the group's own lease (its cursor starts at the snapshot capture) yields the change once SnapshotEnd commits.
The same guard covers added and recovered items. Nothing starves: an undelivered SnapshotEnd stops the stream.

Deterministic test (BeforeDirtyTickForTests hold + gated modify ack + publish under the hold): red 3/3 before
(value:R:20 | begin | snapshot:R:10), green after, with a positive control that 20 is delivered after the end.
Parallel in-process stress of the unhooked scenario (2 items on one source, modify one under continuous publish):
60/40000 violations before (10000 x widths 2/4/6/8), 0/40000 after.
This commit is contained in:
Joseph Doherty
2026-12-02 13:12:27 -05:00
parent 366a92d768
commit efd749da0f
3 changed files with 93 additions and 1 deletions
+8
View File
@@ -181,6 +181,14 @@ replaces the origin item (trigger, deadband or view change) could also produce i
acknowledgement released the replaced item's interest while a session tick was reading it. That acknowledgement released the replaced item's interest while a session tick was reading it. That
release is no longer counted as a lost history; the replacement continues with its own snapshot. release is no longer counted as a lost history; the replacement continues with its own snapshot.
An item's first frames on a Subscribe stream are its snapshot (`SnapshotBegin`, its snapshot value, `SnapshotEnd`). A
live delta for that item comes only after them. This applies to an added item, an item recovered from waiting for
initial data, and the new handle a `Modify` returns when it replaces the item. Until #966 a replacement could break
this. If a source change was read (for example through another item on the same source) while the modify's ack was
being committed, the replacement could send that newer value as a live delta before its `SnapshotBegin`. The
snapshot that followed then carried the older captured value. Now the change waits until the item's snapshot is
complete, and the item then delivers it as a live delta.
### Mixed versions (X0 rollout) ### Mixed versions (X0 rollout)
The remote history and alarm work (`docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`) The remote history and alarm work (`docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`)
@@ -1031,7 +1031,16 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
private async Task ConsiderAsync(Item item) private async Task ConsiderAsync(Item item)
{ {
lock (_gate) if (_challengedHandles.ContainsKey(item.Handle.Handle)) return; lock (_gate)
{
if (_challengedHandles.ContainsKey(item.Handle.Handle)) return;
// #966: no live delta before the item's own snapshot. A modify's replacement (or an added/recovered item) is
// scheduler-registered and in _items before its SnapshotEnd commits; a dirty mark for its source (from a
// sibling group, or a commit landing mid-tick after the snapshot dequeue) would otherwise emit a newer live
// value ahead of its SnapshotBegin. Nothing is lost: LastConsidered is untouched and the group's own lease
// (cursor from the snapshot capture) yields the change once the group is snapshot-complete.
if (item.Interest is { SnapshotComplete: false }) return;
}
if (item.Ticket is not { } ticket) return; if (item.Ticket is not { } ticket) return;
using var read = _services.SubscriptionHub.Read(ticket); using var read = _services.SubscriptionHub.Read(ticket);
if (read.Readiness != DataReadiness.Ready || read.Sample is null) { CloseWithReset("Source became unavailable."); return; } if (read.Readiness != DataReadiness.Ready || read.Sample is null) { CloseWithReset("Source became unavailable."); return; }
@@ -988,6 +988,81 @@ public sealed class GrpcDataStreamOrderingTests
} }
} }
// #966: the modify's replacement item enters _items (and was registered with the delivery scheduler at staging) the
// moment the ack commits on the delivery side, but its snapshot job only reaches the pump on the NEXT tick. A tick
// already past that dequeue which then reads a source change (here from a sibling item on the same source, whose
// interest group survives the modify) marks the source dirty, and the scheduler hands it the replacement's handle.
// Before the fix that emitted a live delta for the replacement ahead of its SnapshotBegin/Snapshot/End.
[Fact(Timeout = 30000)]
public async Task Modify_committed_mid_tick_does_not_emit_a_replacement_delta_before_its_snapshot()
{
var ct = TestContext.Current.CancellationToken;
using var demand = new FirstLeaseReleaseSignalDemand();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
fixture.Publish(10);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(ct);
var session = subscription.ShouldBeOfType<DataSubscriptionSession>();
var sink = new HeldModifyAckSink();
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>().RunDeliveryAsync(sink, ct);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
// "one" and "two" share a source and one interest group, so the group outlives the modify of "one".
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings), new("two", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30),
LocalDataFixture.Budget), ct);
await sink.FirstSnapshotEnd.Task.WaitAsync(ct);
var armed = 0;
var tickHolding = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
session.BeforeDirtyTickForTests = (_, _, interests) =>
{
if (interests == 0 || Interlocked.Exchange(ref armed, 0) == 0) return;
tickHolding.TrySetResult(true);
// Past this tick's committed-snapshot dequeue: hold it until the modify commits on the delivery side.
demand.FirstReleased.Wait(TimeSpan.FromSeconds(10));
};
await subscription.SendAsync(new ModifySubscriptionItems("s", 1, "modify", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings with { Deadband = 5 })]), ct);
await sink.ModifyAckHeld.Task.WaitAsync(ct); // replacement snapshot captured (10), ack not yet committed
Volatile.Write(ref armed, 1);
fixture.Clock.Advance(TimeSpan.FromMilliseconds(100)); // the session tick timer queues a tick
await tickHolding.Task.WaitAsync(ct);
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 20); fixture.Hub.ProcessPending(); // a change after the replacement's capture, readable from the surviving group
demand.FirstReleased.IsSet.ShouldBeFalse(); // positive control: the held tick predates the commit
sink.ReleaseModifyAck();
await Task.WhenAny(sink.SecondSnapshotEnd.Task, writer).WaitAsync(ct);
demand.FirstReleased.IsSet.ShouldBeTrue();
var ackIndex = -1;
string? replacement = null;
var deadline = DateTime.UtcNow.AddSeconds(10);
while (true)
{
var frames = sink.Frames.ToArray();
var trace = string.Join(" | ", frames);
frames.ShouldNotContain(frame => frame.StartsWith("reset", StringComparison.Ordinal), trace);
ackIndex = Array.FindIndex(frames, frame => frame.StartsWith("ack:modify:", StringComparison.Ordinal));
ackIndex.ShouldBeGreaterThan(0, trace);
replacement = frames[ackIndex]["ack:modify:".Length..];
replacement.ShouldNotBe(sink.OriginalHandle);
var after = frames.Skip(ackIndex + 1).Where(frame => frame.Contains($":{replacement}:", StringComparison.Ordinal) ||
frame is "begin" or "end").ToArray();
// The replacement's first frames are its snapshot; its live delta (20) only after the snapshot end.
after.Take(3).ShouldBe(["begin", $"snapshot:{replacement}:10", "end"], trace);
// Positive control: the change the guard deferred is not lost; the replacement's own interest delivers it.
if (after.Contains($"value:{replacement}:20")) break;
if (DateTime.UtcNow > deadline) throw new ShouldAssertException("Replacement never delivered 20: " + trace);
fixture.Clock.Advance(TimeSpan.FromMilliseconds(100));
await Task.Delay(20, ct);
}
}
}
[Fact(Timeout = 30000)] [Fact(Timeout = 30000)]
public async Task Quiet_control_only_session_expires_without_renewal_or_further_commands() public async Task Quiet_control_only_session_expires_without_renewal_or_further_commands()
{ {