From d4bcf1e8595d6ab6ce501cb96f0acfd434850ee5 Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 11:12:47 +0100 Subject: [PATCH 1/9] Add opt-in locking for SQL Server legacy checkpoint polls (#31) Restrict READCOMMITTEDLOCK to the two open-ended checkpoint queries used by legacy pollers. Preserve the existing default, bounded reads, stream loading, and other dialects. Co-authored-by: Codex --- Changelog.md | 4 + .../CheckpointReadLockTests.cs | 153 ++++++++++++++++++ .../SqlDialects/MsSqlDialect.cs | 37 ++++- 3 files changed, 192 insertions(+), 2 deletions(-) create mode 100644 src/NEventStore.Persistence.MsSql.Tests/CheckpointReadLockTests.cs diff --git a/Changelog.md b/Changelog.md index 24e574e..2a853f4 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,5 +1,9 @@ # NEventStore.Persistence.Sql +## Unreleased + +- Add an opt-in SQL Server and Azure SQL mitigation for legacy checkpoint polls under `READ_COMMITTED_SNAPSHOT`. Choose `WithDialect(new MsSqlDialect(useReadCommittedLockForCheckpointReads: true))` to request locking for the global and bucket-scoped open-ended checkpoint reads. Polls can wait for an uncommitted insert; this does not guarantee checkpoint publication order. Default behavior, other reads, and the schema are unchanged. [#31](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/31) + ## 10.2.0 - Added explicit support for net8.0,net9.0,net10.0 diff --git a/src/NEventStore.Persistence.MsSql.Tests/CheckpointReadLockTests.cs b/src/NEventStore.Persistence.MsSql.Tests/CheckpointReadLockTests.cs new file mode 100644 index 0000000..51fe876 --- /dev/null +++ b/src/NEventStore.Persistence.MsSql.Tests/CheckpointReadLockTests.cs @@ -0,0 +1,153 @@ +#if NUNIT +using FluentAssertions; +using Microsoft.Data.SqlClient; +using NEventStore.Persistence.AcceptanceTests; +using NEventStore.Persistence.Sql; +using NEventStore.Persistence.Sql.SqlDialects; +using NEventStore.Serialization.Binary; +using NUnit.Framework; + +namespace NEventStore.Persistence.MsSql.Tests; + +[TestFixture] +public class CheckpointReadLockTests +{ + private const string Bucket = "checkpoint-lock"; + private const string Hint = "WITH (READCOMMITTEDLOCK)"; + + [Test] + public void The_option_changes_only_the_two_legacy_poll_queries() + { + var ordinary = new MsSqlDialect(); + var locked = new MsSqlDialect(useReadCommittedLockForCheckpointReads: true); + var explicitlyDisabled = new MsSqlDialect(useReadCommittedLockForCheckpointReads: false); + + ordinary.GetCommitsFromCheckpoint.Should().NotContain(Hint).And.Be(explicitlyDisabled.GetCommitsFromCheckpoint); + ordinary.GetCommitsFromBucketAndCheckpoint.Should().NotContain(Hint).And.Be(explicitlyDisabled.GetCommitsFromBucketAndCheckpoint); + locked.GetCommitsFromCheckpoint.Should().Contain("FROM Commits " + Hint); + locked.GetCommitsFromBucketAndCheckpoint.Should().Contain("FROM Commits " + Hint); + locked.GetCommitsFromStartingRevision.Should().Be(ordinary.GetCommitsFromStartingRevision); + locked.GetCommitsFromInstant.Should().Be(ordinary.GetCommitsFromInstant); + locked.GetCommitsFromToInstant.Should().Be(ordinary.GetCommitsFromToInstant); + locked.GetCommitsFromToCheckpoint.Should().Be(ordinary.GetCommitsFromToCheckpoint); + locked.GetCommitsFromToBucketAndCheckpoint.Should().Be(ordinary.GetCommitsFromToBucketAndCheckpoint); + locked.GetSnapshot.Should().Be(ordinary.GetSnapshot); + locked.PersistCommit.Should().Be(ordinary.PersistCommit); + } + + [TestCase(false, false, true)] + [TestCase(false, true, false)] + [TestCase(true, false, false)] + [TestCase(true, true, true)] + public async Task Checkpoint_poll_waits_for_a_lower_insert_under_rcsi(bool useAsync, bool scoped, bool commit) + { + var db = "NEventStore_Issue31_" + Guid.NewGuid().ToString("N"); + var settings = new SqlConnectionStringBuilder( + Environment.GetEnvironmentVariable("NEventStore.MsSql") + ?? throw new InvalidOperationException("Set NEventStore.MsSql to a test SQL Server.")) + { + InitialCatalog = "master", Pooling = false, Enlist = false + }; + using var admin = new SqlConnection(settings.ConnectionString); + await admin.OpenAsync(); + using var manageDatabase = admin.CreateCommand(); + manageDatabase.CommandText = $"CREATE DATABASE [{db}]"; + await manageDatabase.ExecuteNonQueryAsync(); + + try + { + manageDatabase.CommandText = $"ALTER DATABASE [{db}] SET READ_COMMITTED_SNAPSHOT ON"; + await manageDatabase.ExecuteNonQueryAsync(); + + settings.InitialCatalog = db; + using var ordinary = OpenEngine(settings.ConnectionString, new MsSqlDialect()); + ordinary.Initialize(); + var seed = ordinary.Commit("seed".BuildAttempt(bucketId: Bucket))!; + + using var writer = new SqlConnection(settings.ConnectionString); + await writer.OpenAsync(); + using var transaction = writer.BeginTransaction(); + using var insert = writer.CreateCommand(); + insert.Transaction = transaction; + // Copy a valid serialized commit into a different stream while retaining control of its transaction. + insert.CommandText = """ + INSERT INTO dbo.Commits + (BucketId, StreamId, StreamIdOriginal, StreamRevision, Items, CommitId, CommitSequence, CommitStamp, Headers, Payload) + OUTPUT INSERTED.CheckpointNumber + SELECT BucketId, REPLICATE('a', 40), 'delayed', StreamRevision, Items, NEWID(), CommitSequence, CommitStamp, Headers, Payload + FROM dbo.Commits WHERE CheckpointNumber = @seed; + """; + insert.Parameters.AddWithValue("@seed", seed.CheckpointToken); + long lower = (long)(await insert.ExecuteScalarAsync())!; + var higher = ordinary.Commit("higher".BuildAttempt(bucketId: Bucket))!.CheckpointToken; + higher.Should().BeGreaterThan(lower); + (await Poll(ordinary, seed.CheckpointToken, useAsync, scoped)).Should().Equal(higher); + + settings.ApplicationName = db; + using var locking = OpenEngine(settings.ConnectionString, new MsSqlDialect(useReadCommittedLockForCheckpointReads: true)); + var pending = Task.Run(() => Poll(locking, seed.CheckpointToken, useAsync, scoped)); + try + { + using var check = admin.CreateCommand(); + check.CommandText = """ + SELECT COUNT(*) FROM sys.dm_exec_requests r + JOIN sys.dm_exec_sessions s ON r.session_id = s.session_id + WHERE s.program_name = @application AND r.wait_type LIKE 'LCK_M_%' + AND r.blocking_session_id = @writer; + """; + check.Parameters.AddWithValue("@application", db); + check.Parameters.AddWithValue("@writer", writer.ServerProcessId); + var clock = System.Diagnostics.Stopwatch.StartNew(); + bool waiting = false; + while (!pending.IsCompleted && clock.Elapsed < TimeSpan.FromSeconds(10)) + { + waiting = (int)(await check.ExecuteScalarAsync())! > 0; + if (waiting) break; + await Task.Delay(25); + } + + waiting.Should().BeTrue("the opt-in poll must wait for the lower checkpoint's transaction"); + } + finally + { + if (commit) transaction.Commit(); + else transaction.Rollback(); + // Drain the poll before disposing its engine or dropping the test database. + await pending; + } + + (await pending).Should().Equal(commit ? new[] { lower, higher } : new[] { higher }); + (await Poll(ordinary, higher, useAsync, scoped)).Should().BeEmpty(); + } + finally + { + manageDatabase.CommandText = $"DROP DATABASE [{db}]"; + await manageDatabase.ExecuteNonQueryAsync(); + } + } + + private static IPersistStreams OpenEngine(string connectionString, MsSqlDialect dialect) + { + var serializer = new BinarySerializer(); + return new SqlPersistenceFactory(new NetStandardConnectionFactory(SqlClientFactory.Instance, connectionString), + serializer, new DefaultEventSerializer(serializer), dialect).Build(); + } + + private static async Task Poll(IPersistStreams engine, long after, bool useAsync, bool scoped) + { + if (!useAsync) + return (scoped ? engine.GetFrom(Bucket, after) : engine.GetFrom(after)) + .Select(commit => commit.CheckpointToken).ToArray(); + + var result = new List(); + var observer = new LambdaAsyncObserver((commit, _) => + { + result.Add(commit.CheckpointToken); + return Task.FromResult(true); + }, (error, _) => Task.FromException(error)); + if (scoped) await engine.GetFromAsync(Bucket, after, observer, CancellationToken.None); + else await engine.GetFromAsync(after, observer, CancellationToken.None); + return result.ToArray(); + } +} +#endif diff --git a/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs b/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs index f1ed780..b535e70 100644 --- a/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs +++ b/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs @@ -12,6 +12,27 @@ public class MsSqlDialect : CommonSqlDialect { private const int UniqueIndexViolation = 2601; private const int UniqueKeyViolation = 2627; + private readonly bool _useReadCommittedLockForCheckpointReads; + + /// Initializes the dialect with unchanged database read semantics. + public MsSqlDialect() : this(false) + { + } + + /// Initializes the dialect with optional locking for legacy checkpoint reads. + /// + /// to request lock-based READ COMMITTED for open-ended checkpoint reads; + /// otherwise, to preserve the database's read behavior. + /// + /// + /// Locking reads may wait on an uncommitted insert under READ_COMMITTED_SNAPSHOT. This is + /// a mitigation for legacy polling, not a guarantee of checkpoint publication order. + /// + public MsSqlDialect(bool useReadCommittedLockForCheckpointReads) + { + _useReadCommittedLockForCheckpointReads = useReadCommittedLockForCheckpointReads; + } + /// public override string InitializeStorage { @@ -45,7 +66,7 @@ public override string PersistCommit /// public override string GetCommitsFromCheckpoint { - get { return CommonTableExpressionPaging(base.GetCommitsFromCheckpoint); } + get { return LegacyCheckpointPaging(base.GetCommitsFromCheckpoint); } } /// public override string GetCommitsFromToCheckpoint @@ -55,7 +76,7 @@ public override string GetCommitsFromToCheckpoint /// public override string GetCommitsFromBucketAndCheckpoint { - get { return CommonTableExpressionPaging(base.GetCommitsFromBucketAndCheckpoint); } + get { return LegacyCheckpointPaging(base.GetCommitsFromBucketAndCheckpoint); } } /// public override string GetCommitsFromToBucketAndCheckpoint @@ -68,6 +89,18 @@ public override string GetStreamsRequiringSnapshots get { return NaturalPaging(base.GetStreamsRequiringSnapshots); } } + /// Builds the paged query used to resume a legacy poll from a checkpoint. + /// The open-ended global or bucket-scoped checkpoint query. + /// The SQL Server query with the configured read semantics. + private string LegacyCheckpointPaging(string query) + { + // Only these queries advance a legacy poller. Do not make unrelated reads wait on writes. + if (_useReadCommittedLockForCheckpointReads) + query = query.Replace("FROM Commits", "FROM Commits WITH (READCOMMITTEDLOCK)"); + + return CommonTableExpressionPaging(query); + } + private static string NaturalPaging(string query) { return "SET ROWCOUNT @Limit;\n" + RemovePaging(query); From e544ccdbb67714a62e6e2d3dd6ffa2be95e5e627 Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 11:38:38 +0100 Subject: [PATCH 2/9] Apply opt-in SQL Server locking to all public commit reads Cover custom consumers using checkpoint ranges, date bounds or stream revisions as well as the built-in pollers. Keep the default, paging, snapshot queries and writes unchanged. Co-authored-by: Codex --- Changelog.md | 2 +- .../CheckpointReadLockTests.cs | 124 +++++++++++++----- .../SqlDialects/MsSqlDialect.cs | 45 ++++--- 3 files changed, 115 insertions(+), 56 deletions(-) diff --git a/Changelog.md b/Changelog.md index 2a853f4..3de22aa 100644 --- a/Changelog.md +++ b/Changelog.md @@ -2,7 +2,7 @@ ## Unreleased -- Add an opt-in SQL Server and Azure SQL mitigation for legacy checkpoint polls under `READ_COMMITTED_SNAPSHOT`. Choose `WithDialect(new MsSqlDialect(useReadCommittedLockForCheckpointReads: true))` to request locking for the global and bucket-scoped open-ended checkpoint reads. Polls can wait for an uncommitted insert; this does not guarantee checkpoint publication order. Default behavior, other reads, and the schema are unchanged. [#31](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/31) +- Add an opt-in SQL Server and Azure SQL mitigation for commit readers under `READ_COMMITTED_SNAPSHOT`. Choose `WithDialect(new MsSqlDialect(useReadCommittedLockForCommitReads: true))` to request locking for open-ended and bounded checkpoint reads, date-based reads, and stream revision reads. These reads can wait for an uncommitted insert; this does not guarantee checkpoint publication order. Default behavior, write and snapshot queries, and the schema are unchanged. [#31](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/31) ## 10.2.0 diff --git a/src/NEventStore.Persistence.MsSql.Tests/CheckpointReadLockTests.cs b/src/NEventStore.Persistence.MsSql.Tests/CheckpointReadLockTests.cs index 51fe876..72fa2b6 100644 --- a/src/NEventStore.Persistence.MsSql.Tests/CheckpointReadLockTests.cs +++ b/src/NEventStore.Persistence.MsSql.Tests/CheckpointReadLockTests.cs @@ -13,33 +13,59 @@ namespace NEventStore.Persistence.MsSql.Tests; public class CheckpointReadLockTests { private const string Bucket = "checkpoint-lock"; + private const string DelayedStream = "delayed"; + private static readonly DateTime CommitTime = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + public enum Query + { + Checkpoint, + BoundedCheckpoint, + FromDate, + DateRange, + StreamRevision + } private const string Hint = "WITH (READCOMMITTEDLOCK)"; [Test] - public void The_option_changes_only_the_two_legacy_poll_queries() + public void The_option_applies_only_to_all_public_commit_read_queries() { var ordinary = new MsSqlDialect(); - var locked = new MsSqlDialect(useReadCommittedLockForCheckpointReads: true); - var explicitlyDisabled = new MsSqlDialect(useReadCommittedLockForCheckpointReads: false); - - ordinary.GetCommitsFromCheckpoint.Should().NotContain(Hint).And.Be(explicitlyDisabled.GetCommitsFromCheckpoint); - ordinary.GetCommitsFromBucketAndCheckpoint.Should().NotContain(Hint).And.Be(explicitlyDisabled.GetCommitsFromBucketAndCheckpoint); - locked.GetCommitsFromCheckpoint.Should().Contain("FROM Commits " + Hint); - locked.GetCommitsFromBucketAndCheckpoint.Should().Contain("FROM Commits " + Hint); - locked.GetCommitsFromStartingRevision.Should().Be(ordinary.GetCommitsFromStartingRevision); - locked.GetCommitsFromInstant.Should().Be(ordinary.GetCommitsFromInstant); - locked.GetCommitsFromToInstant.Should().Be(ordinary.GetCommitsFromToInstant); - locked.GetCommitsFromToCheckpoint.Should().Be(ordinary.GetCommitsFromToCheckpoint); - locked.GetCommitsFromToBucketAndCheckpoint.Should().Be(ordinary.GetCommitsFromToBucketAndCheckpoint); + var locked = new MsSqlDialect(useReadCommittedLockForCommitReads: true); + var explicitlyDisabled = new MsSqlDialect(useReadCommittedLockForCommitReads: false); + + Func[] commitReads = + [ + d => d.GetCommitsFromCheckpoint, + d => d.GetCommitsFromBucketAndCheckpoint, + d => d.GetCommitsFromToCheckpoint, + d => d.GetCommitsFromToBucketAndCheckpoint, + d => d.GetCommitsFromStartingRevision, + d => d.GetCommitsFromInstant, + d => d.GetCommitsFromToInstant + ]; + foreach (var read in commitReads) + { + read(ordinary).Should().NotContain(Hint).And.Be(read(explicitlyDisabled)); + read(locked).Should().Contain("FROM Commits " + Hint) + .And.Be(read(ordinary).Replace("FROM Commits", "FROM Commits " + Hint)); + } + locked.GetSnapshot.Should().Be(ordinary.GetSnapshot); + locked.GetStreamsRequiringSnapshots.Should().Be(ordinary.GetStreamsRequiringSnapshots); locked.PersistCommit.Should().Be(ordinary.PersistCommit); } - [TestCase(false, false, true)] - [TestCase(false, true, false)] - [TestCase(true, false, false)] - [TestCase(true, true, true)] - public async Task Checkpoint_poll_waits_for_a_lower_insert_under_rcsi(bool useAsync, bool scoped, bool commit) + [TestCase(Query.Checkpoint, false, false, true)] + [TestCase(Query.Checkpoint, false, true, false)] + [TestCase(Query.Checkpoint, true, false, false)] + [TestCase(Query.Checkpoint, true, true, true)] + [TestCase(Query.BoundedCheckpoint, false, false, true)] + [TestCase(Query.BoundedCheckpoint, true, true, false)] + [TestCase(Query.FromDate, false, true, true)] + [TestCase(Query.DateRange, false, true, false)] + [TestCase(Query.StreamRevision, false, true, true)] + [TestCase(Query.StreamRevision, true, true, false)] + public async Task Commit_read_waits_for_a_matching_uncommitted_insert_under_rcsi(Query query, bool useAsync, bool scoped, bool commit) { var db = "NEventStore_Issue31_" + Guid.NewGuid().ToString("N"); var settings = new SqlConnectionStringBuilder( @@ -62,7 +88,7 @@ public async Task Checkpoint_poll_waits_for_a_lower_insert_under_rcsi(bool useAs settings.InitialCatalog = db; using var ordinary = OpenEngine(settings.ConnectionString, new MsSqlDialect()); ordinary.Initialize(); - var seed = ordinary.Commit("seed".BuildAttempt(bucketId: Bucket))!; + var seed = ordinary.Commit("seed".BuildAttempt(CommitTime, Bucket))!; using var writer = new SqlConnection(settings.ConnectionString); await writer.OpenAsync(); @@ -74,18 +100,26 @@ public async Task Checkpoint_poll_waits_for_a_lower_insert_under_rcsi(bool useAs INSERT INTO dbo.Commits (BucketId, StreamId, StreamIdOriginal, StreamRevision, Items, CommitId, CommitSequence, CommitStamp, Headers, Payload) OUTPUT INSERTED.CheckpointNumber - SELECT BucketId, REPLICATE('a', 40), 'delayed', StreamRevision, Items, NEWID(), CommitSequence, CommitStamp, Headers, Payload + SELECT BucketId, @streamHash, @stream, StreamRevision, Items, NEWID(), CommitSequence, CommitStamp, Headers, Payload FROM dbo.Commits WHERE CheckpointNumber = @seed; """; insert.Parameters.AddWithValue("@seed", seed.CheckpointToken); + insert.Parameters.AddWithValue("@streamHash", new Sha1StreamIdHasher().GetHash(DelayedStream)); + insert.Parameters.AddWithValue("@stream", DelayedStream); long lower = (long)(await insert.ExecuteScalarAsync())!; - var higher = ordinary.Commit("higher".BuildAttempt(bucketId: Bucket))!.CheckpointToken; + var higher = ordinary.Commit("higher".BuildAttempt(CommitTime.AddMilliseconds(10), Bucket))!.CheckpointToken; higher.Should().BeGreaterThan(lower); - (await Poll(ordinary, seed.CheckpointToken, useAsync, scoped)).Should().Equal(higher); + long[] ordinaryResult = query switch + { + Query.StreamRevision => [], + Query.FromDate or Query.DateRange => [seed.CheckpointToken, higher], + _ => [higher] + }; + (await Read(ordinary, query, seed.CheckpointToken, higher, useAsync, scoped)).Should().Equal(ordinaryResult); settings.ApplicationName = db; - using var locking = OpenEngine(settings.ConnectionString, new MsSqlDialect(useReadCommittedLockForCheckpointReads: true)); - var pending = Task.Run(() => Poll(locking, seed.CheckpointToken, useAsync, scoped)); + using var locking = OpenEngine(settings.ConnectionString, new MsSqlDialect(useReadCommittedLockForCommitReads: true)); + var pending = Task.Run(() => Read(locking, query, seed.CheckpointToken, higher, useAsync, scoped)); try { using var check = admin.CreateCommand(); @@ -106,7 +140,7 @@ SELECT COUNT(*) FROM sys.dm_exec_requests r await Task.Delay(25); } - waiting.Should().BeTrue("the opt-in poll must wait for the lower checkpoint's transaction"); + waiting.Should().BeTrue("the opt-in read must wait for the uncommitted matching row"); } finally { @@ -116,8 +150,10 @@ SELECT COUNT(*) FROM sys.dm_exec_requests r await pending; } - (await pending).Should().Equal(commit ? new[] { lower, higher } : new[] { higher }); - (await Poll(ordinary, higher, useAsync, scoped)).Should().BeEmpty(); + var expected = commit ? ordinaryResult.Append(lower).OrderBy(checkpoint => checkpoint).ToArray() : ordinaryResult; + (await pending).Should().Equal(expected); + if (query == Query.Checkpoint) + (await Read(ordinary, query, higher, higher, useAsync, scoped)).Should().BeEmpty(); } finally { @@ -128,16 +164,31 @@ SELECT COUNT(*) FROM sys.dm_exec_requests r private static IPersistStreams OpenEngine(string connectionString, MsSqlDialect dialect) { +#if NET8_0_OR_GREATER + // The fixture only serializes its own test commits, including when run by itself. + AppContext.SetSwitch("System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization", true); +#endif var serializer = new BinarySerializer(); return new SqlPersistenceFactory(new NetStandardConnectionFactory(SqlClientFactory.Instance, connectionString), serializer, new DefaultEventSerializer(serializer), dialect).Build(); } - private static async Task Poll(IPersistStreams engine, long after, bool useAsync, bool scoped) + private static async Task Read(IPersistStreams engine, Query query, long after, long upper, bool useAsync, bool scoped) { if (!useAsync) - return (scoped ? engine.GetFrom(Bucket, after) : engine.GetFrom(after)) - .Select(commit => commit.CheckpointToken).ToArray(); + { +#pragma warning disable CS0618 // Verify the existing date-based commit-read APIs as well. + var commits = query switch + { + Query.BoundedCheckpoint => scoped ? engine.GetFromTo(Bucket, after, upper) : engine.GetFromTo(after, upper), + Query.FromDate => engine.GetFrom(Bucket, CommitTime), + Query.DateRange => engine.GetFromTo(Bucket, CommitTime, CommitTime.AddSeconds(1)), + Query.StreamRevision => engine.GetFrom(Bucket, DelayedStream, 1, 1), + _ => scoped ? engine.GetFrom(Bucket, after) : engine.GetFrom(after) + }; +#pragma warning restore CS0618 + return commits.Select(commit => commit.CheckpointToken).ToArray(); + } var result = new List(); var observer = new LambdaAsyncObserver((commit, _) => @@ -145,8 +196,17 @@ private static async Task Poll(IPersistStreams engine, long after, bool result.Add(commit.CheckpointToken); return Task.FromResult(true); }, (error, _) => Task.FromException(error)); - if (scoped) await engine.GetFromAsync(Bucket, after, observer, CancellationToken.None); - else await engine.GetFromAsync(after, observer, CancellationToken.None); + var read = query switch + { + Query.BoundedCheckpoint => scoped + ? engine.GetFromToAsync(Bucket, after, upper, observer, CancellationToken.None) + : engine.GetFromToAsync(after, upper, observer, CancellationToken.None), + Query.StreamRevision => engine.GetFromAsync(Bucket, DelayedStream, 1, 1, observer, CancellationToken.None), + _ => scoped + ? engine.GetFromAsync(Bucket, after, observer, CancellationToken.None) + : engine.GetFromAsync(after, observer, CancellationToken.None) + }; + await read; return result.ToArray(); } } diff --git a/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs b/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs index b535e70..a67bbcc 100644 --- a/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs +++ b/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs @@ -12,25 +12,25 @@ public class MsSqlDialect : CommonSqlDialect { private const int UniqueIndexViolation = 2601; private const int UniqueKeyViolation = 2627; - private readonly bool _useReadCommittedLockForCheckpointReads; + private readonly bool _useReadCommittedLockForCommitReads; /// Initializes the dialect with unchanged database read semantics. public MsSqlDialect() : this(false) { } - /// Initializes the dialect with optional locking for legacy checkpoint reads. - /// - /// to request lock-based READ COMMITTED for open-ended checkpoint reads; + /// Initializes the dialect with optional locking for commit reads. + /// + /// to request lock-based READ COMMITTED for checkpoint, date-range, and stream-revision commit reads; /// otherwise, to preserve the database's read behavior. /// /// /// Locking reads may wait on an uncommitted insert under READ_COMMITTED_SNAPSHOT. This is /// a mitigation for legacy polling, not a guarantee of checkpoint publication order. /// - public MsSqlDialect(bool useReadCommittedLockForCheckpointReads) + public MsSqlDialect(bool useReadCommittedLockForCommitReads) { - _useReadCommittedLockForCheckpointReads = useReadCommittedLockForCheckpointReads; + _useReadCommittedLockForCommitReads = useReadCommittedLockForCommitReads; } /// @@ -46,17 +46,17 @@ public override string GetSnapshot /// public override string GetCommitsFromStartingRevision { - get { return NaturalPaging(base.GetCommitsFromStartingRevision); } + get { return NaturalPaging(AddReadCommittedLockToFromCommits(base.GetCommitsFromStartingRevision)); } } /// public override string GetCommitsFromInstant { - get { return CommonTableExpressionPaging(base.GetCommitsFromInstant); } + get { return CommonTableExpressionPaging(AddReadCommittedLockToFromCommits(base.GetCommitsFromInstant)); } } /// public override string GetCommitsFromToInstant { - get { return CommonTableExpressionPaging(base.GetCommitsFromToInstant); } + get { return CommonTableExpressionPaging(AddReadCommittedLockToFromCommits(base.GetCommitsFromToInstant)); } } /// public override string PersistCommit @@ -66,22 +66,22 @@ public override string PersistCommit /// public override string GetCommitsFromCheckpoint { - get { return LegacyCheckpointPaging(base.GetCommitsFromCheckpoint); } + get { return CommonTableExpressionPaging(AddReadCommittedLockToFromCommits(base.GetCommitsFromCheckpoint)); } } /// public override string GetCommitsFromToCheckpoint { - get { return CommonTableExpressionPaging(base.GetCommitsFromToCheckpoint); } + get { return CommonTableExpressionPaging(AddReadCommittedLockToFromCommits(base.GetCommitsFromToCheckpoint)); } } /// public override string GetCommitsFromBucketAndCheckpoint { - get { return LegacyCheckpointPaging(base.GetCommitsFromBucketAndCheckpoint); } + get { return CommonTableExpressionPaging(AddReadCommittedLockToFromCommits(base.GetCommitsFromBucketAndCheckpoint)); } } /// public override string GetCommitsFromToBucketAndCheckpoint { - get { return CommonTableExpressionPaging(base.GetCommitsFromToBucketAndCheckpoint); } + get { return CommonTableExpressionPaging(AddReadCommittedLockToFromCommits(base.GetCommitsFromToBucketAndCheckpoint)); } } /// public override string GetStreamsRequiringSnapshots @@ -89,16 +89,15 @@ public override string GetStreamsRequiringSnapshots get { return NaturalPaging(base.GetStreamsRequiringSnapshots); } } - /// Builds the paged query used to resume a legacy poll from a checkpoint. - /// The open-ended global or bucket-scoped checkpoint query. - /// The SQL Server query with the configured read semantics. - private string LegacyCheckpointPaging(string query) - { - // Only these queries advance a legacy poller. Do not make unrelated reads wait on writes. - if (_useReadCommittedLockForCheckpointReads) - query = query.Replace("FROM Commits", "FROM Commits WITH (READCOMMITTEDLOCK)"); - - return CommonTableExpressionPaging(query); + /// Applies the optional READCOMMITTEDLOCK hint to a public commit-read query. + /// A SQL Server query that returns commits to the caller. + /// The query with the configured read semantics. + private string AddReadCommittedLockToFromCommits(string query) + { + // Custom consumers can use any commit-read API. Leave writes and snapshot queries alone. + return _useReadCommittedLockForCommitReads + ? query.Replace("FROM Commits", "FROM Commits WITH (READCOMMITTEDLOCK)") + : query; } private static string NaturalPaging(string query) From a658b8b34205eb5d971316a72f4844050bd3f936 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 24 Jun 2026 03:43:42 +0000 Subject: [PATCH 3/9] ci: bump actions/checkout from 6 to 7 Bumps [actions/checkout](https://github.com/actions/checkout) from 6 to 7. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v6...v7) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/ci.yml | 4 ++-- .github/workflows/pack-and-publish.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 30d4290..ea14456 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,7 +28,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: fetch-depth: 0 fetch-tags: true @@ -152,7 +152,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: fetch-depth: 0 fetch-tags: true diff --git a/.github/workflows/pack-and-publish.yml b/.github/workflows/pack-and-publish.yml index ad27903..257724d 100644 --- a/.github/workflows/pack-and-publish.yml +++ b/.github/workflows/pack-and-publish.yml @@ -24,7 +24,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: ref: ${{ inputs.branch }} fetch-depth: 0 From 54b85fee4227e72497feb73fc3df69dce9e1698b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 24 Jun 2026 03:43:39 +0000 Subject: [PATCH 4/9] ci: bump actions/cache from 5 to 6 Bumps [actions/cache](https://github.com/actions/cache) from 5 to 6. - [Release notes](https://github.com/actions/cache/releases) - [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md) - [Commits](https://github.com/actions/cache/compare/v5...v6) --- updated-dependencies: - dependency-name: actions/cache dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/ci.yml | 4 ++-- .github/workflows/pack-and-publish.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ea14456..68cc16b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,7 @@ jobs: 10.0.x - name: Cache NuGet packages - uses: actions/cache@v5 + uses: actions/cache@v6 with: path: ~/.nuget/packages key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', '**/*.props', '**/*.targets', '.config/dotnet-tools.json') }} @@ -167,7 +167,7 @@ jobs: 10.0.x - name: Cache NuGet packages - uses: actions/cache@v5 + uses: actions/cache@v6 with: path: ~/.nuget/packages key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', '**/*.props', '**/*.targets', '.config/dotnet-tools.json') }} diff --git a/.github/workflows/pack-and-publish.yml b/.github/workflows/pack-and-publish.yml index 257724d..2b70ce4 100644 --- a/.github/workflows/pack-and-publish.yml +++ b/.github/workflows/pack-and-publish.yml @@ -39,7 +39,7 @@ jobs: 10.0.x - name: Cache NuGet packages - uses: actions/cache@v5 + uses: actions/cache@v6 with: path: ~/.nuget/packages key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', '**/*.props', '**/*.targets', '.config/dotnet-tools.json') }} From ce1addb8a9b28ae3d22127729f7151d715d6b320 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 22 Jul 2026 03:43:56 +0000 Subject: [PATCH 5/9] ci: bump actions/setup-dotnet from 5 to 6 Bumps [actions/setup-dotnet](https://github.com/actions/setup-dotnet) from 5 to 6. - [Release notes](https://github.com/actions/setup-dotnet/releases) - [Commits](https://github.com/actions/setup-dotnet/compare/v5...v6) --- updated-dependencies: - dependency-name: actions/setup-dotnet dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/ci.yml | 4 ++-- .github/workflows/pack-and-publish.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 68cc16b..0d1c235 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,7 +35,7 @@ jobs: submodules: recursive - name: Setup .NET SDKs - uses: actions/setup-dotnet@v5 + uses: actions/setup-dotnet@v6 with: dotnet-version: | 8.0.x @@ -159,7 +159,7 @@ jobs: submodules: recursive - name: Setup .NET SDKs - uses: actions/setup-dotnet@v5 + uses: actions/setup-dotnet@v6 with: dotnet-version: | 8.0.x diff --git a/.github/workflows/pack-and-publish.yml b/.github/workflows/pack-and-publish.yml index 2b70ce4..4a81b97 100644 --- a/.github/workflows/pack-and-publish.yml +++ b/.github/workflows/pack-and-publish.yml @@ -31,7 +31,7 @@ jobs: submodules: recursive - name: Setup .NET - uses: actions/setup-dotnet@v5 + uses: actions/setup-dotnet@v6 with: dotnet-version: | 8.0.x From 66b926fb0b7d054175d4398225455e60631ae121 Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 12:07:52 +0100 Subject: [PATCH 6/9] Use keyset paging for checkpoint reads across SQL dialects (#63) Seek after each page's last checkpoint with the bucket and upper bound preserved. Keep legacy offset SQL for custom dialects and statements, and omit the limit for PageSize = 0. Co-authored-by: Codex --- Changelog.md | 2 + docs/Checkpoint-Seek-Paging.md | 36 ++++++++ ...tStore.Persistence.MsSql.Core.Tests.csproj | 1 + ...tStore.Persistence.MySql.Core.Tests.csproj | 1 + ...Store.Persistence.Oracle.Core.Tests.csproj | 1 + ...e.Persistence.PostgreSql.Core.Tests.csproj | 1 + ...entStore.Persistence.Sql.Core.Tests.csproj | 2 + .../PersistenceTests.CheckpointPaging.cs | 89 +++++++++++++++++++ .../SqlDialects/CheckpointKeysetQuery.cs | 46 ++++++++++ .../SqlDialects/CommonDbStatement.cs | 49 ++++++++-- .../SqlDialects/MsSqlDialect.cs | 2 +- .../SqlDialects/PagedEnumerationCollection.cs | 15 +++- .../SqlPersistenceEngine.Async.cs | 24 +++-- .../SqlPersistenceEngine.cs | 40 +++++++-- .../CheckpointPagingDeletionTests.cs | 71 +++++++++++++++ ...Store.Persistence.Sqlite.Core.Tests.csproj | 1 + 16 files changed, 355 insertions(+), 26 deletions(-) create mode 100644 docs/Checkpoint-Seek-Paging.md create mode 100644 src/NEventStore.Persistence.Sql.Tests/PersistenceTests.CheckpointPaging.cs create mode 100644 src/NEventStore.Persistence.Sql/SqlDialects/CheckpointKeysetQuery.cs create mode 100644 src/NEventStore.Persistence.Sqlite.Tests/CheckpointPagingDeletionTests.cs diff --git a/Changelog.md b/Changelog.md index 3de22aa..2ee31b4 100644 --- a/Changelog.md +++ b/Changelog.md @@ -2,6 +2,8 @@ ## Unreleased +- Use ordered keyset paging for checkpoint reads on SQL Server, PostgreSQL, MySQL, Oracle, and SQLite. A deletion before the next page no longer shifts it, and zero page size reads without a page limit. Keep the existing behavior for custom dialects and non-checkpoint reads. No schema change. [#63](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/63) + - Add an opt-in SQL Server and Azure SQL mitigation for commit readers under `READ_COMMITTED_SNAPSHOT`. Choose `WithDialect(new MsSqlDialect(useReadCommittedLockForCommitReads: true))` to request locking for open-ended and bounded checkpoint reads, date-based reads, and stream revision reads. These reads can wait for an uncommitted insert; this does not guarantee checkpoint publication order. Default behavior, write and snapshot queries, and the schema are unchanged. [#31](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/31) ## 10.2.0 diff --git a/docs/Checkpoint-Seek-Paging.md b/docs/Checkpoint-Seek-Paging.md new file mode 100644 index 0000000..e4b6ae6 --- /dev/null +++ b/docs/Checkpoint-Seek-Paging.md @@ -0,0 +1,36 @@ +# Checkpoint seek paging + +The built-in SQL Server, PostgreSQL, MySQL, Oracle, and SQLite dialects read the +next page with `CheckpointNumber > last returned checkpoint`, ordered by +checkpoint. Bucket filters and inclusive upper bounds are carried across +pages. `PageSize = 0` sends one ordered query with no page limit. + +This changes only checkpoint reads. Older custom dialects and statement +implementations keep their existing offset SQL and behavior. Seek paging +does not make a late lower checkpoint visible before a higher one, does not +provide snapshot isolation across pages, and does not restore already deleted +commits. Ordered publication is tracked in [#72](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/72). + +## Large catch-up comparison + +1. Start the database services using [the Docker instructions](../docker/Readme.md) + or mirror the images and connection settings used by + [the CI workflow](../.github/workflows/ci.yml). SQLite uses a local file. + Use disposable stores and the same schema and indexes in both runs. +2. Seed at least 500,000 commits with identical payloads and checkpoints + distributed across multiple buckets. Keep the fixture read-only during + the performance comparison. Compare the parent revision (offset) with the + candidate (seek), on the same connection settings and runtime. +3. For each revision, read the same open-ended and bounded windows, globally + and for a quiet bucket, with page sizes 128 and 512. Test both a full + catch-up and deep pages after at least 400,000 global checkpoints. + Verify that returned checkpoints match in order before comparing timings. +4. Warm up each query shape, alternate the order of baseline and candidate, + and record at least 20 timings. Report total catch-up time, median and + p95 deep-page latency, and where available execution-plan rows examined + or logical reads. Don't compare the default offset against a seek on a + different index or with different result counts. +5. Check correctness separately: delete an already returned row between + pages. The next surviving commit must still be returned. This scenario + is covered by the SQLite WAL regression and is not part of the timing + sample. diff --git a/src/NEventStore.Persistence.MsSql.Tests/NEventStore.Persistence.MsSql.Core.Tests.csproj b/src/NEventStore.Persistence.MsSql.Tests/NEventStore.Persistence.MsSql.Core.Tests.csproj index f1060ce..b3af844 100644 --- a/src/NEventStore.Persistence.MsSql.Tests/NEventStore.Persistence.MsSql.Core.Tests.csproj +++ b/src/NEventStore.Persistence.MsSql.Tests/NEventStore.Persistence.MsSql.Core.Tests.csproj @@ -48,6 +48,7 @@ + diff --git a/src/NEventStore.Persistence.MySql.Tests/NEventStore.Persistence.MySql.Core.Tests.csproj b/src/NEventStore.Persistence.MySql.Tests/NEventStore.Persistence.MySql.Core.Tests.csproj index f367d41..123d687 100644 --- a/src/NEventStore.Persistence.MySql.Tests/NEventStore.Persistence.MySql.Core.Tests.csproj +++ b/src/NEventStore.Persistence.MySql.Tests/NEventStore.Persistence.MySql.Core.Tests.csproj @@ -47,6 +47,7 @@ + diff --git a/src/NEventStore.Persistence.Oracle.Tests/NEventStore.Persistence.Oracle.Core.Tests.csproj b/src/NEventStore.Persistence.Oracle.Tests/NEventStore.Persistence.Oracle.Core.Tests.csproj index e50c184..ab7af24 100644 --- a/src/NEventStore.Persistence.Oracle.Tests/NEventStore.Persistence.Oracle.Core.Tests.csproj +++ b/src/NEventStore.Persistence.Oracle.Tests/NEventStore.Persistence.Oracle.Core.Tests.csproj @@ -50,6 +50,7 @@ + diff --git a/src/NEventStore.Persistence.PostgreSql.Tests/NEventStore.Persistence.PostgreSql.Core.Tests.csproj b/src/NEventStore.Persistence.PostgreSql.Tests/NEventStore.Persistence.PostgreSql.Core.Tests.csproj index 9f4ac37..83ee2fd 100644 --- a/src/NEventStore.Persistence.PostgreSql.Tests/NEventStore.Persistence.PostgreSql.Core.Tests.csproj +++ b/src/NEventStore.Persistence.PostgreSql.Tests/NEventStore.Persistence.PostgreSql.Core.Tests.csproj @@ -44,6 +44,7 @@ + diff --git a/src/NEventStore.Persistence.Sql.Tests/NEventStore.Persistence.Sql.Core.Tests.csproj b/src/NEventStore.Persistence.Sql.Tests/NEventStore.Persistence.Sql.Core.Tests.csproj index 5e96b09..671af95 100644 --- a/src/NEventStore.Persistence.Sql.Tests/NEventStore.Persistence.Sql.Core.Tests.csproj +++ b/src/NEventStore.Persistence.Sql.Tests/NEventStore.Persistence.Sql.Core.Tests.csproj @@ -11,6 +11,7 @@ + @@ -23,6 +24,7 @@ + diff --git a/src/NEventStore.Persistence.Sql.Tests/PersistenceTests.CheckpointPaging.cs b/src/NEventStore.Persistence.Sql.Tests/PersistenceTests.CheckpointPaging.cs new file mode 100644 index 0000000..9e002a9 --- /dev/null +++ b/src/NEventStore.Persistence.Sql.Tests/PersistenceTests.CheckpointPaging.cs @@ -0,0 +1,89 @@ +#if NUNIT +using FluentAssertions; +using NUnit.Framework; + +namespace NEventStore.Persistence.AcceptanceTests; + +[TestFixture] +[NonParallelizable] +public sealed class CheckpointPagingTests +{ + private const string SelectedBucket = "paging-a"; + private const string OtherBucket = "paging-b"; + + [TestCase(2, false)] + [TestCase(2, true)] + [TestCase(0, false)] + [TestCase(0, true)] + public async Task Checkpoint_reads_preserve_order_scope_gaps_and_range_bounds(int pageSize, bool useAsync) + { + using var fixture = new PersistenceEngineFixture(); + fixture.Initialize(pageSize); + var engine = fixture.Persistence!; + ICommit Write(string name, string bucket) => engine.Commit(name.BuildAttempt(bucketId: bucket))!; + + var start = Write("start", SelectedBucket); + var b1 = Write("b1", OtherBucket); + var a1 = Write("a1", SelectedBucket); + var gap = Write("gap", SelectedBucket); + var b2 = Write("b2", OtherBucket); + var a2 = Write("a2", SelectedBucket); + var b3 = Write("b3", OtherBucket); + var a3 = Write("a3", SelectedBucket); + var a4 = Write("a4", SelectedBucket); + engine.DeleteStream(gap.BucketId, gap.StreamId); + + var after = start.CheckpointToken; + var upper = a3.CheckpointToken; + (await ReadAsync(engine, after, useAsync: useAsync)) + .Should().Equal(b1.CheckpointToken, a1.CheckpointToken, b2.CheckpointToken, a2.CheckpointToken, b3.CheckpointToken, upper, a4.CheckpointToken); + (await ReadAsync(engine, after, bucket: SelectedBucket, useAsync: useAsync)) + .Should().Equal(a1.CheckpointToken, a2.CheckpointToken, upper, a4.CheckpointToken); + (await ReadAsync(engine, after, upper: upper, useAsync: useAsync)) + .Should().Equal(b1.CheckpointToken, a1.CheckpointToken, b2.CheckpointToken, a2.CheckpointToken, b3.CheckpointToken, upper); + (await ReadAsync(engine, after, upper: upper, bucket: SelectedBucket, useAsync: useAsync)) + .Should().Equal(a1.CheckpointToken, a2.CheckpointToken, upper); + (await ReadAsync(engine, upper, upper: upper, bucket: SelectedBucket, useAsync: useAsync)) + .Should().BeEmpty(); + } + + internal static async Task ReadAsync(IPersistStreams engine, long after, long? upper = null, + string? bucket = null, bool useAsync = false, Action? onRead = null) + { + var result = new List(); + void Record(ICommit commit) + { + result.Add(commit.CheckpointToken); + onRead?.Invoke(commit); + } + + if (!useAsync) + { + var commits = (bucket, upper) switch + { + (null, null) => engine.GetFrom(after), + (null, long end) => engine.GetFromTo(after, end), + (string id, null) => engine.GetFrom(id, after), + (string id, long end) => engine.GetFromTo(id, after, end) + }; + foreach (var commit in commits) Record(commit); + return result.ToArray(); + } + + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + var observer = new LambdaAsyncObserver((commit, _) => + { + Record(commit); + return Task.FromResult(true); + }, (error, _) => Task.FromException(error)); + await ((bucket, upper) switch + { + (null, null) => engine.GetFromAsync(after, observer, timeout.Token), + (null, long end) => engine.GetFromToAsync(after, end, observer, timeout.Token), + (string id, null) => engine.GetFromAsync(id, after, observer, timeout.Token), + (string id, long end) => engine.GetFromToAsync(id, after, end, observer, timeout.Token) + }); + return result.ToArray(); + } +} +#endif diff --git a/src/NEventStore.Persistence.Sql/SqlDialects/CheckpointKeysetQuery.cs b/src/NEventStore.Persistence.Sql/SqlDialects/CheckpointKeysetQuery.cs new file mode 100644 index 0000000..e04214a --- /dev/null +++ b/src/NEventStore.Persistence.Sql/SqlDialects/CheckpointKeysetQuery.cs @@ -0,0 +1,46 @@ +namespace NEventStore.Persistence.Sql.SqlDialects +{ + /// Builds ordered checkpoint seeks for the provider's built-in SQL dialects. + internal static class CheckpointKeysetQuery + { + /// Builds a checkpoint query with the dialect's native page limit, if requested. + /// The keyset SQL, or to keep a custom dialect's virtual SQL. + internal static string? Create(ISqlDialect dialect, bool scoped, bool bounded, int pageSize) + { + var type = dialect.GetType(); + bool sqlServer = type == typeof(MsSqlDialect) || type == typeof(MsSql2005Dialect); + bool oracle = type == typeof(OracleNativeDialect); + if (!sqlServer && !oracle && + type != typeof(MySqlDialect) && type != typeof(PostgreSqlDialect) && + type != typeof(PostgreNpgsql6Dialect) && type != typeof(SqliteDialect) && + type != typeof(MicrosoftDataSqliteDialect)) + return null; + + // Reuse the column order and predicates of the existing checkpoint queries, not their offset. + string query = (scoped, bounded) switch + { + (true, true) => CommonSqlStatements.GetCommitsFromToBucketAndCheckpoint, + (true, false) => CommonSqlStatements.GetCommitsFromBucketAndCheckpoint, + (false, true) => CommonSqlStatements.GetCommitsFromToCheckpoint, + _ => CommonSqlStatements.GetCommitsFromCheckpoint + }; + query = query.Substring(0, query.LastIndexOf("LIMIT ", StringComparison.Ordinal)).TrimEnd(); + if (sqlServer) + { + query = ((MsSqlDialect)dialect).AddReadCommittedLockToFromCommits(query); + return pageSize > 0 ? query.Insert("SELECT".Length, " TOP (@Limit)") : query; + } + + if (oracle) + { + query = query.Replace('@', ':'); + // ROWNUM must limit the ordered inner rows; the outer order is explicit too. + return pageSize > 0 + ? $"SELECT * FROM ({query}) WHERE ROWNUM <= :Limit ORDER BY CheckpointNumber" + : query; + } + + return pageSize > 0 ? query + "\nLIMIT @Limit" : query; + } + } +} diff --git a/src/NEventStore.Persistence.Sql/SqlDialects/CommonDbStatement.cs b/src/NEventStore.Persistence.Sql/SqlDialects/CommonDbStatement.cs index 868d728..296646e 100644 --- a/src/NEventStore.Persistence.Sql/SqlDialects/CommonDbStatement.cs +++ b/src/NEventStore.Persistence.Sql/SqlDialects/CommonDbStatement.cs @@ -201,6 +201,15 @@ public virtual IEnumerable ExecutePagedQuery(string queryText, Next return ExecuteQuery(queryText, nextPage, pageSize); } + /// Executes checkpoint pages without sending an unused offset parameter. + internal IEnumerable ExecuteCheckpointPages(string query, NextPageDelegate nextPage) + { + if (PageSize > 0) + Parameters.Add(Dialect.Limit, Tuple.Create((object)PageSize, (DbType?)null)); + + return ExecuteQuery(query, nextPage, PageSize, useOffset: false); + } + /// protected virtual void Dispose(bool disposing) { @@ -218,13 +227,18 @@ protected virtual void Dispose(bool disposing) /// protected virtual IEnumerable ExecuteQuery(string queryText, NextPageDelegate nextPage, int pageSize) + => ExecuteQuery(queryText, nextPage, pageSize, useOffset: true); + + /// Builds a reader for either offset paging or a checkpoint seek. + private IEnumerable ExecuteQuery(string queryText, NextPageDelegate nextPage, int pageSize, bool useOffset) { - Parameters.Add(Dialect.Skip, Tuple.Create((object)0, (DbType?)null)); + if (useOffset) + Parameters.Add(Dialect.Skip, Tuple.Create((object)0, (DbType?)null)); IDbCommand command = BuildCommand(queryText); try { - return new PagedEnumerationCollection(_scope, Dialect, command, nextPage, pageSize, this); + return new PagedEnumerationCollection(_scope, Dialect, command, nextPage, pageSize, useOffset, this); } catch (Exception) { @@ -328,10 +342,20 @@ public async Task ExecuteWithQueryAsync(string queryText, IAsyncObserver - public async Task ExecutePagedQueryAsync(string queryText, NextPageDelegate nextPage, IAsyncObserver asyncObserver, CancellationToken cancellationToken) + public Task ExecutePagedQueryAsync(string queryText, NextPageDelegate nextPage, IAsyncObserver asyncObserver, CancellationToken cancellationToken) + => ExecutePagedQueryAsync(queryText, nextPage, asyncObserver, cancellationToken, useOffset: true); + + /// Streams checkpoint pages without binding an offset or limiting an unpaged read. + internal Task ExecuteCheckpointPagesAsync(string queryText, NextPageDelegate nextPage, + IAsyncObserver observer, CancellationToken cancellationToken) + => ExecutePagedQueryAsync(queryText, nextPage, observer, cancellationToken, useOffset: false); + + /// Streams pages while keeping checkpoint and offset continuation rules separate. + private async Task ExecutePagedQueryAsync(string queryText, NextPageDelegate nextPage, + IAsyncObserver asyncObserver, CancellationToken cancellationToken, bool useOffset) { int pageSize = Dialect.CanPage ? PageSize : InfinitePageSize; - if (Dialect.CanPage) + if (Dialect.CanPage && (useOffset || pageSize > 0)) { if (Logger.IsEnabled(LogLevel.Trace)) { @@ -339,7 +363,8 @@ public async Task ExecutePagedQueryAsync(string queryText, NextPageDelegate next } Parameters.Add(Dialect.Limit, Tuple.Create((object)(pageSize > 0 ? pageSize : int.MaxValue), (DbType?)null)); } - Parameters.Add(Dialect.Skip, Tuple.Create((object)0, (DbType?)null)); + if (useOffset) + Parameters.Add(Dialect.Skip, Tuple.Create((object)0, (DbType?)null)); using (var command = BuildCommand(queryText)) { // keep reading in pages until we have no more records to read. @@ -359,11 +384,19 @@ public async Task ExecutePagedQueryAsync(string queryText, NextPageDelegate next await asyncObserver.OnCompletedAsync(cancellationToken).ConfigureAwait(false); return; } - position++; recordsRead++; - if (pageSize > 0 && position >= pageSize) + if (useOffset) + { + position++; + if (pageSize > 0 && position >= pageSize) + { + command.SetParameter(Dialect.Skip, position); + nextPage(command, reader); + } + } + else if (pageSize > 0 && recordsRead == pageSize) { - command.SetParameter(Dialect.Skip, position); + // Rebind once per full page, after the observer accepts its last row. nextPage(command, reader); } } diff --git a/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs b/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs index a67bbcc..b6ba0f0 100644 --- a/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs +++ b/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs @@ -92,7 +92,7 @@ public override string GetStreamsRequiringSnapshots /// Applies the optional READCOMMITTEDLOCK hint to a public commit-read query. /// A SQL Server query that returns commits to the caller. /// The query with the configured read semantics. - private string AddReadCommittedLockToFromCommits(string query) + internal string AddReadCommittedLockToFromCommits(string query) { // Custom consumers can use any commit-read API. Leave writes and snapshot queries alone. return _useReadCommittedLockForCommitReads diff --git a/src/NEventStore.Persistence.Sql/SqlDialects/PagedEnumerationCollection.cs b/src/NEventStore.Persistence.Sql/SqlDialects/PagedEnumerationCollection.cs index cdd4991..bdc98e9 100644 --- a/src/NEventStore.Persistence.Sql/SqlDialects/PagedEnumerationCollection.cs +++ b/src/NEventStore.Persistence.Sql/SqlDialects/PagedEnumerationCollection.cs @@ -17,6 +17,7 @@ public class PagedEnumerationCollection : IEnumerable, IEnumerator< private readonly IEnumerable _disposable = []; private readonly NextPageDelegate _nextPage; private readonly int _pageSize; + private readonly bool _useOffset; private readonly TransactionScope? _scope; private IDataRecord? _current; @@ -34,12 +35,20 @@ public PagedEnumerationCollection( NextPageDelegate nextPage, int pageSize, params IDisposable[] disposable) + : this(scope, dialect, command, nextPage, pageSize, true, disposable) + { + } + + /// Initializes a paged reader with optional offset tracking. + internal PagedEnumerationCollection(TransactionScope? scope, ISqlDialect dialect, IDbCommand command, + NextPageDelegate nextPage, int pageSize, bool useOffset, params IDisposable[] disposable) { _scope = scope; _dialect = dialect; _command = command; _nextPage = nextPage; _pageSize = pageSize; + _useOffset = useOffset; _disposable = disposable ?? _disposable; } @@ -149,7 +158,8 @@ private bool MoveToNextRecord() { if (_pageSize > 0 && _position >= _pageSize) { - _command.SetParameter(_dialect.Skip, _position); + if (_useOffset) + _command.SetParameter(_dialect.Skip, _position); if (_current is null) { throw new InvalidOperationException("Enumeration not started."); @@ -179,6 +189,9 @@ private bool MoveToNextRecord() Logger.LogTrace(Messages.EnumeratedRowCount, _position); } _reader.Dispose(); + // A seek only needs the current page count, even for streams larger than Int32.MaxValue. + if (!_useOffset) + _position = 0; _reader = OpenNextPage(); if (_reader.Read()) diff --git a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs index bb19b9c..771ba49 100644 --- a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs +++ b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs @@ -2,6 +2,7 @@ using System.Data; using System.Data.Common; using NEventStore.Serialization; +using NEventStore.Persistence.Sql.SqlDialects; namespace NEventStore.Persistence.Sql { @@ -19,9 +20,8 @@ public Task GetFromAsync(long checkpointToken, IAsyncObserver asyncObse return ExecuteQueryAsync((query, asyncObserver, cancellationToken) => { - string statement = _dialect.GetCommitsFromCheckpoint; query.AddParameter(_dialect.CheckpointNumber, checkpointToken); - return query.ExecutePagedQueryAsync(statement, (_, _) => { }, asyncObserver, cancellationToken); + return ReadCheckpointPagesAsync(query, false, false, asyncObserver, cancellationToken); }, adapter, cancellationToken); } @@ -38,10 +38,9 @@ public Task GetFromToAsync(long fromCheckpointToken, long toCheckpointToken, IAs return ExecuteQueryAsync((query, asyncObserver, cancellationToken) => { - string statement = _dialect.GetCommitsFromToCheckpoint; query.AddParameter(_dialect.FromCheckpointNumber, fromCheckpointToken); query.AddParameter(_dialect.ToCheckpointNumber, toCheckpointToken); - return query.ExecutePagedQueryAsync(statement, (_, _) => { }, asyncObserver, cancellationToken); + return ReadCheckpointPagesAsync(query, false, true, asyncObserver, cancellationToken); }, adapter, cancellationToken); } @@ -58,10 +57,9 @@ public Task GetFromAsync(string bucketId, long checkpointToken, IAsyncObserver { - string statement = _dialect.GetCommitsFromBucketAndCheckpoint; query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString); query.AddParameter(_dialect.CheckpointNumber, checkpointToken); - return query.ExecutePagedQueryAsync(statement, (_, _) => { }, asyncObserver, cancellationToken); + return ReadCheckpointPagesAsync(query, true, false, asyncObserver, cancellationToken); }, adapter, cancellationToken); } @@ -78,15 +76,25 @@ public Task GetFromToAsync(string bucketId, long fromCheckpointToken, long toChe return ExecuteQueryAsync((query, asyncObserver, cancellationToken) => { - string statement = _dialect.GetCommitsFromToBucketAndCheckpoint; query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString); query.AddParameter(_dialect.FromCheckpointNumber, fromCheckpointToken); query.AddParameter(_dialect.ToCheckpointNumber, toCheckpointToken); - return query.ExecutePagedQueryAsync(statement, (_, _) => { }, asyncObserver, cancellationToken); + return ReadCheckpointPagesAsync(query, true, true, asyncObserver, cancellationToken); }, adapter, cancellationToken); } + /// Uses the same checkpoint seek rule as the synchronous reader. + private Task ReadCheckpointPagesAsync(IDbStatement query, bool scoped, bool bounded, + IAsyncObserver observer, CancellationToken cancellationToken) + { + if (query is CommonDbStatement builtIn && + CheckpointKeysetQuery.Create(_dialect, scoped, bounded, query.PageSize) is { } keyset) + return builtIn.ExecuteCheckpointPagesAsync(keyset, AdvanceCheckpoint(bounded), observer, cancellationToken); + + return query.ExecutePagedQueryAsync(GetOffsetCheckpointQuery(scoped, bounded), (_, _) => { }, observer, cancellationToken); + } + /// public Task PurgeAsync(CancellationToken cancellationToken) { diff --git a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.cs b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.cs index 60d3107..6b348d1 100644 --- a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.cs +++ b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.cs @@ -4,6 +4,7 @@ using Microsoft.Extensions.Logging; using NEventStore.Logging; using NEventStore.Serialization; +using NEventStore.Persistence.Sql.SqlDialects; namespace NEventStore.Persistence.Sql { @@ -316,10 +317,9 @@ public IEnumerable GetFrom(string bucketId, Int64 checkpointToken) return ExecuteQuery(query => { - string statement = _dialect.GetCommitsFromBucketAndCheckpoint; query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString); query.AddParameter(_dialect.CheckpointNumber, checkpointToken); - return query.ExecutePagedQuery(statement, (_, _) => { }) + return ReadCheckpointPages(query, scoped: true, bounded: false) .Select(x => x.GetCommit(_serializer, _eventSerializer, _dialect)); }); } @@ -334,11 +334,10 @@ public IEnumerable GetFromTo(String bucketId, Int64 fromCheckpointToken return ExecuteQuery(query => { - string statement = _dialect.GetCommitsFromToBucketAndCheckpoint; query.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString); query.AddParameter(_dialect.FromCheckpointNumber, fromCheckpointToken); query.AddParameter(_dialect.ToCheckpointNumber, toCheckpointToken); - return query.ExecutePagedQuery(statement, (_, _) => { }) + return ReadCheckpointPages(query, scoped: true, bounded: true) .Select(x => x.GetCommit(_serializer, _eventSerializer, _dialect)); }); } @@ -353,9 +352,8 @@ public IEnumerable GetFrom(Int64 checkpointToken) return ExecuteQuery(query => { - string statement = _dialect.GetCommitsFromCheckpoint; query.AddParameter(_dialect.CheckpointNumber, checkpointToken); - return query.ExecutePagedQuery(statement, (_, _) => { }) + return ReadCheckpointPages(query, scoped: false, bounded: false) .Select(x => x.GetCommit(_serializer, _eventSerializer, _dialect)); }); } @@ -370,14 +368,40 @@ public IEnumerable GetFromTo(Int64 fromCheckpointToken, Int64 toCheckpo return ExecuteQuery(query => { - string statement = _dialect.GetCommitsFromToCheckpoint; query.AddParameter(_dialect.FromCheckpointNumber, fromCheckpointToken); query.AddParameter(_dialect.ToCheckpointNumber, toCheckpointToken); - return query.ExecutePagedQuery(statement, (_, _) => { }) + return ReadCheckpointPages(query, scoped: false, bounded: true) .Select(x => x.GetCommit(_serializer, _eventSerializer, _dialect)); }); } + /// Reads checkpoint pages without shifting the next page when an earlier row disappears. + /// Custom dialects and statements keep their existing SQL and paging behavior. + private IEnumerable ReadCheckpointPages(IDbStatement query, bool scoped, bool bounded) + { + if (query is CommonDbStatement builtIn && + CheckpointKeysetQuery.Create(_dialect, scoped, bounded, query.PageSize) is { } keyset) + return builtIn.ExecuteCheckpointPages(keyset, AdvanceCheckpoint(bounded)); + + return query.ExecutePagedQuery(GetOffsetCheckpointQuery(scoped, bounded), (_, _) => { }); + } + + /// Advances only the exclusive lower bound; a bounded query keeps its original ceiling. + private NextPageDelegate AdvanceCheckpoint(bool bounded) + { + string parameter = bounded ? _dialect.FromCheckpointNumber : _dialect.CheckpointNumber; + return (command, row) => command.SetParameter(parameter, row.CheckpointNumber()); + } + + /// Resolves the existing virtual SQL getter for a custom dialect or statement. + private string GetOffsetCheckpointQuery(bool scoped, bool bounded) => (scoped, bounded) switch + { + (true, true) => _dialect.GetCommitsFromToBucketAndCheckpoint, + (true, false) => _dialect.GetCommitsFromBucketAndCheckpoint, + (false, true) => _dialect.GetCommitsFromToCheckpoint, + _ => _dialect.GetCommitsFromCheckpoint + }; + /// public bool IsDisposed { diff --git a/src/NEventStore.Persistence.Sqlite.Tests/CheckpointPagingDeletionTests.cs b/src/NEventStore.Persistence.Sqlite.Tests/CheckpointPagingDeletionTests.cs new file mode 100644 index 0000000..b7d59ff --- /dev/null +++ b/src/NEventStore.Persistence.Sqlite.Tests/CheckpointPagingDeletionTests.cs @@ -0,0 +1,71 @@ +#if NUNIT +using FluentAssertions; +using Microsoft.Data.Sqlite; +using NEventStore.Persistence.AcceptanceTests; +using NEventStore.Persistence.Sql; +using NEventStore.Persistence.Sql.SqlDialects; +using NEventStore.Serialization.Binary; +using NUnit.Framework; + +namespace NEventStore.Persistence.Sqlite.Tests; + +[TestFixture] +[NonParallelizable] +public sealed class CheckpointPagingDeletionTests +{ + private const string Bucket = "paging"; + + [TestCase(false, false)] + [TestCase(false, true)] + [TestCase(true, false)] + [TestCase(true, true)] + public async Task Deleting_the_in_flight_first_page_does_not_skip_the_next_commit(bool useAsync, bool scoped) + { + var directory = Path.Combine(Path.GetTempPath(), "neventstore-paging-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + var settings = new SqliteConnectionStringBuilder + { + DataSource = Path.Combine(directory, "store.db"), Pooling = false + }; + using var writer = new SqliteConnection(settings.ConnectionString); + writer.Open(); + using var command = writer.CreateCommand(); + command.CommandText = "PRAGMA journal_mode = WAL"; + command.ExecuteScalar().Should().Be("wal"); + +#if NET8_0_OR_GREATER + AppContext.SetSwitch("System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization", true); +#endif + var serializer = new BinarySerializer(); + using var engine = new SqlPersistenceFactory(new NetStandardConnectionFactory(SqliteFactory.Instance, settings.ConnectionString), + serializer, new DefaultEventSerializer(serializer), new MicrosoftDataSqliteDialect(), pageSize: 1).Build(); + engine.Initialize(); + var first = engine.Commit("first".BuildAttempt(bucketId: Bucket))!.CheckpointToken; + var second = engine.Commit("second".BuildAttempt(bucketId: Bucket))!.CheckpointToken; + var third = engine.Commit("third".BuildAttempt(bucketId: Bucket))!.CheckpointToken; + bool deleted = false; + + var result = await CheckpointPagingTests.ReadAsync(engine, 0, upper: scoped ? third : null, + bucket: scoped ? Bucket : null, useAsync: useAsync, onRead: commit => + { + if (deleted) return; + commit.CheckpointToken.Should().Be(first); + // WAL lets a separate connection remove the consumed row before the next page. + command.CommandText = "DELETE FROM Commits WHERE CheckpointNumber = @checkpoint"; + command.Parameters.AddWithValue("@checkpoint", commit.CheckpointToken); + command.ExecuteNonQuery().Should().Be(1); + deleted = true; + }); + + deleted.Should().BeTrue(); + result.Should().Equal(first, second, third); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } +} +#endif diff --git a/src/NEventStore.Persistence.Sqlite.Tests/NEventStore.Persistence.Sqlite.Core.Tests.csproj b/src/NEventStore.Persistence.Sqlite.Tests/NEventStore.Persistence.Sqlite.Core.Tests.csproj index 93d0d37..7ea3791 100644 --- a/src/NEventStore.Persistence.Sqlite.Tests/NEventStore.Persistence.Sqlite.Core.Tests.csproj +++ b/src/NEventStore.Persistence.Sqlite.Tests/NEventStore.Persistence.Sqlite.Core.Tests.csproj @@ -51,6 +51,7 @@ + From 31abd1e45502707a7260ace846189e0b94612629 Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 12:15:24 +0100 Subject: [PATCH 7/9] Verify persisted Oracle checkpoints and derived dialect compatibility Read expected checkpoints through the existing stream API rather than relying on Oracle's write result. Exercise a derived SQLite dialect with an overridden checkpoint query on both reader paths. Co-authored-by: Codex --- .../PersistenceTests.CheckpointPaging.cs | 14 +++++- .../CheckpointPagingDeletionTests.cs | 46 ++++++++++++++++--- 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/src/NEventStore.Persistence.Sql.Tests/PersistenceTests.CheckpointPaging.cs b/src/NEventStore.Persistence.Sql.Tests/PersistenceTests.CheckpointPaging.cs index 9e002a9..a86b952 100644 --- a/src/NEventStore.Persistence.Sql.Tests/PersistenceTests.CheckpointPaging.cs +++ b/src/NEventStore.Persistence.Sql.Tests/PersistenceTests.CheckpointPaging.cs @@ -20,7 +20,14 @@ public async Task Checkpoint_reads_preserve_order_scope_gaps_and_range_bounds(in using var fixture = new PersistenceEngineFixture(); fixture.Initialize(pageSize); var engine = fixture.Persistence!; - ICommit Write(string name, string bucket) => engine.Commit(name.BuildAttempt(bucketId: bucket))!; + using var referenceReader = fixture.CreateCheckpointReferenceReader(); + ICommit Write(string name, string bucket) + { + engine.Commit(name.BuildAttempt(bucketId: bucket)).Should().NotBeNull(); + // Oracle's existing write result does not report the assigned checkpoint. + // Use a separate, paged stream reader so the expected value is independent of the tested query. + return referenceReader.GetFrom(bucket, name, 1, 1).Single(); + } var start = Write("start", SelectedBucket); var b1 = Write("b1", OtherBucket); @@ -86,4 +93,9 @@ void Record(ICommit commit) return result.ToArray(); } } +public partial class PersistenceEngineFixture +{ + // Use the initialized fixture's store without owning its schema or changing the tested page size. + internal IPersistStreams CreateCheckpointReferenceReader() => _createPersistence(2); +} #endif diff --git a/src/NEventStore.Persistence.Sqlite.Tests/CheckpointPagingDeletionTests.cs b/src/NEventStore.Persistence.Sqlite.Tests/CheckpointPagingDeletionTests.cs index b7d59ff..f087b0b 100644 --- a/src/NEventStore.Persistence.Sqlite.Tests/CheckpointPagingDeletionTests.cs +++ b/src/NEventStore.Persistence.Sqlite.Tests/CheckpointPagingDeletionTests.cs @@ -35,12 +35,7 @@ public async Task Deleting_the_in_flight_first_page_does_not_skip_the_next_commi command.CommandText = "PRAGMA journal_mode = WAL"; command.ExecuteScalar().Should().Be("wal"); -#if NET8_0_OR_GREATER - AppContext.SetSwitch("System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization", true); -#endif - var serializer = new BinarySerializer(); - using var engine = new SqlPersistenceFactory(new NetStandardConnectionFactory(SqliteFactory.Instance, settings.ConnectionString), - serializer, new DefaultEventSerializer(serializer), new MicrosoftDataSqliteDialect(), pageSize: 1).Build(); + using var engine = OpenEngine(settings, new MicrosoftDataSqliteDialect()); engine.Initialize(); var first = engine.Commit("first".BuildAttempt(bucketId: Bucket))!.CheckpointToken; var second = engine.Commit("second".BuildAttempt(bucketId: Bucket))!.CheckpointToken; @@ -67,5 +62,44 @@ public async Task Deleting_the_in_flight_first_page_does_not_skip_the_next_commi Directory.Delete(directory, recursive: true); } } + + [TestCase(false)] + [TestCase(true)] + public async Task A_derived_dialect_keeps_its_custom_checkpoint_query(bool useAsync) + { + var settings = new SqliteConnectionStringBuilder + { + DataSource = "nes-paging-" + Guid.NewGuid().ToString("N"), + Mode = SqliteOpenMode.Memory, + Cache = SqliteCacheMode.Shared, + Pooling = false + }; + using var keepDatabaseAlive = new SqliteConnection(settings.ConnectionString); + keepDatabaseAlive.Open(); + using var engine = OpenEngine(settings, new CustomSqliteDialect()); + engine.Initialize(); + var first = engine.Commit("first".BuildAttempt(bucketId: Bucket))!.CheckpointToken; + engine.Commit("not returned by this dialect".BuildAttempt(bucketId: "hidden")); + var last = engine.Commit("last".BuildAttempt(bucketId: Bucket))!.CheckpointToken; + + // With one row per page, the custom statement must still filter and continue correctly. + (await CheckpointPagingTests.ReadAsync(engine, 0, useAsync: useAsync)).Should().Equal(first, last); + } + + private static IPersistStreams OpenEngine(SqliteConnectionStringBuilder settings, MicrosoftDataSqliteDialect dialect) + { +#if NET8_0_OR_GREATER + AppContext.SetSwitch("System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization", true); +#endif + var serializer = new BinarySerializer(); + return new SqlPersistenceFactory(new NetStandardConnectionFactory(SqliteFactory.Instance, settings.ConnectionString), + serializer, new DefaultEventSerializer(serializer), dialect, pageSize: 1).Build(); + } + + private sealed class CustomSqliteDialect : MicrosoftDataSqliteDialect + { + public override string GetCommitsFromCheckpoint => base.GetCommitsFromCheckpoint.Replace( + "CheckpointNumber > @CheckpointNumber", "CheckpointNumber > @CheckpointNumber AND BucketId <> 'hidden'"); + } } #endif From 1dc3c18de55ddc195dfae1e5b6fb8437f05e0f83 Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 12:31:05 +0100 Subject: [PATCH 8/9] Default derived SQL dialects to keyset checkpoint paging Add a protected virtual hook to customize the ordered seek or keep the legacy query for a given shape. Document that existing checkpoint SQL overrides must opt out or migrate. Co-authored-by: Codex --- Changelog.md | 6 ++- docs/Checkpoint-Seek-Paging.md | 26 +++++++++- .../SqlDialects/CheckpointKeysetQuery.cs | 18 +++---- .../SqlDialects/CommonSqlDialect.cs | 21 ++++++++ .../SqlPersistenceEngine.Async.cs | 5 +- .../SqlPersistenceEngine.cs | 7 +-- .../CheckpointPagingDeletionTests.cs | 48 ++++++++++++++----- 7 files changed, 99 insertions(+), 32 deletions(-) diff --git a/Changelog.md b/Changelog.md index 2ee31b4..1593bdc 100644 --- a/Changelog.md +++ b/Changelog.md @@ -2,10 +2,14 @@ ## Unreleased -- Use ordered keyset paging for checkpoint reads on SQL Server, PostgreSQL, MySQL, Oracle, and SQLite. A deletion before the next page no longer shifts it, and zero page size reads without a page limit. Keep the existing behavior for custom dialects and non-checkpoint reads. No schema change. [#63](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/63) +- Use ordered keyset paging for checkpoint reads on SQL Server, PostgreSQL, MySQL, Oracle, and SQLite. A deletion before the next page no longer shifts it, and zero page size reads without a page limit. Keep the existing behavior for non-checkpoint reads. No schema change. [#63](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/63) - Add an opt-in SQL Server and Azure SQL mitigation for commit readers under `READ_COMMITTED_SNAPSHOT`. Choose `WithDialect(new MsSqlDialect(useReadCommittedLockForCommitReads: true))` to request locking for open-ended and bounded checkpoint reads, date-based reads, and stream revision reads. These reads can wait for an uncommitted insert; this does not guarantee checkpoint publication order. Default behavior, write and snapshot queries, and the schema are unchanged. [#31](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/31) +### Breaking Changes + +- Subclasses of the built-in SQL dialects now inherit checkpoint keyset paging when using the built-in statement execution path. Overrides of the old `GetCommitsFrom…Checkpoint` SQL properties are not used by that path. To preserve custom checkpoint SQL, override `GetCheckpointKeysetQuery(bool scoped, bool bounded, int pageSize)` and return `null` for the relevant query shapes, or migrate those queries to ordered keyset SQL. Other `ISqlDialect` implementations and separate statement wrappers keep their existing behavior. + ## 10.2.0 - Added explicit support for net8.0,net9.0,net10.0 diff --git a/docs/Checkpoint-Seek-Paging.md b/docs/Checkpoint-Seek-Paging.md index e4b6ae6..2e728a5 100644 --- a/docs/Checkpoint-Seek-Paging.md +++ b/docs/Checkpoint-Seek-Paging.md @@ -5,12 +5,34 @@ next page with `CheckpointNumber > last returned checkpoint`, ordered by checkpoint. Bucket filters and inclusive upper bounds are carried across pages. `PageSize = 0` sends one ordered query with no page limit. -This changes only checkpoint reads. Older custom dialects and statement -implementations keep their existing offset SQL and behavior. Seek paging +This changes only checkpoint reads. Seek paging does not make a late lower checkpoint visible before a higher one, does not provide snapshot isolation across pages, and does not restore already deleted commits. Ordered publication is tracked in [#72](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/72). +## Upgrading a derived dialect + +**Breaking change:** subclasses of the built-in SQL Server, PostgreSQL, MySQL, +Oracle, and SQLite dialects inherit keyset paging when they use the built-in +statement path. The keyset path does not call the older virtual checkpoint SQL +properties. If those overrides add a filter, join, or hint, either port that +change to the new hook or keep offset paging explicitly: + +```csharp +protected override string? GetCheckpointKeysetQuery(bool scoped, bool bounded, int pageSize) + => null; +``` + +Return `null` only for the shapes that need the old SQL, or call the base hook and +adapt its keyset query. Custom SQL must return the same commit columns in the +same order, seek after the active lower checkpoint parameter, retain the bucket +filter and upper bound when requested, and order by checkpoint. Don't bind a +limit for page size zero or use the offset parameter. + +Independent `ISqlDialect` implementations, subclasses that disable paging, and +custom statement wrappers that don't use the built-in executor keep their +existing paging behavior. + ## Large catch-up comparison 1. Start the database services using [the Docker instructions](../docker/Readme.md) diff --git a/src/NEventStore.Persistence.Sql/SqlDialects/CheckpointKeysetQuery.cs b/src/NEventStore.Persistence.Sql/SqlDialects/CheckpointKeysetQuery.cs index e04214a..c018496 100644 --- a/src/NEventStore.Persistence.Sql/SqlDialects/CheckpointKeysetQuery.cs +++ b/src/NEventStore.Persistence.Sql/SqlDialects/CheckpointKeysetQuery.cs @@ -5,15 +5,11 @@ internal static class CheckpointKeysetQuery { /// Builds a checkpoint query with the dialect's native page limit, if requested. /// The keyset SQL, or to keep a custom dialect's virtual SQL. - internal static string? Create(ISqlDialect dialect, bool scoped, bool bounded, int pageSize) + internal static string? CreateDefault(CommonSqlDialect dialect, bool scoped, bool bounded, int pageSize) { - var type = dialect.GetType(); - bool sqlServer = type == typeof(MsSqlDialect) || type == typeof(MsSql2005Dialect); - bool oracle = type == typeof(OracleNativeDialect); - if (!sqlServer && !oracle && - type != typeof(MySqlDialect) && type != typeof(PostgreSqlDialect) && - type != typeof(PostgreNpgsql6Dialect) && type != typeof(SqliteDialect) && - type != typeof(MicrosoftDataSqliteDialect)) + // Inherit the provider's SQL family in subclasses; the virtual hook can still opt out. + if (dialect is not (MsSqlDialect or OracleNativeDialect or MySqlDialect + or PostgreSqlDialect or PostgreNpgsql6Dialect or SqliteDialect)) return null; // Reuse the column order and predicates of the existing checkpoint queries, not their offset. @@ -25,13 +21,13 @@ internal static class CheckpointKeysetQuery _ => CommonSqlStatements.GetCommitsFromCheckpoint }; query = query.Substring(0, query.LastIndexOf("LIMIT ", StringComparison.Ordinal)).TrimEnd(); - if (sqlServer) + if (dialect is MsSqlDialect sqlServer) { - query = ((MsSqlDialect)dialect).AddReadCommittedLockToFromCommits(query); + query = sqlServer.AddReadCommittedLockToFromCommits(query); return pageSize > 0 ? query.Insert("SELECT".Length, " TOP (@Limit)") : query; } - if (oracle) + if (dialect is OracleNativeDialect) { query = query.Replace('@', ':'); // ROWNUM must limit the ordered inner rows; the outer order is explicit too. diff --git a/src/NEventStore.Persistence.Sql/SqlDialects/CommonSqlDialect.cs b/src/NEventStore.Persistence.Sql/SqlDialects/CommonSqlDialect.cs index e132526..bf7a39c 100644 --- a/src/NEventStore.Persistence.Sql/SqlDialects/CommonSqlDialect.cs +++ b/src/NEventStore.Persistence.Sql/SqlDialects/CommonSqlDialect.cs @@ -168,6 +168,27 @@ public virtual string ToCheckpointNumber { get { return "@ToCheckpointNumber"; } } + /// Returns the SQL used to seek through a checkpoint result. + /// Whether the query includes the filter. + /// Whether the query includes the inclusive bound. + /// The page size, or zero to read without a row limit. + /// The keyset query, or to use the existing offset query for this shape. + /// + /// Built-in dialects and their subclasses use keyset paging by default. Override this method to + /// customize their keyset SQL, or return to keep using legacy checkpoint + /// query overrides. Custom SQL must return the standard commit columns in their existing order, + /// seek strictly after (or when + /// bounded), and order by checkpoint. Preserve the requested scope and upper bound, use + /// only when is positive, and do not use + /// . + /// + protected virtual string? GetCheckpointKeysetQuery(bool scoped, bool bounded, int pageSize) + => CheckpointKeysetQuery.CreateDefault(this, scoped, bounded, pageSize); + + /// Dispatches to the dialect's checkpoint hook only when it supports paging. + internal string? ResolveCheckpointKeysetQuery(bool scoped, bool bounded, int pageSize) + => CanPage ? GetCheckpointKeysetQuery(scoped, bounded, pageSize) : null; + /// public virtual string GetCommitsFromCheckpoint { diff --git a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs index 771ba49..06425d5 100644 --- a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs +++ b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs @@ -88,8 +88,9 @@ public Task GetFromToAsync(string bucketId, long fromCheckpointToken, long toChe private Task ReadCheckpointPagesAsync(IDbStatement query, bool scoped, bool bounded, IAsyncObserver observer, CancellationToken cancellationToken) { - if (query is CommonDbStatement builtIn && - CheckpointKeysetQuery.Create(_dialect, scoped, bounded, query.PageSize) is { } keyset) + // A custom statement wrapper must not receive keyset SQL through its offset executor. + if (query is CommonDbStatement builtIn && _dialect is CommonSqlDialect dialect && + dialect.ResolveCheckpointKeysetQuery(scoped, bounded, query.PageSize) is { } keyset) return builtIn.ExecuteCheckpointPagesAsync(keyset, AdvanceCheckpoint(bounded), observer, cancellationToken); return query.ExecutePagedQueryAsync(GetOffsetCheckpointQuery(scoped, bounded), (_, _) => { }, observer, cancellationToken); diff --git a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.cs b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.cs index 6b348d1..689bb76 100644 --- a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.cs +++ b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.cs @@ -376,11 +376,12 @@ public IEnumerable GetFromTo(Int64 fromCheckpointToken, Int64 toCheckpo } /// Reads checkpoint pages without shifting the next page when an earlier row disappears. - /// Custom dialects and statements keep their existing SQL and paging behavior. + /// Dialect opt-outs and separate statement wrappers keep their existing offset path. private IEnumerable ReadCheckpointPages(IDbStatement query, bool scoped, bool bounded) { - if (query is CommonDbStatement builtIn && - CheckpointKeysetQuery.Create(_dialect, scoped, bounded, query.PageSize) is { } keyset) + // A custom statement wrapper must not receive keyset SQL through its offset executor. + if (query is CommonDbStatement builtIn && _dialect is CommonSqlDialect dialect && + dialect.ResolveCheckpointKeysetQuery(scoped, bounded, query.PageSize) is { } keyset) return builtIn.ExecuteCheckpointPages(keyset, AdvanceCheckpoint(bounded)); return query.ExecutePagedQuery(GetOffsetCheckpointQuery(scoped, bounded), (_, _) => { }); diff --git a/src/NEventStore.Persistence.Sqlite.Tests/CheckpointPagingDeletionTests.cs b/src/NEventStore.Persistence.Sqlite.Tests/CheckpointPagingDeletionTests.cs index f087b0b..131214b 100644 --- a/src/NEventStore.Persistence.Sqlite.Tests/CheckpointPagingDeletionTests.cs +++ b/src/NEventStore.Persistence.Sqlite.Tests/CheckpointPagingDeletionTests.cs @@ -15,11 +15,13 @@ public sealed class CheckpointPagingDeletionTests { private const string Bucket = "paging"; - [TestCase(false, false)] - [TestCase(false, true)] - [TestCase(true, false)] - [TestCase(true, true)] - public async Task Deleting_the_in_flight_first_page_does_not_skip_the_next_commit(bool useAsync, bool scoped) + [TestCase(false, false, false)] + [TestCase(false, true, false)] + [TestCase(true, false, false)] + [TestCase(true, true, false)] + [TestCase(false, false, true)] + [TestCase(true, true, true)] + public async Task Deleting_the_in_flight_first_page_does_not_skip_the_next_commit(bool useAsync, bool scoped, bool derived) { var directory = Path.Combine(Path.GetTempPath(), "neventstore-paging-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(directory); @@ -35,7 +37,7 @@ public async Task Deleting_the_in_flight_first_page_does_not_skip_the_next_commi command.CommandText = "PRAGMA journal_mode = WAL"; command.ExecuteScalar().Should().Be("wal"); - using var engine = OpenEngine(settings, new MicrosoftDataSqliteDialect()); + using var engine = OpenEngine(settings, derived ? new InheritedSqliteDialect() : new MicrosoftDataSqliteDialect()); engine.Initialize(); var first = engine.Commit("first".BuildAttempt(bucketId: Bucket))!.CheckpointToken; var second = engine.Commit("second".BuildAttempt(bucketId: Bucket))!.CheckpointToken; @@ -63,9 +65,11 @@ public async Task Deleting_the_in_flight_first_page_does_not_skip_the_next_commi } } - [TestCase(false)] - [TestCase(true)] - public async Task A_derived_dialect_keeps_its_custom_checkpoint_query(bool useAsync) + [TestCase(false, false)] + [TestCase(true, false)] + [TestCase(false, true)] + [TestCase(true, true)] + public async Task A_derived_dialect_can_customize_keyset_or_keep_the_legacy_override(bool useAsync, bool customKeyset) { var settings = new SqliteConnectionStringBuilder { @@ -76,14 +80,17 @@ public async Task A_derived_dialect_keeps_its_custom_checkpoint_query(bool useAs }; using var keepDatabaseAlive = new SqliteConnection(settings.ConnectionString); keepDatabaseAlive.Open(); - using var engine = OpenEngine(settings, new CustomSqliteDialect()); + using var engine = OpenEngine(settings, customKeyset ? new CustomKeysetDialect() : new LegacyCheckpointDialect()); engine.Initialize(); var first = engine.Commit("first".BuildAttempt(bucketId: Bucket))!.CheckpointToken; - engine.Commit("not returned by this dialect".BuildAttempt(bucketId: "hidden")); + var hidden = engine.Commit("hidden".BuildAttempt(bucketId: "hidden"))!.CheckpointToken; var last = engine.Commit("last".BuildAttempt(bucketId: Bucket))!.CheckpointToken; - // With one row per page, the custom statement must still filter and continue correctly. + // Both custom statements must still filter and continue across one-row pages. (await CheckpointPagingTests.ReadAsync(engine, 0, useAsync: useAsync)).Should().Equal(first, last); + // The keyset subclass opts out of only the bucket query and honors its legacy override there. + (await CheckpointPagingTests.ReadAsync(engine, 0, bucket: "hidden", useAsync: useAsync)) + .Should().Equal(customKeyset ? Array.Empty() : new[] { hidden }); } private static IPersistStreams OpenEngine(SqliteConnectionStringBuilder settings, MicrosoftDataSqliteDialect dialect) @@ -96,10 +103,25 @@ private static IPersistStreams OpenEngine(SqliteConnectionStringBuilder settings serializer, new DefaultEventSerializer(serializer), dialect, pageSize: 1).Build(); } - private sealed class CustomSqliteDialect : MicrosoftDataSqliteDialect + private sealed class InheritedSqliteDialect : MicrosoftDataSqliteDialect; + + private sealed class LegacyCheckpointDialect : MicrosoftDataSqliteDialect { + protected override string? GetCheckpointKeysetQuery(bool scoped, bool bounded, int pageSize) => null; + public override string GetCommitsFromCheckpoint => base.GetCommitsFromCheckpoint.Replace( "CheckpointNumber > @CheckpointNumber", "CheckpointNumber > @CheckpointNumber AND BucketId <> 'hidden'"); } + + private sealed class CustomKeysetDialect : MicrosoftDataSqliteDialect + { + protected override string? GetCheckpointKeysetQuery(bool scoped, bool bounded, int pageSize) => scoped + ? null + : base.GetCheckpointKeysetQuery(scoped, bounded, pageSize)?.Replace( + "CheckpointNumber > @CheckpointNumber", "CheckpointNumber > @CheckpointNumber AND BucketId <> 'hidden'"); + + public override string GetCommitsFromBucketAndCheckpoint => base.GetCommitsFromBucketAndCheckpoint.Replace( + "BucketId = @BucketId", "BucketId = @BucketId AND BucketId <> 'hidden'"); + } } #endif From c7acb723cfc4b1c9d42ddb0b350ec005e55f3236 Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 12:47:02 +0100 Subject: [PATCH 9/9] Expand the derived-dialect keyset migration guide Show inherited paging, complete and selective offset fallback, and adapted or fully custom keyset SQL. Call out the impact on existing checkpoint overrides under Breaking Changes. Co-authored-by: Codex --- Changelog.md | 4 +- docs/Checkpoint-Seek-Paging.md | 167 ++++++++++++++++++++++++++++++--- 2 files changed, 157 insertions(+), 14 deletions(-) diff --git a/Changelog.md b/Changelog.md index 1593bdc..fce59a4 100644 --- a/Changelog.md +++ b/Changelog.md @@ -8,7 +8,9 @@ ### Breaking Changes -- Subclasses of the built-in SQL dialects now inherit checkpoint keyset paging when using the built-in statement execution path. Overrides of the old `GetCommitsFrom…Checkpoint` SQL properties are not used by that path. To preserve custom checkpoint SQL, override `GetCheckpointKeysetQuery(bool scoped, bool bounded, int pageSize)` and return `null` for the relevant query shapes, or migrate those queries to ordered keyset SQL. Other `ISqlDialect` implementations and separate statement wrappers keep their existing behavior. +- **Derived SQL dialects and checkpoint overrides (#63).** Keyset paging is now the default for subclasses of built-in SQL dialects that use the built-in statement executor. It **does not call** the old virtual checkpoint SQL properties, so filters, joins, or hints in those overrides will no longer be applied even though the subclass still compiles. + - Move the customization to `GetCheckpointKeysetQuery(bool scoped, bool bounded, int pageSize)` to use keyset paging, or return `null` for the affected shapes to keep the previous SQL and offset paging. + - Independent `ISqlDialect` implementations, dialects that disable paging, and separate custom statement wrappers retain their existing behavior. See the [migration guide and examples](docs/Checkpoint-Seek-Paging.md#upgrading-a-derived-dialect). ## 10.2.0 diff --git a/docs/Checkpoint-Seek-Paging.md b/docs/Checkpoint-Seek-Paging.md index 2e728a5..e986f21 100644 --- a/docs/Checkpoint-Seek-Paging.md +++ b/docs/Checkpoint-Seek-Paging.md @@ -14,24 +14,165 @@ commits. Ordered publication is tracked in [#72](https://github.com/NEventStore/ **Breaking change:** subclasses of the built-in SQL Server, PostgreSQL, MySQL, Oracle, and SQLite dialects inherit keyset paging when they use the built-in -statement path. The keyset path does not call the older virtual checkpoint SQL -properties. If those overrides add a filter, join, or hint, either port that -change to the new hook or keep offset paging explicitly: +statement executor. Keyset paging bypasses the four old virtual checkpoint SQL +properties. If one of your overrides adds a filter, join, or hint, migrate it to +the new hook or return `null` to keep that query on offset paging. Otherwise its +customization will no longer be applied, even though your subclass still compiles. + +### 1. Inherit keyset paging without changing your queries + +If your subclass only customizes unrelated behavior, leave the checkpoint hook +alone. The new keyset paging is inherited. This example keeps the SQL Server +read-locking option explicit: + +```csharp +using NEventStore.Persistence.Sql.SqlDialects; + +public sealed class ApplicationSqlDialect : MsSqlDialect +{ + public ApplicationSqlDialect(bool useCommitReadLocking = false) + : base(useReadCommittedLockForCommitReads: useCommitReadLocking) + { + } +} +``` + +Register the subclass as before, for example +`.WithDialect(new ApplicationSqlDialect())` on your SQL persistence wireup. + +### 2. Keep existing offset SQL + +If you need to preserve several legacy checkpoint SQL overrides for now, add +the following override to your existing dialect. It makes all four checkpoint +query shapes use the old virtual properties and offset paging: ```csharp -protected override string? GetCheckpointKeysetQuery(bool scoped, bool bounded, int pageSize) - => null; +using NEventStore.Persistence.Sql.SqlDialects; + +public class CompatibilitySqlDialect : MsSqlDialect +{ + // Keep any existing GetCommitsFrom...Checkpoint overrides in this class. + protected override string? GetCheckpointKeysetQuery( + bool scoped, bool bounded, int pageSize) => null; +} ``` -Return `null` only for the shapes that need the old SQL, or call the base hook and -adapt its keyset query. Custom SQL must return the same commit columns in the -same order, seek after the active lower checkpoint parameter, retain the bucket -filter and upper bound when requested, and order by checkpoint. Don't bind a -limit for page size zero or use the offset parameter. +You can also opt out for only the shape whose SQL you haven't migrated. This +example keeps a custom global, open-ended feed on offset paging, while other +checkpoint reads still use keyset paging: + +```csharp +using NEventStore.Persistence.Sql.SqlDialects; + +public sealed class LegacyGlobalFeedDialect : MsSqlDialect +{ + public override string GetCommitsFromCheckpoint => + base.GetCommitsFromCheckpoint.Replace( + "FROM Commits", "FROM Commits WITH (READCOMMITTEDLOCK)"); + + protected override string? GetCheckpointKeysetQuery( + bool scoped, bool bounded, int pageSize) => + !scoped && !bounded + ? null + : base.GetCheckpointKeysetQuery(scoped, bounded, pageSize); +} +``` + +The two flags correspond to these public read methods, including their async equivalents: + +| `scoped` | `bounded` | Checkpoint read | Legacy SQL property | +| --- | --- | --- | --- | +| `false` | `false` | `GetFrom(after)` | `GetCommitsFromCheckpoint` | +| `true` | `false` | `GetFrom(bucket, after)` | `GetCommitsFromBucketAndCheckpoint` | +| `false` | `true` | `GetFromTo(after, upper)` | `GetCommitsFromToCheckpoint` | +| `true` | `true` | `GetFromTo(bucket, after, upper)` | `GetCommitsFromToBucketAndCheckpoint` | + +### 3. Carry a custom filter into the built-in keyset query + +If the change is small, call the base hook and adapt its SQL. This example +excludes the fixed `maintenance` bucket from global feeds without changing +bucket-scoped reads. The built-in query retains its bounds, ordering, page limit, +and any configured SQL Server read-locking hint: + +```csharp +using System; +using NEventStore.Persistence.Sql.SqlDialects; + +public sealed class ApplicationFeedDialect : MsSqlDialect +{ + protected override string? GetCheckpointKeysetQuery( + bool scoped, bool bounded, int pageSize) + { + var sql = base.GetCheckpointKeysetQuery(scoped, bounded, pageSize); + if (scoped || sql is null) + return sql; + + const string where = "WHERE "; + int index = sql.IndexOf(where, StringComparison.Ordinal); + if (index < 0) + throw new InvalidOperationException("The checkpoint query has no WHERE clause."); + + // This is a fixed application filter, not interpolated user input. + return sql.Insert(index + where.Length, "BucketId <> 'maintenance' AND "); + } +} +``` + +This rewrite is specific to the built-in SQL Server query shape. Test it if +you upgrade the provider or change the base dialect. + +### 4. Supply a complete keyset query + +For a larger change, return your own SQL. This example supplies both global +query shapes and delegates bucket-scoped reads to the built-in query: + +```csharp +using NEventStore.Persistence.Sql.SqlDialects; + +public sealed class CustomGlobalFeedDialect : MsSqlDialect +{ + protected override string? GetCheckpointKeysetQuery( + bool scoped, bool bounded, int pageSize) + { + if (scoped) + return base.GetCheckpointKeysetQuery(scoped, bounded, pageSize); + + var lower = bounded ? FromCheckpointNumber : CheckpointNumber; + var upper = bounded ? $" AND CheckpointNumber <= {ToCheckpointNumber}" : ""; + var top = pageSize > 0 ? $"TOP ({Limit}) " : ""; + + return $""" + SELECT {top}BucketId, StreamId, StreamIdOriginal, StreamRevision, + CommitId, CommitSequence, CommitStamp, CheckpointNumber, Headers, Payload + FROM Commits + WHERE CheckpointNumber > {lower}{upper} + AND BucketId <> 'maintenance' + ORDER BY CheckpointNumber + """; + } +} +``` + +A complete query must: + +- Return the standard commit columns in their existing order, including + `CheckpointNumber`, and return each matching checkpoint only once. +- Use the active lower-bound parameter with `>`, preserve the bucket predicate + for scoped reads and `<= ToCheckpointNumber` for bounded reads, and order by + checkpoint ascending. +- Use the dialect's `Limit` parameter only when `pageSize > 0`. Do not use + `Skip` or introduce other parameters that the statement does not bind. +- Explicitly include any provider-specific hints your custom query needs. + Returning complete SQL does not automatically add the SQL Server read-locking + hint. Call the base hook if you want to retain its configured hint. + +After migrating, exercise sync and async reads, a range spanning multiple +pages, and `PageSize = 0`. Check the expected checkpoints in order and verify +that any filter, hint, or join from your old override is still in effect. -Independent `ISqlDialect` implementations, subclasses that disable paging, and -custom statement wrappers that don't use the built-in executor keep their -existing paging behavior. +Subclasses that disable paging, independent `ISqlDialect` implementations, +and custom statement wrappers that don't use the built-in executor keep their +existing paging behavior; the new keyset hook is not used for those reads. ## Large catch-up comparison