fix(galaxy): #865 review round 2 - wait for the replay's pump, never race a second stream

Round 1 replaced a stale-session pump from any advise path and disposed the
old one in the background; that could start a second stream while the old
one still held the gateway's single-subscriber slot, and a kept
current-session pump could be dead with no fault re-reported.

- EnsureEventPumpStarted reuses again; only ReplayAsync restarts the pump.
  RestartEventPumpForReplay keeps a current-session pump only while its loop
  is running (EventPump.HasEnded), and flags the restart so no advise path
  starts a competing pump in the dispose gap.
- AwaitCurrentEventStreamAsync (bounded by StreamRequestWait) starts a pump
  only when none exists, WAITS for the replay while the pump is stale or
  restarting, waits for StreamRequested, and returns the session it verified.
  SubscribeAsync (per #861 attempt), read-via-subscribe and the probe hook
  issue and fence the advise under that session, so a reconnect after the
  check is caught as a straddle and retried.
- Read: a deadline (not caller) cancel during the wait falls through to
  per-ref results.
- Tests: reopen-window probe test now asserts the advise waits for the
  replay's single new stream; first Subscribe/Read wait for the stream; the
  fencing tests that advise in the window use a short wait bound; the
  production-path seed test uses an empty galaxy (a real probe advise now
  starts a stream against the fake endpoint).

Claude-Session: https://claude.ai/code/session_01GT67AD99zQQqpLCVm3p7xk
This commit is contained in:
Joseph Doherty
2026-11-11 12:46:15 -05:00
parent cc1a7ec687
commit 9060ff5561
6 changed files with 199 additions and 104 deletions
@@ -844,6 +844,7 @@ public sealed class EarlyEventWindowTests
"g", Opts(), hierarchySource: null, dataReader: null, dataWriter: null, subscriber: subscriber)
{
RecreateOverrideForTests = _ => Task.CompletedTask,
StreamRequestWait = TimeSpan.FromMilliseconds(100), // advises in the reopen window on purpose (#865 bound)
};
var delivered = new ConcurrentQueue<(string Ref, double Value)>();
driver.OnDataChange += (_, e) => delivered.Enqueue((e.FullReference, (double)e.Snapshot.Value!));
@@ -1027,6 +1028,9 @@ public sealed class EarlyEventWindowTests
"g", Opts(), hierarchySource: null, dataReader: null, dataWriter: null, subscriber: subscriber)
{
RecreateOverrideForTests = _ => Task.CompletedTask,
// These tests advise in the reopen → replay window on purpose (fencing, not values). #865 makes
// such an advise wait for the replay's pump, bounded; keep the bound short so they don't idle.
StreamRequestWait = TimeSpan.FromMilliseconds(100),
};
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
return driver;
@@ -272,7 +272,10 @@ public sealed class GalaxyDriverFixRound1Tests
[Fact]
public async Task Production_path_queries_the_platform_source_at_init()
{
var platforms = new ScriptedPlatformSource();
// An empty galaxy: since #865 a probe advise starts the event stream first, and this owned runtime's
// gRPC channel points at no real gateway — its stream would fault and (correctly) degrade health.
// The query itself is what this test pins.
var platforms = new ScriptedPlatformSource { Script = _ => [] };
await using var driver = new GalaxyDriver("drv", Opts(), hierarchySource: null, platformSource: platforms)
{
SessionOpenOverrideForTests = _ => Task.CompletedTask,
@@ -195,10 +195,10 @@ public sealed class ProbeInitialValueTests
/// <summary>
/// Review finding: a probe advised in the reopen → replay window (the session was swapped, the old
/// pump still streams the dead session) must still get its initial value — the stale-session pump
/// is replaced before the advise, and the replay keeps the replacement (it already streams the
/// recreated session). Reusing the old pump bound the value to the old session, so it never routed,
/// and the replay skipped the platform (its handle is current-session).
/// pump still streams the dead session) must still get its initial value. The advise waits for the
/// replay's restarted pump instead of advising onto the stale one (its value would route under the
/// old session and be lost, and the replay skips a current-session handle) or starting a competing
/// stream (the gateway's default single-subscriber mode refuses a second attach).
/// </summary>
[Fact]
public async Task Probe_advised_between_reopen_and_replay_still_gets_its_initial_value()
@@ -218,23 +218,55 @@ public sealed class ProbeInitialValueTests
await driver.InvokeReopenForTestAsync(CancellationToken.None); // session swapped; no replay yet
sub.ScanStateRunning = false;
await driver.ProbeWatcherForTests.ShouldNotBeNull()
var callsBeforeWindow = sub.CallsSnapshot().Length;
// The window advise must WAIT for the replay's current-session pump rather than advise onto the
// stale one (or start a competing stream).
var sync = driver.ProbeWatcherForTests.ShouldNotBeNull()
.SyncPlatformsAsync([.. Platforms, "LatePlatform"], CancellationToken.None);
await TestWait.UntilAsync(
() => StateOf(driver, "LatePlatform") == HostState.Stopped,
"a probe advised in the reopen window must get its initial value",
() => Describe(driver, sub));
var windowPump = driver.EventPumpInstanceForTests;
windowPump.ShouldNotBeSameAs(oldPump, "the stale-session pump must have been replaced before the advise");
await driver.InvokeReplayForTestAsync(CancellationToken.None);
driver.EventPumpInstanceForTests.ShouldBeSameAs(windowPump, "the replay keeps a pump already on the current session");
await TestWait.ForAsync(sync, "the window advise completes once the replay restarted the pump");
await TestWait.UntilAsync(
() => Platforms.All(p => StateOf(driver, p) == HostState.Stopped),
"the replay re-advises the stale probes and their initial values arrive on the kept pump",
() => StateOf(driver, "LatePlatform") == HostState.Stopped
&& Platforms.All(p => StateOf(driver, p) == HostState.Stopped),
"the window advise and the replay's re-advises all get their initial values",
() => Describe(driver, sub));
StateOf(driver, "LatePlatform").ShouldBe(HostState.Stopped);
driver.EventPumpInstanceForTests.ShouldNotBeSameAs(oldPump, "the replay restarted the stale pump");
var windowCalls = sub.CallsSnapshot()[callsBeforeWindow..];
var lateAdvise = Array.FindIndex(windowCalls, c => c.Contains("LatePlatform", StringComparison.Ordinal));
var newStream = Array.IndexOf(windowCalls, "stream");
newStream.ShouldBeGreaterThanOrEqualTo(0, $"the replay must start a new stream; calls=[{string.Join(" | ", windowCalls)}]");
lateAdvise.ShouldBeGreaterThan(newStream, $"the window advise must follow the new stream; calls=[{string.Join(" | ", windowCalls)}]");
windowCalls.Count(c => c == "stream").ShouldBe(1, "no competing stream may be started for the window advise");
sub.DroppedInitialValues.ShouldBe(0);
}
/// <summary>
/// The data paths too: a first SubscribeAsync and a first ReadAsync on a driver whose pump was never
/// started request the stream BEFORE advising, so their initial values arrive (a read of a value that
/// never changes again would otherwise time out).
/// </summary>
[Fact]
public async Task First_subscribe_and_read_advise_only_after_the_stream_is_requested()
{
var sub = new GatewayLikeSubscriber();
await using var driver = new GalaxyDriver("drv", Opts(), hierarchySource: null, subscriber: sub)
{
ReadViaSubscribeDeadline = TimeSpan.FromSeconds(10),
};
await driver.InitializeAsync("{}", CancellationToken.None);
var delivered = new TaskCompletionSource<DataChangeEventArgs>(TaskCreationOptions.RunContinuationsAsynchronously);
driver.OnDataChange += (_, e) => delivered.TrySetResult(e);
await driver.SubscribeAsync(["Tank01.Level"], TimeSpan.Zero, CancellationToken.None);
var calls = sub.CallsSnapshot();
Array.IndexOf(calls, "stream").ShouldBe(0, $"the stream must be requested before the advise; calls=[{string.Join(" | ", calls)}]");
(await TestWait.ForAsync(delivered.Task, "the subscribe's initial value must arrive", () => Describe(driver, sub)))
.FullReference.ShouldBe("Tank01.Level");
var read = await driver.ReadAsync(["Tank02.Level"], CancellationToken.None);
read[0].StatusCode.ShouldBe(0u, "the read's initial value must arrive (not BadTimeout)");
sub.DroppedInitialValues.ShouldBe(0);
}