fix(galaxy): #859 second review + #861 — window-sequence trim, per-session handles, straddling subscribes

I-2: unclaimed parked events are trimmed by window sequence. Each window gets a
monotonically increasing sequence at Begin, each parked event is stamped with
the newest one, and on every End events stamped before the oldest open
window's sequence are dropped (amortised O(1) via a park-order queue). Under
concurrent reads the open count rarely hit 0, so trailing events used to pile
up to the bound and push genuine early values into overflow.

I-1 / #861: SubscriptionRegistry.StartNewSession() — called FIRST in
ReplayAsync on every reconnect — clears held events, invalidates the reverse
map (subscriptions kept) and bumps a session number. New-session events whose
number an old binding still held now park until the replay's per-subscription
Rebind promotes them, instead of resolving to the wrong tag. TryRegister /
TryRebind refuse a stale session atomically under the park gate: a
SubscribeAsync whose reply straddled a reconnect is re-issued on the new
session (max 3 attempts), a subscribe-once read returns BadCommunicationError,
ResubscribeAllAsync stops if the session changes again. Old-session handle
numbers are never unsubscribed (Remove reports whether the entry belongs to
the current session; the read's late-reply path checks too), and an old
session's pump can no longer resolve through the map (fast path checks the
session).

I-3 (interim): a completed UnsubscribeBulk purges events parked for its
handles (driver + probe watcher). Full fix needs a worker sequence on the
SubscribeBulk reply (mxaccessgw, optional) — documented.

M-1: a resolved handle with a stranded parked list promotes it and resolves
the live event (never parks it). M-2: ResolveOrPark returns the ready events
to replay first, one gate acquisition per event while anything is held.
M-3: SubscribeAsync/read dispose the window before the orphan-release RPC.
M-5: ResolveOrPark remarks document the single-dispatching-pump invariant.

Tests (TestWait): overlapping windows don't accumulate, purge, stranded list,
session fence + map invalidation, stale-session registration refused,
end-to-end replay with swapped handle numbers and event-before-reply,
subscribe and read straddling a reconnect, read deadline closes its window.
Each was checked red against a mutation of the fix it pins.

Refs #859, #861.

