fix(sessions): reject a StreamEvents resume cursor ahead of the stream with InvalidArgument (SES-006, #256)
This commit is contained in:
@@ -297,6 +297,8 @@ Emit order on a resumed stream:
|
||||
|
||||
When `after_worker_sequence` is inside the retained window (nothing was evicted), step 1 is skipped: the stream replays the retained tail then resumes live with no sentinel.
|
||||
|
||||
**A cursor ahead of the stream is rejected.** If `after_worker_sequence` is greater than every `worker_sequence` the session has produced (a cursor carried over from an earlier session, a corrupted one, or `2^64 - 1` from an unsigned `0 - 1`), `StreamEvents` fails the attach with gRPC `InvalidArgument` and registers nothing. Accepting it would attach a stream whose live filter drops every event until the session catches up to the bogus value, with nothing replayed and no gap signalled — a silently dead stream. The cursor equal to the newest sequence is valid (fully caught up). A client that gets this error should discard the cursor and attach fresh (`after_worker_sequence = 0`) after re-snapshotting.
|
||||
|
||||
**`oldest_available_sequence` when the ring is empty.** Age eviction (`ReplayRetentionSeconds`, default 300) and a disabled ring (`ReplayBufferCapacity = 0`) both leave nothing retained, so there is no oldest-retained sequence to report. In that case the sentinel carries the **next sequence that can possibly be delivered** — the highest sequence the distributor has observed plus one — rather than `0`. That keeps `after_worker_sequence = oldest_available_sequence - 1` the single universal resume formula: the follow-up resume lands exactly on the highest observed sequence, replays nothing, reports no gap, and receives every subsequent live event. Reporting `0` here would make an unsigned client compute `2^64 - 1` and then silently receive nothing, because the live filter drops every event at or below that watermark. Nothing is lost relative to reporting `0` — the evicted interval is unrecoverable either way, and the sentinel's job is to tell the client to re-snapshot. `0` remains the value when there is no gap, where the field is meaningless and never emitted.
|
||||
|
||||
The ReplayGap sentinel is emitted **only** on the `StreamEvents` server stream and only to the resuming subscriber — it is never fanned to other subscribers and never appears in `DrainEventsReply` (the diagnostic drain path is untouched). Replay retention itself is bounded by `MxGateway:Events:ReplayBufferCapacity` (count), `ReplayRetentionSeconds` (age) and `ReplayBufferMaxBytes` (summed serialized size, so a burst of large-array events cannot pin memory the count cap would allow); whichever binds first evicts oldest-first. Evicted slots are cleared at once, so an evicted event is released immediately rather than when its slot is next reused. See [Configuration](GatewayConfiguration.md).
|
||||
|
||||
@@ -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]
|
||||
|
||||
Reference in New Issue
Block a user