From 5d3ec0b461f6534da64fc9af3aaf4a7d91ced04b Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 12:07:52 +0100 Subject: [PATCH 1/4] 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 8927227b5ea6f17f111de7af6628b89216e77c13 Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 12:15:24 +0100 Subject: [PATCH 2/4] 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 0275a6e5fea1afbfda91f6bdc91bb4b1f31b82d3 Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 12:31:05 +0100 Subject: [PATCH 3/4] 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 fa699ea88b536b6d789f3c84fb61c54a00ae80a0 Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 12:47:02 +0100 Subject: [PATCH 4/4] 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