fix(grpc-data): #962 a modify's ack commit releasing a replaced item's interest mid-tick no longer resets the stream

The Runtime.Tests flake (Changing_the_filter_acknowledges_a_new_revision_before_its_snapshot) was a real
production race. DataSubscriptionSession.TickAsync captures the snapshot-complete interest-group leases
under the gate, awaits the snapshot/condition pumps, then reads each lease's changes. A Modify that replaces
an item is committed on the DELIVERY side (the ack's commit -> CommitStaged -> ReleaseItem), which disposes
the replaced item's SourceInterestLease. If that lands between the capture and the read, TryReadChanges
returns false exactly like a lost history and the session answered a successful modify with
Reset: "Source change history expired." (ack, then Reset instead of SnapshotBegin).

InterestGroup now carries Released (set under the gate in ReleaseItem before the lease is disposed); the
tick skips a failed read of a group the session itself released - the replacement has its own snapshot.
A failed read of a group the session still owns is still a reset.

Regression test holds a tick at the capture point (BeforeDirtyTickForTests), commits the modify under it
via a gated transport write, then lets the tick read: red 3/3 before, green after. Stress of the original
scenario (5000 iterations x 6 widths): 137/30000 Reset before, 0/30000 after.
This commit is contained in:
Joseph Doherty
2026-12-01 21:30:59 -05:00
parent 60e1328218
commit 23b28e001f
3 changed files with 148 additions and 4 deletions
@@ -930,6 +930,64 @@ public sealed class GrpcDataStreamOrderingTests
}
}
// #962: a modify that replaces an item is committed on the DELIVERY side (the ack's commit), which releases the
// replaced item's interest group and disposes its SourceInterestLease. A tick already running on the command worker
// may have captured that lease before the commit; reading it afterwards fails exactly like an expired change history,
// and the session used to answer a successful modify with "Reset: Source change history expired.". This holds a tick
// at the capture point, commits the modify under it, then lets the tick read the released lease.
[Fact(Timeout = 30000)]
public async Task Modify_committed_while_a_tick_holds_the_replaced_interest_continues_with_the_replacement_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);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("one", 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);
// This tick captured the original item's interest lease; hold it until the modify commit releases it.
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); // the ack is in the transport, 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);
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 frames = sink.Frames.ToArray();
var trace = string.Join(" | ", frames);
frames.ShouldNotContain(frame => frame.StartsWith("reset", StringComparison.Ordinal), trace);
var ack = Array.FindIndex(frames, frame => frame.StartsWith("ack:modify:", StringComparison.Ordinal));
ack.ShouldBeGreaterThan(0, trace);
var replacement = frames[ack]["ack:modify:".Length..];
replacement.ShouldNotBe(sink.OriginalHandle);
frames.Skip(ack + 1).Take(3).ShouldBe(["begin", $"snapshot:{replacement}:10", "end"], trace);
}
}
[Fact(Timeout = 30000)]
public async Task Quiet_control_only_session_expires_without_renewal_or_further_commands()
{
@@ -1168,3 +1226,72 @@ internal sealed class CountingSnapshotDemand(int target) : ISubscriptionDemandSo
}
private sealed class Lease : IDisposable { public void Dispose() { } }
}
/// <summary>#962: the first item's demand lease signals when it is disposed (the replaced item's release).</summary>
internal sealed class FirstLeaseReleaseSignalDemand : ISubscriptionDemandSource, IDisposable
{
internal readonly ManualResetEventSlim FirstReleased = new();
private int _calls;
public ValueTask<SubscriptionDemandResult> AcquireAsync(SubscriptionAuthorizedView view,
DataSubscriptionSettings settings, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var lease = new Lease(Interlocked.Increment(ref _calls) == 1 ? FirstReleased : null);
return ValueTask.FromResult(new SubscriptionDemandResult(DataItemStatus.Good, settings, 1, lease));
}
public void Dispose() => FirstReleased.Dispose();
private sealed class Lease(ManualResetEventSlim? released) : IDisposable
{
public void Dispose() => released?.Set();
}
}
/// <summary>#962: records every frame and holds the transport write of the "modify" ack until released.</summary>
internal sealed class HeldModifyAckSink : IDataSubscriptionDeliverySink
{
internal readonly TaskCompletionSource<bool> FirstSnapshotEnd = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> SecondSnapshotEnd = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> ModifyAckHeld = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly System.Collections.Concurrent.ConcurrentQueue<string> Frames = new();
internal string? OriginalHandle;
private readonly TaskCompletionSource<bool> _releaseModifyAck = new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _snapshotEnds;
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
CancellationToken cancellationToken) => ValueTask.FromResult<IDataPreparedSubscriptionDelivery>(new Prepared(frame));
public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken)
{
switch (((Prepared)prepared).Frame)
{
case DataSubscriptionAck { CommandId: "open" } open:
OriginalHandle = Handle(open.Items[0].Handle);
Frames.Enqueue("ack:open:" + OriginalHandle);
break;
case DataSubscriptionAck { CommandId: "modify" } modify:
ModifyAckHeld.TrySetResult(true);
await _releaseModifyAck.Task.WaitAsync(cancellationToken); // intentionally gated transport write
Frames.Enqueue("ack:modify:" + Handle(modify.Items[0].Handle));
break;
case DataSubscriptionAck other: Frames.Enqueue("ack:" + other.CommandId); break;
case DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotBegin }: Frames.Enqueue("begin"); break;
case DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }:
Frames.Enqueue("end");
(Interlocked.Increment(ref _snapshotEnds) == 1 ? FirstSnapshotEnd : SecondSnapshotEnd).TrySetResult(true);
break;
case DataSubscriptionControl { Kind: DataStreamControlKind.Reset } reset: Frames.Enqueue("reset:" + reset.Diagnostic); break;
case DataSubscriptionControl control: Frames.Enqueue(control.Kind.ToString()); break;
case DataSubscriptionValues values:
foreach (var item in values.Items)
Frames.Enqueue((values.IsSnapshot ? "snapshot:" : "value:") + Handle(item.Handle) + ":" + item.Sample.Value.GetScalar());
break;
}
}
internal void ReleaseModifyAck() => _releaseModifyAck.TrySetResult(true);
private static string Handle(DataItemHandle? handle) =>
handle?.Handle.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "none";
private sealed class Prepared(DataSubscriptionFrame frame) : IDataPreparedSubscriptionDelivery
{
internal DataSubscriptionFrame Frame { get; } = frame;
public long RetainedBytes => 1;
public void Dispose() { }
}
}