diff --git a/docs/Sessions.md b/docs/Sessions.md index acea2952..b2e5b97b 100644 --- a/docs/Sessions.md +++ b/docs/Sessions.md @@ -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). diff --git a/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs b/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs index dcb509fd..894abd2d 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs @@ -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, }; diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionEventDistributor.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionEventDistributor.cs index c2f5032a..6523815f 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionEventDistributor.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionEventDistributor.cs @@ -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 newer = []; ulong highestReplayed = afterSequence; diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManagerErrorCode.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManagerErrorCode.cs index d302cf48..6e1c324b 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManagerErrorCode.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManagerErrorCode.cs @@ -25,4 +25,12 @@ public enum SessionManagerErrorCode /// against the restarted gateway. /// GatewayStopping, + + /// + /// A StreamEvents resume cursor (after_worker_sequence) 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 InvalidArgument. + /// + InvalidResumeCursor, } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/GatewayEndToEndReconnectReplayTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/GatewayEndToEndReconnectReplayTests.cs index 6380cc9a..2ff76489 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/GatewayEndToEndReconnectReplayTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/GatewayEndToEndReconnectReplayTests.cs @@ -234,6 +234,41 @@ public sealed class GatewayEndToEndReconnectReplayTests(ITestOutputHelper output Assert.Equal(expectedTail, tail.Select(e => e.WorkerSequence).ToArray()); } + /// + /// SES-006, end to end: a resume cursor ahead of every event the session has produced is + /// rejected with InvalidArgument 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. + /// + /// A task that represents the asynchronous operation. + [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(async () => + await fixture.Service.StreamEvents( + new StreamEventsRequest { SessionId = sessionId, AfterWorkerSequence = 50_000 }, + new RecordingServerStreamWriter(), + 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(), + 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); + } + /// /// Regression, end to end: when age eviction has emptied the replay ring, the /// ReplayGap sentinel carries the next deliverable sequence (highest observed + 1), diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionEventDistributorTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionEventDistributorTests.cs index 4f828c2a..f0b52a89 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionEventDistributorTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionEventDistributorTests.cs @@ -881,6 +881,55 @@ public sealed class SessionEventDistributorTests Assert.Equal(5ul, liveResume); } + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task RegisterWithReplay_CursorAheadOfStream_IsRejectedAndRegistersNothing() + { + Channel source = Channel.CreateUnbounded(); + 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(() => distributor.RegisterWithReplay( + 1000, + out _, + out _, + out _, + out _)); + Assert.Equal(SessionManagerErrorCode.InvalidResumeCursor, exception.ErrorCode); + Assert.Throws(() => 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 replay, + out bool gap, + out _, + out ulong liveResume); + Assert.Empty(replay); + Assert.False(gap); + Assert.Equal(10ul, liveResume); + } + /// When nothing retained is newer than the requested sequence, the live resume watermark equals the requested sequence and no gap is reported. /// A task that represents the asynchronous operation. [Fact]