Claude-Session: https://claude.ai/code/session_01GT67AD99zQQqpLCVm3p7xk
This commit is contained in:
Joseph Doherty
2026-11-11 10:41:16 -05:00
parent f89e0cc04c
commit d08e900203
6 changed files with 789 additions and 231 deletions
@@ -45,9 +45,9 @@ public sealed class EarlyEventWindowTests
public void Unknown_handle_without_a_pending_subscribe_is_stale()
{
var registry = new SubscriptionRegistry();
var epoch = registry.StartNewEpoch();
var epoch = registry.CurrentSession;
registry.ResolveOrPark(DataChange(7, 1), epoch, out _).ShouldBe(EarlyEventOutcome.Stale);
registry.ResolveOrPark(DataChange(7, 1), epoch, out _, out _).ShouldBe(EarlyEventOutcome.Stale);
registry.ParkedEventCount.ShouldBe(0);
}
@@ -56,15 +56,15 @@ public sealed class EarlyEventWindowTests
public void Parked_events_are_promoted_in_order_on_register()
{
var registry = new SubscriptionRegistry();
var epoch = registry.StartNewEpoch();
var epoch = registry.CurrentSession;
var woken = 0;
registry.ParkedEventsReady += () => woken++;
using (registry.BeginPendingSubscribe())
{
registry.ResolveOrPark(DataChange(7, 1), epoch, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.ResolveOrPark(DataChange(7, 2), epoch, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.ResolveOrPark(DataChange(8, 9), epoch, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.ResolveOrPark(DataChange(7, 1), epoch, out _, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.ResolveOrPark(DataChange(7, 2), epoch, out _, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.ResolveOrPark(DataChange(8, 9), epoch, out _, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.TakeReadyEvents(epoch).ShouldBeEmpty();
registry.Register(1, [new TagBinding("Tank.Level", 7)]);
@@ -82,12 +82,12 @@ public sealed class EarlyEventWindowTests
public void Rebind_promotes_parked_events_for_the_new_handles()
{
var registry = new SubscriptionRegistry();
var epoch = registry.StartNewEpoch();
var epoch = registry.CurrentSession;
registry.Register(1, [new TagBinding("Tank.Level", 7)]);
using (registry.BeginPendingSubscribe())
{
registry.ResolveOrPark(DataChange(70, 5), epoch, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.ResolveOrPark(DataChange(70, 5), epoch, out _, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.Rebind(1, [new TagBinding("Tank.Level", 70)]);
}
@@ -99,11 +99,11 @@ public sealed class EarlyEventWindowTests
public void Closing_one_of_two_windows_keeps_parked_events()
{
var registry = new SubscriptionRegistry();
var epoch = registry.StartNewEpoch();
var epoch = registry.CurrentSession;
var first = registry.BeginPendingSubscribe();
var second = registry.BeginPendingSubscribe();
registry.ResolveOrPark(DataChange(7, 1), epoch, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.ResolveOrPark(DataChange(7, 1), epoch, out _, out _).ShouldBe(EarlyEventOutcome.Parked);
first.Dispose();
first.Dispose(); // idempotent — must not close the second window
registry.PendingSubscribeCount.ShouldBe(1);
@@ -111,7 +111,7 @@ public sealed class EarlyEventWindowTests
second.Dispose();
registry.ParkedEventCount.ShouldBe(0);
registry.ResolveOrPark(DataChange(7, 1), epoch, out _).ShouldBe(EarlyEventOutcome.Stale);
registry.ResolveOrPark(DataChange(7, 1), epoch, out _, out _).ShouldBe(EarlyEventOutcome.Stale);
}
/// <summary>
@@ -122,9 +122,9 @@ public sealed class EarlyEventWindowTests
public void A_new_window_never_inherits_the_previous_windows_leftovers()
{
var registry = new SubscriptionRegistry();
var epoch = registry.StartNewEpoch();
var epoch = registry.CurrentSession;
var first = registry.BeginPendingSubscribe();
registry.ResolveOrPark(DataChange(7, 1), epoch, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.ResolveOrPark(DataChange(7, 1), epoch, out _, out _).ShouldBe(EarlyEventOutcome.Parked);
first.Dispose();
using var second = registry.BeginPendingSubscribe();
@@ -138,35 +138,104 @@ public sealed class EarlyEventWindowTests
public void Parking_is_bounded()
{
var registry = new SubscriptionRegistry();
var epoch = registry.StartNewEpoch();
var epoch = registry.CurrentSession;
using var window = registry.BeginPendingSubscribe();
var ev = DataChange(7, 1);
for (var i = 0; i < SubscriptionRegistry.MaxParkedEvents; i++)
{
registry.ResolveOrPark(ev, epoch, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.ResolveOrPark(ev, epoch, out _, out _).ShouldBe(EarlyEventOutcome.Parked);
}
registry.ResolveOrPark(ev, epoch, out _).ShouldBe(EarlyEventOutcome.Overflow);
registry.ResolveOrPark(ev, epoch, out _, out _).ShouldBe(EarlyEventOutcome.Overflow);
registry.ParkedEventCount.ShouldBe(SubscriptionRegistry.MaxParkedEvents);
}
/// <summary>Review #5: promoted-but-not-yet-replayed events still count toward the bound.</summary>
/// <summary>
/// Review #5 + M-2: promoted-but-not-yet-replayed events stay counted until the dispatch thread
/// takes them, and the next ResolveOrPark hands them back (in order) before anything else.
/// </summary>
[Fact]
public void Ready_events_count_toward_the_bound()
public void Ready_events_stay_counted_until_handed_back_by_the_next_resolve()
{
var registry = new SubscriptionRegistry();
var epoch = registry.StartNewEpoch();
var session = registry.CurrentSession;
using var window = registry.BeginPendingSubscribe();
var ev = DataChange(7, 1);
for (var i = 0; i < SubscriptionRegistry.MaxParkedEvents; i++) registry.ResolveOrPark(ev, epoch, out _);
registry.Register(1, [new TagBinding("Tank.Level", 7)]); // all promoted to ready
registry.ResolveOrPark(DataChange(7, 1), session, out _, out _);
registry.ResolveOrPark(DataChange(7, 2), session, out _, out _);
registry.Register(1, [new TagBinding("Tank.Level", 7)]); // promoted to ready
registry.ParkedEventCount.ShouldBe(2);
registry.ResolveOrPark(DataChange(8, 1), epoch, out _).ShouldBe(EarlyEventOutcome.Overflow);
registry.ResolveOrPark(DataChange(8, 3), session, out _, out var replayFirst).ShouldBe(EarlyEventOutcome.Parked);
replayFirst.Select(e => e.Value.DoubleValue).ShouldBe([1.0, 2.0]);
registry.ParkedEventCount.ShouldBe(1, "only the newly parked event for handle 8 remains held");
}
registry.TakeReadyEvents(epoch).Count.ShouldBe(SubscriptionRegistry.MaxParkedEvents);
/// <summary>
/// I-2: windows that overlap so the open count never reaches 0 (concurrent reads) must not
/// accumulate unclaimed events — each is trimmed once every window that could claim it closed.
/// </summary>
[Fact]
public void Overlapping_windows_that_never_all_close_do_not_accumulate_unclaimed_events()
{
var registry = new SubscriptionRegistry();
var session = registry.CurrentSession;
var open = registry.BeginPendingSubscribe();
for (var i = 0; i < 1_000; i++)
{
// An unknown-handle event nobody will ever claim (e.g. a trailing event after a read's Remove).
registry.ResolveOrPark(DataChange(10_000 + i, i), session, out _, out _).ShouldBe(EarlyEventOutcome.Parked);
var next = registry.BeginPendingSubscribe(); // overlap: the count never drops to 0
open.Dispose();
open = next;
registry.ParkedEventCount.ShouldBe(0, $"iteration {i}: the event's only possible owners have all closed");
}
// Positive control: an event parked inside the still-open window survives and is claimable.
registry.ResolveOrPark(DataChange(7, 42), session, out _, out _).ShouldBe(EarlyEventOutcome.Parked);
var later = registry.BeginPendingSubscribe();
later.Dispose(); // a window opened AFTER the park closing must not trim it
registry.ParkedEventCount.ShouldBe(1);
registry.Register(1, [new TagBinding("Tank.Level", 7)]);
registry.TakeReadyEvents(session).Single().Value.DoubleValue.ShouldBe(42.0);
open.Dispose();
}
/// <summary>I-3 interim: an unsubscribe purges events parked for its handles.</summary>
[Fact]
public void Purge_drops_events_parked_for_unsubscribed_handles()
{
var registry = new SubscriptionRegistry();
var session = registry.CurrentSession;
using var window = registry.BeginPendingSubscribe();
registry.ResolveOrPark(DataChange(7, 1), session, out _, out _); // trailing event of a removed item
registry.ResolveOrPark(DataChange(8, 2), session, out _, out _); // positive control
registry.PurgeParked([7]);
registry.ParkedEventCount.ShouldBe(1);
registry.Register(1, [new TagBinding("Reused", 7), new TagBinding("Other", 8)]);
registry.TakeReadyEvents(session).Select(e => e.ItemHandle).ShouldBe([8]);
}
/// <summary>
/// M-1: a live event for a RESOLVED handle that (defensively) still has a parked list is never
/// parked behind it — the list is promoted and the event resolves, so no trim can lose it.
/// </summary>
[Fact]
public void A_resolved_handle_with_a_stranded_parked_list_promotes_it_and_resolves()
{
var registry = new SubscriptionRegistry();
var session = registry.CurrentSession;
var window = registry.BeginPendingSubscribe();
registry.Register(1, [new TagBinding("Tank.Level", 7)]);
registry.ForceParkForTests(DataChange(7, 1)); // the "should be impossible" stranded list
registry.ResolveOrPark(DataChange(7, 2), session, out var subs, out var replayFirst)
.ShouldBe(EarlyEventOutcome.Resolved);
subs.Single().FullReference.ShouldBe("Tank.Level");
replayFirst.Select(e => e.Value.DoubleValue).ShouldBe([1.0]);
window.Dispose();
registry.ParkedEventCount.ShouldBe(0);
registry.ResolveOrPark(DataChange(8, 1), epoch, out _).ShouldBe(EarlyEventOutcome.Parked,
"positive control: once replayed, the room is back");
}
/// <summary>A registered handle resolves normally even while a window is open.</summary>
@@ -174,11 +243,11 @@ public sealed class EarlyEventWindowTests
public void Registered_handle_resolves_while_a_window_is_open()
{
var registry = new SubscriptionRegistry();
var epoch = registry.StartNewEpoch();
var epoch = registry.CurrentSession;
registry.Register(1, [new TagBinding("Tank.Level", 7)]);
using var window = registry.BeginPendingSubscribe();
registry.ResolveOrPark(DataChange(7, 1), epoch, out var subs).ShouldBe(EarlyEventOutcome.Resolved);
registry.ResolveOrPark(DataChange(7, 1), epoch, out var subs, out _).ShouldBe(EarlyEventOutcome.Resolved);
subs.Single().FullReference.ShouldBe("Tank.Level");
}
@@ -188,25 +257,71 @@ public sealed class EarlyEventWindowTests
/// neither park nor replay — so a reused handle number never receives an old-session value.
/// </summary>
[Fact]
public void A_new_epoch_discards_held_events_and_fences_the_old_epoch()
public void A_new_session_discards_held_events_and_fences_the_old_session()
{
var registry = new SubscriptionRegistry();
var oldEpoch = registry.StartNewEpoch();
var oldSession = registry.CurrentSession;
using var window = registry.BeginPendingSubscribe();
registry.ResolveOrPark(DataChange(7, 111), oldEpoch, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.ResolveOrPark(DataChange(8, 112), oldEpoch, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.ResolveOrPark(DataChange(7, 111), oldSession, out _, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.ResolveOrPark(DataChange(8, 112), oldSession, out _, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.Register(1, [new TagBinding("Old.A", 8)]); // 8 promoted to ready, never replayed
var newEpoch = registry.StartNewEpoch();
var newSession = registry.StartNewSession();
registry.ParkedEventCount.ShouldBe(0);
registry.TakeReadyEvents(newEpoch).ShouldBeEmpty();
registry.TakeReadyEvents(newSession).ShouldBeEmpty();
registry.Register(2, [new TagBinding("New.B", 7)]); // new session reuses handle 7
registry.TakeReadyEvents(newEpoch).ShouldBeEmpty("the old session's value must not reach New.B");
registry.TakeReadyEvents(newSession).ShouldBeEmpty("the old session's value must not reach New.B");
registry.ResolveOrPark(DataChange(9, 1), oldEpoch, out _).ShouldBe(EarlyEventOutcome.Stale);
registry.TakeReadyEvents(oldEpoch).ShouldBeEmpty();
registry.ResolveOrPark(DataChange(9, 1), newEpoch, out _).ShouldBe(EarlyEventOutcome.Parked,
"positive control: the current epoch still parks");
registry.ResolveOrPark(DataChange(7, 1), oldSession, out _, out _).ShouldBe(EarlyEventOutcome.Stale,
"a dying old-session pump must not resolve through the map, even for a registered number");
registry.ResolveOrPark(DataChange(9, 1), oldSession, out _, out _).ShouldBe(EarlyEventOutcome.Stale);
registry.TakeReadyEvents(oldSession).ShouldBeEmpty();
registry.ResolveOrPark(DataChange(9, 1), newSession, out _, out _).ShouldBe(EarlyEventOutcome.Parked,
"positive control: the current session still parks");
}
/// <summary>
/// I-1: a new session invalidates the reverse map but keeps the subscriptions, so a new-session
/// event on a number an old binding still holds PARKS (instead of resolving to the old tag) and
/// is promoted by the replay's Rebind to the right tag.
/// </summary>
[Fact]
public void A_new_session_invalidates_old_handles_so_colliding_numbers_park_until_rebind()
{
var registry = new SubscriptionRegistry();
registry.Register(1, [new TagBinding("Old.A", 7)]);
registry.Register(2, [new TagBinding("Old.B", 8)]);
var session = registry.StartNewSession();
registry.TrackedSubscriptionCount.ShouldBe(2, "subscriptions survive for the replay to rebind");
using var window = registry.BeginPendingSubscribe();
// New session: Old.B is re-issued as handle 7 — the number Old.A still holds until its own Rebind.
registry.ResolveOrPark(DataChange(7, 5), session, out _, out _).ShouldBe(EarlyEventOutcome.Parked);
registry.TryRebind(2, [new TagBinding("Old.B", 7)], session).ShouldBeTrue();
registry.TakeReadyEvents(session).ShouldHaveSingleItem().Value.DoubleValue.ShouldBe(5.0);
registry.ResolveSubscribers(7).ShouldBe([(2L, "Old.B")]);
}
/// <summary>#861: a registration or rebind carrying a stale session is refused.</summary>
[Fact]
public void Registration_with_a_stale_session_is_refused()
{
var registry = new SubscriptionRegistry();
var before = registry.CurrentSession;
registry.Register(1, [new TagBinding("Tank.Level", 7)]);
registry.StartNewSession();
registry.TryRegister(2, [new TagBinding("Late", 9)], before).ShouldBeFalse();
registry.Contains(2).ShouldBeFalse();
registry.TryRebind(1, [new TagBinding("Tank.Level", 9)], before).ShouldBeFalse();
registry.ResolveSubscribers(9).ShouldBeEmpty();
registry.TryRegister(3, [new TagBinding("Fresh", 9)], registry.CurrentSession).ShouldBeTrue("positive control");
registry.Remove(1, out var live).ShouldNotBeNull();
live.ShouldBeFalse("never rebound in the new session — its handle 7 must not be unsubscribed");
registry.Remove(3, out live).ShouldNotBeNull();
live.ShouldBeTrue();
}
// ===== EventPump =====
@@ -368,6 +483,7 @@ public sealed class EarlyEventWindowTests
oldStream.Emit(DataChange(7, 111));
await TestWait.UntilAsync(() => registry.ParkedEventCount == 1, "the old session's event must be parked");
await oldPump.DisposeAsync();
registry.StartNewSession(); // what GalaxyDriver.ReplayAsync does before recreating the pump
var newStream = new ChannelSubscriber();
await using var newPump = new EventPump(newStream, registry, channelCapacity: 16, clientName: "New");
@@ -494,4 +610,172 @@ public sealed class EarlyEventWindowTests
args.FullReference.ShouldBe("PlatformA.ScanState");
((GalaxySubscriptionHandle)args.SubscriptionHandle).SubscriptionId.ShouldBe(SubscriptionRegistry.ProbeSubscriptionId);
}
// ===== Reconnect / session (#859 I-1, #861) =====
/// <summary>
/// A gateway fake whose SubscribeBulk calls follow a per-call script (default: fresh handles).
/// Events go on one stream that survives pump restarts.
/// </summary>
private sealed class ScriptedSubscriber : IGalaxySubscriber
{
private readonly Channel<MxEvent> _events = Channel.CreateUnbounded<MxEvent>();
private int _nextHandle = 1_000;
public ConcurrentQueue<Func<IReadOnlyList<string>, CancellationToken, Task<IReadOnlyList<SubscribeResult>>>> Script { get; } = new();
public ConcurrentQueue<int> Unsubscribed { get; } = new();
public int SubscribeCalls;
public Task<IReadOnlyList<SubscribeResult>> SubscribeBulkAsync(
IReadOnlyList<string> fullReferences, int bufferedUpdateIntervalMs, CancellationToken cancellationToken)
{
Interlocked.Increment(ref SubscribeCalls);
if (Script.TryDequeue(out var step)) return step(fullReferences, cancellationToken);
return Task.FromResult<IReadOnlyList<SubscribeResult>>(
[.. fullReferences.Select(r => Ok(r, Interlocked.Increment(ref _nextHandle)))]);
}
public Task UnsubscribeBulkAsync(IReadOnlyList<int> itemHandles, CancellationToken cancellationToken)
{
foreach (var h in itemHandles) Unsubscribed.Enqueue(h);
return Task.CompletedTask;
}
public async IAsyncEnumerable<MxEvent> StreamEventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
await foreach (var ev in _events.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{
yield return ev;
}
}
public void Emit(MxEvent ev) => _events.Writer.TryWrite(ev).ShouldBeTrue();
}
private static SubscribeResult Ok(string tag, int handle) =>
new() { TagAddress = tag, ItemHandle = handle, WasSuccessful = true };
/// <summary>
/// I-1 end to end: after a reconnect the new session hands Tank.A the number Tank.B held in the
/// old session (and vice versa), and each initial value arrives BEFORE its SubscribeBulk reply.
/// Every value must reach its own tag — not the tag that owned the number before the reconnect.
/// </summary>
[Fact]
public async Task Replay_with_colliding_handles_and_event_before_reply_delivers_each_value_to_its_own_tag()
{
var subscriber = new ScriptedSubscriber();
using var driver = new GalaxyDriver(
"g", Opts(), hierarchySource: null, dataReader: null, dataWriter: null, subscriber: subscriber);
var registry = driver.SubscriptionsForTests;
var delivered = new ConcurrentQueue<(string Ref, double Value)>();
driver.OnDataChange += (_, e) => delivered.Enqueue((e.FullReference, (double)e.Snapshot.Value!));
subscriber.Script.Enqueue((refs, _) => Task.FromResult<IReadOnlyList<SubscribeResult>>([Ok(refs[0], 1)]));
subscriber.Script.Enqueue((refs, _) => Task.FromResult<IReadOnlyList<SubscribeResult>>([Ok(refs[0], 2)]));
await driver.SubscribeAsync(["Tank.A"], TimeSpan.Zero, TestContext.Current.CancellationToken);
await driver.SubscribeAsync(["Tank.B"], TimeSpan.Zero, TestContext.Current.CancellationToken);
// New session: swapped numbers; each initial value is on the stream (and parked) before the reply.
var newHandle = new Dictionary<string, int> { ["Tank.A"] = 2, ["Tank.B"] = 1 };
var newValue = new Dictionary<string, double> { ["Tank.A"] = 10.0, ["Tank.B"] = 20.0 };
for (var i = 0; i < 2; i++)
{
subscriber.Script.Enqueue(async (refs, _) =>
{
var tag = refs[0];
var before = registry.ParkedEventCount;
subscriber.Emit(DataChange(newHandle[tag], newValue[tag]));
await TestWait.UntilAsync(() => registry.ParkedEventCount > before,
$"{tag}'s new-session initial value must PARK, not resolve to the old owner of handle {newHandle[tag]}");
return [Ok(tag, newHandle[tag])];
});
}
await driver.InvokeReplayForTestAsync(TestContext.Current.CancellationToken);
await TestWait.UntilAsync(() => delivered.Count >= 2, "both replayed initial values must be published",
() => string.Join(", ", delivered));
delivered.OrderBy(d => d.Ref).ShouldBe([("Tank.A", 10.0), ("Tank.B", 20.0)]);
registry.ResolveSubscribers(1).Single().FullReference.ShouldBe("Tank.B");
registry.ResolveSubscribers(2).Single().FullReference.ShouldBe("Tank.A");
}
/// <summary>
/// #861: a SubscribeAsync whose reply returns after a reconnect does not register the dead
/// old-session handles (nor unsubscribe their numbers) — it re-issues on the new session.
/// </summary>
[Fact]
public async Task Subscribe_whose_reply_straddles_a_reconnect_is_reissued_on_the_new_session()
{
var subscriber = new ScriptedSubscriber();
using var driver = new GalaxyDriver(
"g", Opts(), hierarchySource: null, dataReader: null, dataWriter: null, subscriber: subscriber);
var registry = driver.SubscriptionsForTests;
var replyGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
subscriber.Script.Enqueue(async (refs, _) =>
{
await replyGate.Task;
return [Ok(refs[0], 500)]; // an old-session handle
});
subscriber.Script.Enqueue((refs, _) => Task.FromResult<IReadOnlyList<SubscribeResult>>([Ok(refs[0], 600)]));
var subscribe = driver.SubscribeAsync(["Tank.X"], TimeSpan.Zero, TestContext.Current.CancellationToken);
await TestWait.UntilAsync(() => Volatile.Read(ref subscriber.SubscribeCalls) == 1, "the first SubscribeBulk must be in flight");
await driver.InvokeReplayForTestAsync(TestContext.Current.CancellationToken); // the reconnect
replyGate.SetResult();
var handle = await TestWait.ForAsync(subscribe, "the subscribe must complete on the new session");
Volatile.Read(ref subscriber.SubscribeCalls).ShouldBe(2);
registry.ResolveSubscribers(500).ShouldBeEmpty("the dead old-session handle must not be registered");
registry.ResolveSubscribers(600).ShouldBe([(((GalaxySubscriptionHandle)handle).SubscriptionId, "Tank.X")]);
subscriber.Unsubscribed.ShouldNotContain(500, "its number may belong to a new-session item");
}
/// <summary>#861: a subscribe-once read whose reply straddles a reconnect reports the lost session.</summary>
[Fact]
public async Task Read_whose_reply_straddles_a_reconnect_returns_bad_communication_and_leaves_old_handles_alone()
{
var subscriber = new ScriptedSubscriber();
using var driver = new GalaxyDriver(
"g", Opts(), hierarchySource: null, dataReader: null, dataWriter: null, subscriber: subscriber);
var registry = driver.SubscriptionsForTests;
var replyGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
subscriber.Script.Enqueue(async (refs, _) =>
{
await replyGate.Task;
return [Ok(refs[0], 700)];
});
var read = driver.ReadAsync(["Tank.Y"], TestContext.Current.CancellationToken);
await TestWait.UntilAsync(() => Volatile.Read(ref subscriber.SubscribeCalls) == 1, "the read's SubscribeBulk must be in flight");
await driver.InvokeReplayForTestAsync(TestContext.Current.CancellationToken);
replyGate.SetResult();
var snapshot = (await TestWait.ForAsync(read, "the read must complete")).ShouldHaveSingleItem();
snapshot.StatusCode.ShouldBe(StatusCodeMap.BadCommunicationError);
registry.ResolveSubscribers(700).ShouldBeEmpty();
subscriber.Unsubscribed.ShouldBeEmpty();
registry.PendingSubscribeCount.ShouldBe(0, "the read's early-event window must be closed");
}
/// <summary>The read's internal-deadline path closes its early-event window.</summary>
[Fact]
public async Task Read_deadline_path_closes_its_window()
{
var subscriber = new ScriptedSubscriber();
using var driver = new GalaxyDriver(
"g", Opts(), hierarchySource: null, dataReader: null, dataWriter: null, subscriber: subscriber)
{
ReadViaSubscribeDeadline = TimeSpan.FromMilliseconds(100),
};
var never = new TaskCompletionSource<IReadOnlyList<SubscribeResult>>(TaskCreationOptions.RunContinuationsAsynchronously);
subscriber.Script.Enqueue((_, _) => never.Task);
var snapshot = (await TestWait.ForAsync(
driver.ReadAsync(["Tank.Z"], TestContext.Current.CancellationToken), "the read must time out")).ShouldHaveSingleItem();
snapshot.StatusCode.ShouldBe(StatusCodeMap.BadTimeout);
driver.SubscriptionsForTests.PendingSubscribeCount.ShouldBe(0);
never.SetResult([]); // let the abandoned RPC finish cleanly
}
}