Merge #962: Subscribe Modify no longer spuriously resets 'Source change history expired' when the replaced item's lease is released under an in-flight tick (real race, 167/45k -> 0/45k)
v2-ci / unit-tests (push) Waiting to run

This commit is contained in:
Joseph Doherty
2026-12-01 21:59:19 -05:00
3 changed files with 148 additions and 4 deletions
+5
View File
@@ -175,6 +175,11 @@ Listener, connection, export and projection limits bound messages, streams, moni
retained bytes, metadata and call lifetimes. Tune them together for measured workload demand;
defaults are admission bounds, not a throughput or capacity guarantee. Overload can reject work or
reset a stream, requiring a fresh snapshot. Do not interpret that recovery as lossless replay.
A reset reading "Source change history expired." (consumer `ResetHistory`) means the origin lost a
source's change history for an item it still serves. Until #962 a Subscribe-stream `Modify` command that
replaces the origin item (trigger, deadband or view change) could also produce it intermittently: the modify's
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.
### Mixed versions (X0 rollout)
@@ -102,6 +102,8 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
internal readonly Dictionary<BackingSourceKey, int> Sources = new();
internal LinkedListNode<InterestGroup>? Node;
internal bool SnapshotComplete;
/// <summary>Set under the session gate when the session itself releases the group (its last item went).</summary>
internal bool Released;
}
private sealed class SnapshotJob(SnapshotLease snapshot, IDisposable admission, InterestGroup group,
IReadOnlyList<Item> items, IReadOnlyList<PartitionWatermark> watermarks, bool temporaryInterest = false)
@@ -795,6 +797,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
if (_interestCursor == group.Node) _interestCursor = group.Node!.Next ?? _interests.First;
_interests.Remove(group.Node!);
if (_interestCursor == group.Node) _interestCursor = _interests.First;
group.Released = true;
group.Lease.Dispose();
}
}
@@ -857,23 +860,32 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
{ waiting.Ticket = null; waiting.WaitingNode = _waiting.AddLast(waiting.Handle.Handle); }
}
}
List<SourceInterestLease> interests = [];
List<InterestGroup> interests = [];
lock (_gate)
{
_interestCursor ??= _interests.First;
for (var count = 0; count < Math.Min(32, _interests.Count); count++)
{
var current = _interestCursor!;
if (current.Value.SnapshotComplete) interests.Add(current.Value.Lease);
if (current.Value.SnapshotComplete) interests.Add(current.Value);
_interestCursor = current.Next ?? _interests.First;
}
}
await PumpSnapshotsAsync().ConfigureAwait(false);
await PumpConditionsAsync().ConfigureAwait(false);
BeforeDirtyTickForTests?.Invoke(_outbound.Reader.Count, Volatile.Read(ref _queuedValues), interests.Count);
foreach (var interest in interests)
foreach (var group in interests)
{
if (!interest.TryReadChanges(32, out var changes)) { CloseWithReset("Source change history expired."); return; }
if (!group.Lease.TryReadChanges(32, out var changes))
{
// #962: a modify's ack commit runs on the delivery side and can release a group this tick captured
// above (the replaced item's interest); its disposed lease then reads like a reset. That group is gone
// by design and its replacement re-snapshots, so only a group the session still owns lost its history.
bool released;
lock (_gate) released = group.Released;
if (released) continue;
CloseWithReset("Source change history expired."); return;
}
foreach (var change in changes) MarkDirty(change.Ticket.Key);
}
var availableValues = AvailableValueSlots();
@@ -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() { }
}
}