diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 30d4290..0d1c235 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,14 +28,14 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: fetch-depth: 0 fetch-tags: true submodules: recursive - name: Setup .NET SDKs - uses: actions/setup-dotnet@v5 + uses: actions/setup-dotnet@v6 with: dotnet-version: | 8.0.x @@ -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') }} @@ -152,14 +152,14 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: fetch-depth: 0 fetch-tags: true submodules: recursive - name: Setup .NET SDKs - uses: actions/setup-dotnet@v5 + uses: actions/setup-dotnet@v6 with: dotnet-version: | 8.0.x @@ -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 ad27903..4a81b97 100644 --- a/.github/workflows/pack-and-publish.yml +++ b/.github/workflows/pack-and-publish.yml @@ -24,14 +24,14 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: ref: ${{ inputs.branch }} fetch-depth: 0 submodules: recursive - name: Setup .NET - uses: actions/setup-dotnet@v5 + uses: actions/setup-dotnet@v6 with: dotnet-version: | 8.0.x @@ -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') }} diff --git a/Changelog.md b/Changelog.md index 24e574e..fce59a4 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,5 +1,17 @@ # NEventStore.Persistence.Sql +## 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 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 + +- **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 - Added explicit support for net8.0,net9.0,net10.0 diff --git a/docs/Checkpoint-Seek-Paging.md b/docs/Checkpoint-Seek-Paging.md new file mode 100644 index 0000000..e986f21 --- /dev/null +++ b/docs/Checkpoint-Seek-Paging.md @@ -0,0 +1,199 @@ +# 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. 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 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 +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; +} +``` + +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. + +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 + +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/CheckpointReadLockTests.cs b/src/NEventStore.Persistence.MsSql.Tests/CheckpointReadLockTests.cs new file mode 100644 index 0000000..72fa2b6 --- /dev/null +++ b/src/NEventStore.Persistence.MsSql.Tests/CheckpointReadLockTests.cs @@ -0,0 +1,213 @@ +#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 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_applies_only_to_all_public_commit_read_queries() + { + var ordinary = new MsSqlDialect(); + 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(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( + 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(CommitTime, 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, @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(CommitTime.AddMilliseconds(10), Bucket))!.CheckpointToken; + higher.Should().BeGreaterThan(lower); + 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(useReadCommittedLockForCommitReads: true)); + var pending = Task.Run(() => Read(locking, query, seed.CheckpointToken, higher, 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 read must wait for the uncommitted matching row"); + } + finally + { + if (commit) transaction.Commit(); + else transaction.Rollback(); + // Drain the poll before disposing its engine or dropping the test database. + await pending; + } + + 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 + { + manageDatabase.CommandText = $"DROP DATABASE [{db}]"; + await manageDatabase.ExecuteNonQueryAsync(); + } + } + + 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 Read(IPersistStreams engine, Query query, long after, long upper, bool useAsync, bool scoped) + { + if (!useAsync) + { +#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, _) => + { + result.Add(commit.CheckpointToken); + return Task.FromResult(true); + }, (error, _) => Task.FromException(error)); + 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(); + } +} +#endif 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..a86b952 --- /dev/null +++ b/src/NEventStore.Persistence.Sql.Tests/PersistenceTests.CheckpointPaging.cs @@ -0,0 +1,101 @@ +#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!; + 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); + 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(); + } +} +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.Sql/SqlDialects/CheckpointKeysetQuery.cs b/src/NEventStore.Persistence.Sql/SqlDialects/CheckpointKeysetQuery.cs new file mode 100644 index 0000000..c018496 --- /dev/null +++ b/src/NEventStore.Persistence.Sql/SqlDialects/CheckpointKeysetQuery.cs @@ -0,0 +1,42 @@ +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? CreateDefault(CommonSqlDialect dialect, bool scoped, bool bounded, int pageSize) + { + // 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. + 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 (dialect is MsSqlDialect sqlServer) + { + query = sqlServer.AddReadCommittedLockToFromCommits(query); + return pageSize > 0 ? query.Insert("SELECT".Length, " TOP (@Limit)") : query; + } + + if (dialect is OracleNativeDialect) + { + 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/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/SqlDialects/MsSqlDialect.cs b/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs index f1ed780..b6ba0f0 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 _useReadCommittedLockForCommitReads; + + /// Initializes the dialect with unchanged database read semantics. + public MsSqlDialect() : this(false) + { + } + + /// 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 useReadCommittedLockForCommitReads) + { + _useReadCommittedLockForCommitReads = useReadCommittedLockForCommitReads; + } + /// public override string InitializeStorage { @@ -25,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 @@ -45,22 +66,22 @@ public override string PersistCommit /// public override string GetCommitsFromCheckpoint { - get { return CommonTableExpressionPaging(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 CommonTableExpressionPaging(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 @@ -68,6 +89,17 @@ public override string GetStreamsRequiringSnapshots get { return NaturalPaging(base.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. + internal 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) { return "SET ROWCOUNT @Limit;\n" + RemovePaging(query); 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..06425d5 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,26 @@ 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) + { + // 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); + } + /// public Task PurgeAsync(CancellationToken cancellationToken) { diff --git a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.cs b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.cs index 60d3107..689bb76 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,41 @@ 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. + /// Dialect opt-outs and separate statement wrappers keep their existing offset path. + private IEnumerable ReadCheckpointPages(IDbStatement query, bool scoped, bool bounded) + { + // 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), (_, _) => { }); + } + + /// 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..131214b --- /dev/null +++ b/src/NEventStore.Persistence.Sqlite.Tests/CheckpointPagingDeletionTests.cs @@ -0,0 +1,127 @@ +#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, 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); + 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"); + + 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; + 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); + } + } + + [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 + { + 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, customKeyset ? new CustomKeysetDialect() : new LegacyCheckpointDialect()); + engine.Initialize(); + var first = engine.Commit("first".BuildAttempt(bucketId: Bucket))!.CheckpointToken; + var hidden = engine.Commit("hidden".BuildAttempt(bucketId: "hidden"))!.CheckpointToken; + var last = engine.Commit("last".BuildAttempt(bucketId: Bucket))!.CheckpointToken; + + // 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) + { +#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 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 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 @@ +