fix(sessions): reject a StreamEvents resume cursor ahead of the stream with InvalidArgument (SES-006, #256)

This commit is contained in:
Joseph Doherty
2026-12-03 09:48:27 -05:00
parent 9756ab843e
commit 09da8063a9
6 changed files with 108 additions and 0 deletions
@@ -1113,6 +1113,7 @@ public sealed class MxAccessGatewayService(
SessionManagerErrorCode.CloseFailed => StatusCode.Unavailable,
SessionManagerErrorCode.PermissionDenied => StatusCode.PermissionDenied,
SessionManagerErrorCode.GatewayStopping => StatusCode.Unavailable,
SessionManagerErrorCode.InvalidResumeCursor => StatusCode.InvalidArgument,
_ => StatusCode.Unavailable,
};
@@ -534,6 +534,19 @@ public sealed class SessionEventDistributor : IAsyncDisposable
{
EvictAged();
// A cursor above every sequence this session has produced cannot have come from this
// session's stream (a stale cursor from an earlier session, or a corrupted one). Resuming
// from it would attach a stream whose live filter drops every event until the session
// catches up, with nothing replayed and no gap signalled — a silently dead stream. Refuse
// it before anything is registered so the client learns of the mistake at attach time.
if (afterSequence > _highestSequenceSeen)
{
throw new SessionManagerException(
SessionManagerErrorCode.InvalidResumeCursor,
$"after_worker_sequence {afterSequence} is ahead of the newest event ({_highestSequenceSeen}) session {_sessionId} has produced; "
+ "resume with the last worker_sequence this session delivered, or use 0 for a fresh stream.");
}
List<MxEvent> newer = [];
ulong highestReplayed = afterSequence;
@@ -25,4 +25,12 @@ public enum SessionManagerErrorCode
/// against the restarted gateway.
/// </summary>
GatewayStopping,
/// <summary>
/// A <c>StreamEvents</c> resume cursor (<c>after_worker_sequence</c>) is ahead of every
/// event the session has produced, so it cannot have come from this session's stream.
/// Accepting it would attach a stream that silently drops every event until the session
/// catches up to the bogus cursor. Maps to gRPC <c>InvalidArgument</c>.
/// </summary>
InvalidResumeCursor,
}
@@ -234,6 +234,41 @@ public sealed class GatewayEndToEndReconnectReplayTests(ITestOutputHelper output
Assert.Equal(expectedTail, tail.Select(e => e.WorkerSequence).ToArray());
}
/// <summary>
/// SES-006, end to end: a resume cursor ahead of every event the session has produced is
/// rejected with <c>InvalidArgument</c> rather than attaching a stream that silently drops
/// every live event until the session catches up. The rejected attach leaves the session
/// usable: a fresh stream still attaches.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task StreamEvents_ResumeCursorAheadOfStream_IsRejectedWithInvalidArgument()
{
GatedEventFakeWorkerProcessLauncher launcher = new();
await using ReconnectReplayGatewayServiceFixture fixture = new(launcher, replayBufferCapacity: 16, diagnosticOutput: output.WriteLine);
string sessionId = await OpenSessionAsync(fixture, "reconnect-bogus-cursor");
RpcException rejected = await Assert.ThrowsAsync<RpcException>(async () =>
await fixture.Service.StreamEvents(
new StreamEventsRequest { SessionId = sessionId, AfterWorkerSequence = 50_000 },
new RecordingServerStreamWriter<MxEvent>(),
new TestServerCallContext()));
Assert.Equal(StatusCode.InvalidArgument, rejected.StatusCode);
// The failed attach rolled back its subscriber slot: a fresh stream attaches.
using CancellationTokenSource writerCts = new();
Task streamTask = Task.Run(async () =>
await fixture.Service.StreamEvents(
new StreamEventsRequest { SessionId = sessionId },
new RecordingServerStreamWriter<MxEvent>(),
new TestServerCallContext(cancellationToken: writerCts.Token)));
await fixture.WaitForSubscriberCountAsync(sessionId, n: 1, TestTimeout);
launcher.StopEmitting();
await DetachAsync(writerCts, streamTask);
await CloseAndDrainAsync(fixture, sessionId, Task.CompletedTask, launcher);
}
/// <summary>
/// Regression, end to end: when age eviction has emptied the replay ring, the
/// <c>ReplayGap</c> sentinel carries the next deliverable sequence (highest observed + 1),
@@ -881,6 +881,55 @@ public sealed class SessionEventDistributorTests
Assert.Equal(5ul, liveResume);
}
/// <summary>
/// SES-006: a resume cursor ahead of every event the session has produced is rejected at
/// attach time instead of silently dropping live events until the session catches up. The
/// rejection registers nothing, and a cursor equal to the newest sequence is still accepted.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task RegisterWithReplay_CursorAheadOfStream_IsRejectedAndRegistersNothing()
{
Channel<MxEvent> source = Channel.CreateUnbounded<MxEvent>();
await using SessionEventDistributor distributor = CreateDistributor(
source.Reader,
replayBufferCapacity: 10,
replayRetentionSeconds: 0);
await distributor.StartAsync(CancellationToken.None);
using IEventSubscriberLease primer = distributor.Register();
for (ulong sequence = 1; sequence <= 10; sequence++)
{
source.Writer.TryWrite(Event(sequence));
_ = await ReadOneAsync(primer.Reader);
}
SessionManagerException exception = Assert.Throws<SessionManagerException>(() => distributor.RegisterWithReplay(
1000,
out _,
out _,
out _,
out _));
Assert.Equal(SessionManagerErrorCode.InvalidResumeCursor, exception.ErrorCode);
Assert.Throws<SessionManagerException>(() => distributor.RegisterWithReplay(
ulong.MaxValue,
out _,
out _,
out _,
out _));
// The newest sequence itself is a valid, fully-caught-up cursor.
using IEventSubscriberLease caughtUp = distributor.RegisterWithReplay(
10,
out IReadOnlyList<MxEvent> replay,
out bool gap,
out _,
out ulong liveResume);
Assert.Empty(replay);
Assert.False(gap);
Assert.Equal(10ul, liveResume);
}
/// <summary>When nothing retained is newer than the requested sequence, the live resume watermark equals the requested sequence and no gap is reported.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]