fix(grpc-data): A3 verification r2 — N1 runner predecessor chain dropped after hand-over + stopped runner clears its record sets; correct the SentMessageQueue clone comment and pin the EventFieldList MemberwiseClone dependency

This commit is contained in:
Joseph Doherty
2026-11-24 22:26:09 -05:00
parent 5bece2a5a5
commit c8b35d494f
5 changed files with 94 additions and 14 deletions
@@ -455,11 +455,14 @@ internal sealed record ProjectedEventMarker(object? Identity, NodeId ConditionId
}
/// <summary>
/// A3 (§5.4): an <see cref="EventFieldList"/> carrying its <see cref="ProjectedEventMarker"/>. The SDK never clones a
/// queued list on its way to the wire (SDK 2.0.1: <c>QueueEvent(EventFieldList)</c> enqueues the instance,
/// <c>Publish</c> dequeues it, <c>ConstructMessage</c> places it, Republish returns the stored message), so
/// <c>ProjectedNotificationRewriter</c> sees this instance on every Publish and Republish and drops it when the re-check
/// fails.
/// A3 (§5.4): an <see cref="EventFieldList"/> carrying its <see cref="ProjectedEventMarker"/>. The rewriter does NOT see
/// the queued instance: SDK 2.0.1 <c>SentMessageQueue</c> stores the constructed message and returns a
/// <c>CoreUtils.Clone</c> of it on Publish and on Republish. The gate still works because
/// <see cref="EventFieldList.Clone"/> is <c>MemberwiseClone</c>, so every copy keeps this subclass, its
/// <see cref="Marker"/> and its handle, and <c>ProjectedNotificationRewriter</c> drops the copy when the re-check fails.
/// That clone dependency is pinned by
/// <c>ImportedConditionClassifierTests.Cloning_a_marked_event_list_the_way_the_SDK_does_keeps_the_subclass_and_the_marker</c>:
/// an SDK that cloned through the activator would turn it red.
/// </summary>
/// <remarks>
/// A3 review round 2 (root cause of the OI refresh failures): SDK 2.0.1 POOLS <see cref="EventFieldList"/> process-wide
@@ -143,7 +143,8 @@ public sealed partial class ProjectedConditionAccess
private readonly CancellationTokenSource _stop = new();
private readonly object _statusGate = new();
private readonly object _staleGate = new();
private readonly ConnectionRunner? _predecessor;
/// <summary>Verification r2 N1: dropped right after the hand-over, so runners never chain (R3 → R2 → R1 …).</summary>
private ConnectionRunner? _predecessor;
private Task _loop = Task.CompletedTask;
private Task _stopped = Task.CompletedTask;
private MappingState[] _states = [];
@@ -177,17 +178,27 @@ public sealed partial class ProjectedConditionAccess
public void Start() => _loop = Task.Run(async () =>
{
if (_predecessor is { } previous)
{
// S3/S4: never overlap the previous runner of this connection — its in-flight Publish or its removal would
// otherwise race this runner's materialisation (an orphaned key, or a fresh key removed by the old continuation).
try { await previous.Stopped.ConfigureAwait(false); } catch (Exception ex) { _owner._log.LogDebug(ex, "Imported conditions: predecessor stop faulted"); }
_materialised = previous._materialised;
previous._materialised = new HashSet<string>(StringComparer.Ordinal);
}
await HandOverAsync().ConfigureAwait(false);
await RunAsync(_stop.Token).ConfigureAwait(false);
});
/// <summary>
/// S3/S4: never overlap the previous runner of this connection — its in-flight Publish or its removal would otherwise
/// race this runner's materialisation (an orphaned key, or a fresh key removed by the old continuation). The
/// materialised set moves over only after the predecessor stopped. Verification r2 N1: the predecessor reference is
/// dropped once the hand-over is done (its own method, so no hoisted local outlives it either) — otherwise every
/// linger expiry or mapping change would add a link to a chain that keeps each old runner reachable.
/// </summary>
private async Task HandOverAsync()
{
var previous = _predecessor;
if (previous is null) return;
try { await previous.Stopped.ConfigureAwait(false); } catch (Exception ex) { _owner._log.LogDebug(ex, "Imported conditions: predecessor stop faulted"); }
_materialised = previous._materialised;
previous._materialised = new HashSet<string>(StringComparer.Ordinal);
_predecessor = null;
}
public void Stop(bool removeConditions)
{
_stop.Cancel();
@@ -195,6 +206,8 @@ public sealed partial class ProjectedConditionAccess
lock (_staleGate) { _staleGeneration++; _stale?.Dispose(); _stale = null; }
_stopped = _loop.ContinueWith(_ =>
{
// Verification r2 N1: a stopped runner keeps no stream's record sets (it may sit in _stopping until the next demand).
lock (_statusGate) _states = [];
if (!removeConditions) return;
var keys = _materialised.ToArray();
if (keys.Length > 0 && _owner._sink() is { } sink) sink.RemoveConditions(ConnectionId, keys);
@@ -290,6 +290,13 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
lock (_gate) return _runners.ContainsKey(connectionId);
}
/// <summary>Test observation (verification r2 N1): a weak reference to the connection's current (or still stopping) runner.</summary>
public WeakReference? RunnerReference(string connectionId)
{
lock (_gate)
return _runners.TryGetValue(connectionId, out var runner) || _stopping.TryGetValue(connectionId, out runner) ? new WeakReference(runner) : null;
}
/// <summary>Test observation: snapshot barriers a connection completed.</summary>
public int BarriersCompleted(string connectionId)
{
@@ -149,6 +149,34 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable
ProjectedNotificationRewriter.Project(message, republish: false, null).NotificationData.Count.ShouldBe(0);
}
/// <summary>
/// Verification review r2: the rewriter never sees the queued instance — SDK 2.0.1 <c>SentMessageQueue</c> hands Publish
/// and Republish a <c>CoreUtils.Clone</c> of the stored message. The gate holds only because
/// <see cref="EventFieldList.Clone"/> is <c>MemberwiseClone</c>, which keeps the subclass, the marker and the handle. Pins
/// that dependency: an SDK that cloned through the activator (a stock list) would turn this red.
/// </summary>
[Fact]
public void Cloning_a_marked_event_list_the_way_the_SDK_does_keeps_the_subclass_and_the_marker()
{
var marker = new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false);
var marked = new ProjectedEventFieldList(marker) { ClientHandle = 42 };
var direct = marked.Clone().ShouldBeOfType<ProjectedEventFieldList>();
direct.Marker.ShouldBeSameAs(marker);
direct.ClientHandle.ShouldBe(42u);
var message = new NotificationMessage { SequenceNumber = 11,
NotificationData = [new ExtensionObject(new EventNotificationList { Events = [marked] })] };
var delivered = CoreUtils.Clone(message)!; // exactly what SentMessageQueue returns for Publish / Republish
delivered.NotificationData[0].TryGetValue<EventNotificationList>(out var list).ShouldBeTrue();
var events = list!.Events;
var cloned = events[0].ShouldBeOfType<ProjectedEventFieldList>();
cloned.ShouldNotBeSameAs(marked, "the SDK delivers a copy, not the queued instance");
cloned.Marker.ShouldBeSameAs(marker);
ProjectedNotificationRewriter.Project(delivered, republish: false, null).NotificationData.Count
.ShouldBe(0, "the copy is still judged by its marker (and dropped when the re-check fails)");
}
[Fact]
public void S2_a_cached_positive_verdict_is_re_proved_past_the_credential_expiry_and_past_the_positive_TTL()
{
@@ -461,6 +461,35 @@ public sealed class GrpcDataProjectedConditionAccessTests
f.Sink.Live.ShouldBe([Key("y")], "x was handed over (not orphaned) and the new complete set removed it");
}
[Fact]
public async Task N1_demand_cycles_and_mapping_changes_do_not_chain_runners_so_an_old_runner_is_collectable()
{
// Verification review r2 N1: each runner kept its predecessor (and that one's record sets), so every linger expiry
// + re-subscribe or mapping change added a link R3 → R2 → R1 and memory grew without bound.
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
var demand = f.Access.AcquireEventDemand(null)!;
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
var first = f.Access.RunnerReference(Connection)!;
var version = 3L;
for (var cycle = 0; cycle < 3; cycle++)
{
demand.Dispose();
await f.WaitAsync(() => !f.Access.IsRunning(Connection)); // linger expired
demand = f.Access.AcquireEventDemand(null)!;
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), ++version)]));
}
for (var change = 0; change < 2; change++)
{
f.Mappings.Current[0].Mapping.MaxConditions++; // a changed signature ⇒ a new runner, a new stream
f.Mappings.Raise();
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), ++version)]));
}
f.Sink.Live.ShouldBe([Key("x")], "the hand-over still works across every cycle");
for (var i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); }
first.IsAlive.ShouldBeFalse("the current runner must not keep a chain of predecessors reachable");
demand.Dispose();
}
// ---------------------------------------------------------------------------------------------------------------------
internal static string Key(string seed) =>