From bfffc8776dd32a576a9c4545acc161459b2eb4a1 Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 16:40:01 +0100 Subject: [PATCH 1/7] Reproduce SQL Server checkpoint overtaking (#72) Co-authored-by: Codex --- dependencies/NEventStore | 2 +- ...tStore.Persistence.MsSql.Core.Tests.csproj | 4 +- .../SafeCheckpointPollingTests.cs | 140 ++++++++++++++++++ ...tStore.Persistence.MySql.Core.Tests.csproj | 4 +- ...Store.Persistence.Oracle.Core.Tests.csproj | 4 +- ...e.Persistence.PostgreSql.Core.Tests.csproj | 4 +- ...Store.Persistence.Sqlite.Core.Tests.csproj | 4 +- 7 files changed, 151 insertions(+), 11 deletions(-) create mode 100644 src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs diff --git a/dependencies/NEventStore b/dependencies/NEventStore index 3d58d5a..d06da7c 160000 --- a/dependencies/NEventStore +++ b/dependencies/NEventStore @@ -1 +1 @@ -Subproject commit 3d58d5a9be3ed74d5217522262ad1ca25a5e394f +Subproject commit d06da7c9c27a7964c8b9c9b5fd0f20371a6ead50 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 b3af844..e34d219 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 @@ -21,8 +21,8 @@ - - + + diff --git a/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs b/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs new file mode 100644 index 0000000..db5c4d4 --- /dev/null +++ b/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs @@ -0,0 +1,140 @@ +#if NUNIT +using System.Transactions; +using Microsoft.Data.SqlClient; +using NEventStore.Persistence.AcceptanceTests; +using NEventStore.Persistence.Sql; +using NEventStore.Persistence.Sql.SqlDialects; +using NEventStore.Serialization.Binary; +using NUnit.Framework; +using Assert = NUnit.Framework.Assert; + +namespace NEventStore.Persistence.MsSql.Tests; + +[TestFixture] +public class SafeCheckpointPollingTests +{ + private const string Bucket = "checkpoint-test"; + private static readonly DateTime CommitTime = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + [TestCase(false)] + [TestCase(true)] + public async Task Fresh_reader_does_not_skip_a_lower_commit_held_by_an_ambient_writer(bool useAsync) + { + await WithDatabase(true, async settings => + { + using var reader = Open(settings, new MsSqlDialect()); + reader.Initialize(); + var seed = await Write(reader, "seed", useAsync); + var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20)); + using var cancel = timeout.Token.Register(() => + { + ready.TrySetCanceled(); + release.TrySetCanceled(); + }); + var delayed = Task.Run(async () => + { + using var scope = new TransactionScope(TransactionScopeOption.RequiresNew, + new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }, + TransactionScopeAsyncFlowOption.Enabled); + using var writer = Open(settings, new MsSqlDialect(), TransactionScopeOption.Required); + try + { + ready.TrySetResult(await Write(writer, "lower", useAsync)); + if (await release.Task) scope.Complete(); + } + catch (Exception error) + { + ready.TrySetException(error); + throw; + } + }); + long lower; + long higher; + long[] first; + try + { + lower = await ready.Task; + higher = await Write(reader, "higher", useAsync); + first = await ReadLegacy(reader, seed, useAsync); + Assert.That(first, Is.EqualTo(new[] { higher }), "the legacy poll stores the higher checkpoint"); + } + finally + { + release.TrySetResult(true); + await delayed; + } + + using var restarted = Open(settings, new MsSqlDialect()); + var remaining = await ReadLegacy(restarted, first.Last(), useAsync); + Assert.That(first.Concat(remaining), Is.EqualTo(new[] { lower, higher }), + "a successful lower commit must not become unreachable after saving a checkpoint"); + }); + } + + private static async Task Write(IPersistStreams engine, string streamId, bool useAsync) + { + var attempt = streamId.BuildAttempt(CommitTime, Bucket); + var commit = useAsync ? await engine.CommitAsync(attempt, CancellationToken.None) : engine.Commit(attempt); + return commit!.CheckpointToken; + } + + private static async Task ReadLegacy(IPersistStreams engine, long after, bool useAsync) + { + if (!useAsync) return engine.GetFrom(Bucket, after).Select(c => c.CheckpointToken).ToArray(); + var results = new List(); + await engine.GetFromAsync(Bucket, after, Collect(results), CancellationToken.None); + return results.ToArray(); + } + + private static LambdaAsyncObserver Collect(List results) => + new((commit, _) => + { + results.Add(commit.CheckpointToken); + return Task.FromResult(true); + }, (error, _) => Task.FromException(error)); + + private static IPersistStreams Open(string settings, MsSqlDialect dialect, TransactionScopeOption? scope = null) + { +#if NET8_0_OR_GREATER + AppContext.SetSwitch("System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization", true); +#endif + var serializer = new BinarySerializer(); + return new SqlPersistenceFactory(new NetStandardConnectionFactory(SqlClientFactory.Instance, settings), + serializer, new DefaultEventSerializer(serializer), dialect, scopeOption: scope, pageSize: 1).Build(); + } + + private static async Task WithDatabase(bool rcsi, Func test) + { + var settings = new SqlConnectionStringBuilder( + Environment.GetEnvironmentVariable("NEventStore.MsSql") + ?? throw new InvalidOperationException("Set NEventStore.MsSql to a disposable SQL Server.")) + { + InitialCatalog = "master", Pooling = false, Enlist = false + }; + var db = "NEventStore_Issue72_" + Guid.NewGuid().ToString("N"); + using var admin = new SqlConnection(settings.ConnectionString); + await admin.OpenAsync(); + using var cmd = admin.CreateCommand(); + cmd.CommandText = $"CREATE DATABASE [{db}]"; + await cmd.ExecuteNonQueryAsync(); + try + { + if (rcsi) + { + cmd.CommandText = $"ALTER DATABASE [{db}] SET READ_COMMITTED_SNAPSHOT ON"; + await cmd.ExecuteNonQueryAsync(); + } + settings.InitialCatalog = db; + settings.Enlist = true; + await test(settings.ConnectionString); + } + finally + { + cmd.CommandText = $"DROP DATABASE [{db}]"; + await cmd.ExecuteNonQueryAsync(); + } + } +} +#endif 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 123d687..d2e1921 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 @@ -22,8 +22,8 @@ - - + + 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 ab7af24..73d6ed7 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 @@ -25,8 +25,8 @@ - - + + 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 83ee2fd..89731be 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 @@ -19,8 +19,8 @@ - - + + 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 7ea3791..e67e8a1 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 @@ -27,8 +27,8 @@ - - + + From d491bd03389c4bc1001cc42ef1dd4470a7ebfbb9 Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 16:40:06 +0100 Subject: [PATCH 2/7] Add opt-in safe checkpoint polling for SQL Server (#72) Co-authored-by: Codex --- Changelog.md | 2 + docs/SqlServer-Safe-Checkpoint-Polling.md | 94 ++++++++ ...tStore.Persistence.MsSql.Core.Tests.csproj | 1 + .../SafeCheckpointPollingTests.cs | 227 ++++++++++++++++-- .../SqlDialects/MsSqlDialect.cs | 34 ++- .../SqlPersistenceEngine.Async.cs | 12 +- .../SqlPersistenceEngine.SafePolling.cs | 95 ++++++++ .../SqlPersistenceEngine.cs | 8 +- 8 files changed, 446 insertions(+), 27 deletions(-) create mode 100644 docs/SqlServer-Safe-Checkpoint-Polling.md create mode 100644 src/NEventStore.Persistence.Sql/SqlPersistenceEngine.SafePolling.cs diff --git a/Changelog.md b/Changelog.md index fce59a4..1eebe90 100644 --- a/Changelog.md +++ b/Changelog.md @@ -2,6 +2,8 @@ ## Unreleased +- Add opt-in safe checkpoint polling for the built-in SQL Server provider ([#72](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/72), [#21](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/21)). It preserves numeric checkpoints, but coordinates all writers in the store and can increase write latency under long transactions. See [Safe checkpoint polling on SQL Server](docs/SqlServer-Safe-Checkpoint-Polling.md) for rollout and limitations. + - 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) diff --git a/docs/SqlServer-Safe-Checkpoint-Polling.md b/docs/SqlServer-Safe-Checkpoint-Polling.md new file mode 100644 index 0000000..54ed25f --- /dev/null +++ b/docs/SqlServer-Safe-Checkpoint-Polling.md @@ -0,0 +1,94 @@ +# Safe checkpoint polling on SQL Server + +Safe polling is opt-in. Enable it on the stock SQL Server dialect used by **every +writer** targeting the same `Commits` table, and on the persistence engine used +by the poller: + +```csharp +var dialect = new MsSqlDialect( + useReadCommittedLockForCommitReads: false, + enableSafeCheckpointPolling: true); + +// Pass dialect to the existing SQL persistence wireup, then configure the poller: +syncClient.StartFrom(savedCheckpoint, requireSafePolling: true); +asyncClient.Start(savedCheckpoint, requireSafePolling: true); +``` + +Use the bucket overload for a bucket-scoped projection. Persist the original +checkpoint only after successfully handling the commit. This does not make +projection processing exactly-once. Verify or rewind existing projection +positions if legacy polling may already have missed commits. + +## How it works + +The writer takes an exclusive, transaction-owned application lock **before** +SQL Server assigns the checkpoint. The lock is scoped to the current database +and covers all buckets in its stock event store. It is released by the actual +commit or rollback, including at the end of an enlisted outer transaction. +Lock acquisition and insert are in one batch. If acquisition fails, the batch +does not insert. + +The safe reader captures a committed upper bound and uses ordered keyset +paging through that bound. The reader does not take the application lock. +Permanent gaps from rollbacks or deletions are allowed. The legacy +`READCOMMITTEDLOCK` option from #31 is not needed for this protocol and still +controls the legacy query hint independently. Under row-versioned +READ COMMITTED (RCSI), the reader can return the previously committed window +while a writer is in flight. Under lock-based READ COMMITTED, a reader can wait +for data locks when finding the ceiling or reading a page. + +## Rollout and limits + +- Stop new appends and drain in-flight transactions while switching every + writer to the new protocol. A legacy writer, bulk load, or direct insert + that bypasses it can invalidate the guarantee. The reader cannot check other + processes' configuration. Keep all reads on the same primary database as the + writers and use normal durable commits. +- Start safe reads and enumerate synchronous results outside ambient + transactions. The provider rejects an ambient reader rather than exposing + its own uncommitted writes. Ambient *writers* continue to use normal + transaction enlistment; the gate follows the enlistment. +- This qualification targets the built-in engine and `MsSqlDialect` on + SQL Server 2022 using the stock `Commits` layout. Custom engine or dialect + subclasses, other SQL engines, and Azure SQL are not qualified by this change. +- No schema migration or new checkpoint column is required. Do not reuse a + saved checkpoint across `Purge`, `Drop`, identity resets, or recovery that + loses commits already seen by a poller. + +## Performance trade-off + +Safe polling adds one indexed ceiling lookup per poll and serializes writers +across the database. The application-lock call is in the existing append +batch, not a separate network round trip. The main cost is **time between +acquiring the lock and committing**. A long outer transaction, including any +synchronous projection work, can queue unrelated writers on other streams or +buckets. Legacy reads and default writes do not acquire this gate. A lock +wait or command timeout is a failed append, not permission to insert or to +skip a checkpoint. + +Measure qualified application workloads against the same schema and settings +with safe mode on and off: commits/second, p95/p99 end-to-end append time, +and reader polling lag. Include short provider-local transactions, concurrent +ambient writers, and real projection work held inside the outer transaction. +The insert-only application lock from the #72 discussion remains an alternative +to prove separately, not part of this guarantee. + +### Initial contention measurement + +A local SQL Server 2022 Developer / .NET 10 loopback run used warmed pooled +connections, distinct streams and buckets, one append per ambient transaction, +and three alternating-order trials per configuration. Listed rates and +percentiles are the medians of those trials. The 12 ms hold was a delay after +the append, not real projection SQL. These figures illustrate contention, not +production capacity or Azure SQL performance. + +| Writers | Post-append hold | Legacy commits/s | Safe commits/s | Legacy p95 / p99 | Safe p95 / p99 | +| --- | ---: | ---: | ---: | ---: | ---: | +| 1 | 0 ms | 533 | 520 | 2.93 / 5.60 ms | 3.51 / 5.53 ms | +| 8 | 0 ms | 2,264 | 895 | 5.67 / 14.46 ms | 12.31 / 19.27 ms | +| 8 | 12 ms | 521 | 74 | 18.21 / 21.04 ms | 116.46 / 134.78 ms | + +The hold case is the most relevant to #72's ambient-transaction concern. +Before opting in on a heavily contended store, measure its actual workload. +This protocol is a correctness-first choice, not a recommended default for +high-throughput writers. 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 e34d219..93bdf44 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 @@ -30,6 +30,7 @@ + diff --git a/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs b/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs index db5c4d4..cd9358f 100644 --- a/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs +++ b/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs @@ -1,8 +1,11 @@ #if NUNIT +using System.Collections.Concurrent; +using System.Diagnostics; using System.Transactions; using Microsoft.Data.SqlClient; using NEventStore.Persistence.AcceptanceTests; using NEventStore.Persistence.Sql; +using NEventStore.PollingClient; using NEventStore.Persistence.Sql.SqlDialects; using NEventStore.Serialization.Binary; using NUnit.Framework; @@ -18,7 +21,7 @@ public class SafeCheckpointPollingTests [TestCase(false)] [TestCase(true)] - public async Task Fresh_reader_does_not_skip_a_lower_commit_held_by_an_ambient_writer(bool useAsync) + public async Task Legacy_polling_can_miss_a_lower_commit_held_by_an_ambient_writer(bool useAsync) { await WithDatabase(true, async settings => { @@ -33,23 +36,7 @@ await WithDatabase(true, async settings => ready.TrySetCanceled(); release.TrySetCanceled(); }); - var delayed = Task.Run(async () => - { - using var scope = new TransactionScope(TransactionScopeOption.RequiresNew, - new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }, - TransactionScopeAsyncFlowOption.Enabled); - using var writer = Open(settings, new MsSqlDialect(), TransactionScopeOption.Required); - try - { - ready.TrySetResult(await Write(writer, "lower", useAsync)); - if (await release.Task) scope.Complete(); - } - catch (Exception error) - { - ready.TrySetException(error); - throw; - } - }); + var delayed = HoldLowerWrite(settings, new MsSqlDialect(), useAsync, ready, release); long lower; long higher; long[] first; @@ -68,14 +55,210 @@ await WithDatabase(true, async settings => using var restarted = Open(settings, new MsSqlDialect()); var remaining = await ReadLegacy(restarted, first.Last(), useAsync); - Assert.That(first.Concat(remaining), Is.EqualTo(new[] { lower, higher }), - "a successful lower commit must not become unreachable after saving a checkpoint"); + Assert.That(remaining, Is.Empty, "the fresh legacy poll cannot recover the skipped commit"); + Assert.That(await ReadLegacy(restarted, seed, useAsync), Is.EqualTo(new[] { lower, higher }), + "replaying from before the gap proves that the lower commit did commit"); + }); + } + + [TestCase(true, false, false, true)] + [TestCase(true, true, true, true)] + [TestCase(true, false, true, false)] + [TestCase(true, true, false, false)] + [TestCase(false, false, true, true)] + [TestCase(false, true, false, true)] + [TestCase(false, false, false, false)] + [TestCase(false, true, true, false)] + public async Task Safe_polling_resumes_without_missing_commits_or_stalling_at_rollback_gaps( + bool rcsi, bool useAsync, bool scoped, bool commitLower) + { + await WithDatabase(rcsi, async settings => + { + var dialect = new MsSqlDialect(useReadCommittedLockForCommitReads: false, enableSafeCheckpointPolling: true); + using var reader = Open(settings, dialect); + reader.Initialize(); + var seed = await Write(reader, "seed", useAsync); + var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(25)); + using var cancel = timeout.Token.Register(() => + { + ready.TrySetCanceled(); + release.TrySetCanceled(); + }); + var delayed = HoldLowerWrite(settings, dialect, useAsync, ready, release); + Task? competing = null; + long lower; + string? bucket = scoped ? Bucket : null; + try + { + lower = await ready.Task; + competing = Task.Run(async () => + { + using var writer = Open(settings, dialect); + return await Write(writer, "higher", useAsync, scoped ? Bucket : "other-bucket"); + }); + await AssertWriterIsWaiting(settings, timeout.Token); + + if (rcsi) + { + var safe = (ISafeCheckpointPolling)reader; + var empty = new List(); + if (useAsync) await safe.ReadForPollingAsync(seed, bucket, Collect(empty), timeout.Token); + else empty.AddRange(safe.ReadForPolling(seed, bucket).Select(c => c.CheckpointToken)); + Assert.That(empty, Is.Empty, "the in-flight lower commit and its waiting successor are not visible"); + } + } + finally + { + release.TrySetResult(commitLower); + await delayed; + if (competing != null) await competing; + } + + var higher = await competing!; + Assert.That(higher, Is.GreaterThan(lower)); + var first = await PollOne(reader, seed, bucket, useAsync); + Assert.That(first, Is.EqualTo(commitLower ? lower : higher)); + using var restarted = Open(settings, dialect); + if (commitLower) + Assert.That(await PollOne(restarted, first, bucket, useAsync), Is.EqualTo(higher)); + else + Assert.That(((ISafeCheckpointPolling)restarted).ReadForPolling(first, bucket), Is.Empty); + }); + } + + [Test] + public async Task A_new_append_does_not_move_the_window_while_the_reader_is_paging() + { + await WithDatabase(true, async settings => + { + var dialect = new MsSqlDialect(false, true); + using var reader = Open(settings, dialect); + reader.Initialize(); + var first = await Write(reader, "first", false); + var second = await Write(reader, "second", false); + var safe = (ISafeCheckpointPolling)reader; + using var pages = safe.ReadForPolling(0, Bucket).GetEnumerator(); + Assert.That(pages.MoveNext(), Is.True); + Assert.That(pages.Current.CheckpointToken, Is.EqualTo(first)); + + using var writer = Open(settings, dialect); + writer.DeleteStream(Bucket, "first"); + var newer = await Write(writer, "newer", false); + + Assert.That(pages.MoveNext(), Is.True); + Assert.That(pages.Current.CheckpointToken, Is.EqualTo(second)); + Assert.That(pages.MoveNext(), Is.False, "new appends cannot extend the current poll"); + Assert.That(safe.ReadForPolling(second, Bucket).Select(c => c.CheckpointToken), + Is.EqualTo(new[] { newer })); }); } - private static async Task Write(IPersistStreams engine, string streamId, bool useAsync) + [Test] + public void Safe_mode_rejects_disabled_or_unqualified_dialects_and_ambient_reads() + { + using var legacy = Open("Server=unused", new MsSqlDialect()); + using var derived = Open("Server=unused", new DerivedDialect()); + var legacyReader = (ISafeCheckpointPolling)legacy; + Assert.That(legacyReader.SupportsSafeCheckpointPolling, Is.False); + Assert.That(((ISafeCheckpointPolling)derived).SupportsSafeCheckpointPolling, Is.False); + Assert.Throws(() => legacyReader.ReadForPolling(0, null)); + + using var engine = Open("Server=unused", new MsSqlDialect(false, true)); + var reader = (ISafeCheckpointPolling)engine; + Assert.That(reader.SupportsSafeCheckpointPolling, Is.True); + var deferred = reader.ReadForPolling(0, null); + using var ambient = new TransactionScope(); + Assert.Throws(() => reader.ReadForPolling(0, null)); + Assert.Throws(() => deferred.ToArray()); + Assert.Throws(() => reader.ReadForPollingAsync(0, null, Collect([]))); + } + + private sealed class DerivedDialect() : MsSqlDialect(false, true); + + private static Task HoldLowerWrite(string settings, MsSqlDialect dialect, bool useAsync, + TaskCompletionSource ready, TaskCompletionSource release) => Task.Run(async () => + { + using var scope = new TransactionScope(TransactionScopeOption.RequiresNew, + new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }, + TransactionScopeAsyncFlowOption.Enabled); + using var writer = Open(settings, dialect, TransactionScopeOption.Required); + try + { + ready.TrySetResult(await Write(writer, "lower", useAsync)); + if (await release.Task) scope.Complete(); + } + catch (Exception error) + { + ready.TrySetException(error); + throw; + } + }); + + private static async Task AssertWriterIsWaiting(string settings, CancellationToken cancellationToken) + { + using var probe = new SqlConnection(settings); + await probe.OpenAsync(cancellationToken); + using var command = probe.CreateCommand(); + command.CommandText = """ + SELECT COUNT(*) FROM sys.dm_tran_locks + WHERE resource_type = 'APPLICATION' AND resource_database_id = DB_ID() + AND request_mode = 'X' AND request_status = 'WAIT'; + """; + var clock = Stopwatch.StartNew(); + while (clock.Elapsed < TimeSpan.FromSeconds(10)) + { + if ((int)(await command.ExecuteScalarAsync(cancellationToken))! > 0) return; + await Task.Delay(25, cancellationToken); + } + Assert.Fail("the second writer must wait for the application's transaction-owned checkpoint lock"); + } + + private static async Task PollOne(IPersistStreams engine, long after, string? bucket, bool useAsync) + { + var store = new OptimisticEventStore(engine, [new PassThroughHook()], []); + var received = new ConcurrentQueue(); + using var completed = new ManualResetEventSlim(); + if (useAsync) + { + var observer = new LambdaAsyncObserver((commit, _) => + { + received.Enqueue(commit.CheckpointToken); + return Task.FromResult(false); + }, onCompletedAsync: _ => + { + completed.Set(); + return Task.CompletedTask; + }); + using var client = new AsyncPollingClient(store.Advanced, observer); + if (bucket == null) client.Start(after, requireSafePolling: true); + else client.Start(bucket, after, requireSafePolling: true); + bool gotCommit = completed.Wait(TimeSpan.FromSeconds(5)); + await client.StopAsync(); + Assert.That(gotCommit, Is.True); + } + else + { + using var client = new PollingClient2(store.Advanced, commit => + { + received.Enqueue(commit.CheckpointToken); + completed.Set(); + return PollingClient2.HandlingResult.Stop; + }, waitInterval: 10000); + if (bucket == null) client.StartFrom(after, requireSafePolling: true); + else client.StartFromBucket(bucket, after, requireSafePolling: true); + client.PollNow(); + Assert.That(completed.Wait(TimeSpan.FromSeconds(5)), Is.True); + } + return received.Single(); + } + + private sealed class PassThroughHook : PipelineHookBase; + + private static async Task Write(IPersistStreams engine, string streamId, bool useAsync, string bucket = Bucket) { - var attempt = streamId.BuildAttempt(CommitTime, Bucket); + var attempt = streamId.BuildAttempt(CommitTime, bucket); var commit = useAsync ? await engine.CommitAsync(attempt, CancellationToken.None) : engine.Commit(attempt); return commit!.CheckpointToken; } diff --git a/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs b/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs index b6ba0f0..ba55f86 100644 --- a/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs +++ b/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs @@ -13,6 +13,18 @@ public class MsSqlDialect : CommonSqlDialect private const int UniqueIndexViolation = 2601; private const int UniqueKeyViolation = 2627; private readonly bool _useReadCommittedLockForCommitReads; + private readonly string? _safePersistCommit; + + // The lock is scoped to the current database, not to the bucket or the connection. + private const string AcquireCheckpointWriterLock = """ + DECLARE @checkpointLockResult int; + EXEC @checkpointLockResult = sys.sp_getapplock + @Resource = N'NEventStore:Commits:CheckpointWriter', + @LockMode = N'Exclusive', @LockOwner = N'Transaction', + @DbPrincipal = N'public'; + IF @checkpointLockResult < 0 + THROW 51072, 'Could not acquire the NEventStore checkpoint writer lock.', 1; + """; /// Initializes the dialect with unchanged database read semantics. public MsSqlDialect() : this(false) @@ -29,10 +41,30 @@ public MsSqlDialect() : this(false) /// a mitigation for legacy polling, not a guarantee of checkpoint publication order. /// public MsSqlDialect(bool useReadCommittedLockForCommitReads) + : this(useReadCommittedLockForCommitReads, enableSafeCheckpointPolling: false) + { + } + + /// Initializes the dialect with optional locking reads and ordered commit publication. + /// Whether to request the legacy locking-read mitigation. + /// Whether to serialize checkpoint allocation through commit or rollback. + /// + /// Every writer targeting the same commits table must use the safe-polling configuration. + /// This is independent of the legacy locking-read mitigation. + /// + public MsSqlDialect(bool useReadCommittedLockForCommitReads, bool enableSafeCheckpointPolling) { _useReadCommittedLockForCommitReads = useReadCommittedLockForCommitReads; + if (enableSafeCheckpointPolling) + { + // Batch the gate and insert on the existing transaction: no extra network round trip. + _safePersistCommit = AcquireCheckpointWriterLock + "\n" + MsSqlStatements.PersistCommits; + } } + /// Gets whether this built-in dialect uses the qualified writer protocol. + internal bool SupportsSafeCheckpointPolling => _safePersistCommit != null && GetType() == typeof(MsSqlDialect); + /// public override string InitializeStorage { @@ -61,7 +93,7 @@ public override string GetCommitsFromToInstant /// public override string PersistCommit { - get { return MsSqlStatements.PersistCommits; } + get { return _safePersistCommit ?? MsSqlStatements.PersistCommits; } } /// public override string GetCommitsFromCheckpoint diff --git a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs index 06425d5..a8d3b06 100644 --- a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs +++ b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs @@ -392,14 +392,22 @@ private Task DetectDuplicateAsync(CommitAttempt attempt, CancellationToken /// Executes a query against the database. /// /// - protected virtual async Task ExecuteQueryAsync( + protected virtual Task ExecuteQueryAsync( Func, CancellationToken, Task> query, IAsyncObserver asyncObserver, CancellationToken cancellationToken) + => ExecuteQueryAsync(query, asyncObserver, cancellationToken, independentRead: false); + + /// Runs a committed asynchronous query without creating an ambient scope for safe polling. + private async Task ExecuteQueryAsync( + Func, CancellationToken, Task> query, + IAsyncObserver asyncObserver, + CancellationToken cancellationToken, + bool independentRead) { ThrowWhenDisposed(); - using (var scope = OpenQueryScope()) + using (var scope = independentRead ? null : OpenQueryScope()) using (var connection = await _connectionFactory.OpenAsync(cancellationToken).ConfigureAwait(false)) using (var transaction = _dialect.OpenTransaction(connection.Current)) using (IDbStatement statement = _dialect.BuildStatement(scope, connection, transaction)) diff --git a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.SafePolling.cs b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.SafePolling.cs new file mode 100644 index 0000000..46717c2 --- /dev/null +++ b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.SafePolling.cs @@ -0,0 +1,95 @@ +using System.Data; +using System.Transactions; +using NEventStore.Persistence.Sql.SqlDialects; + +namespace NEventStore.Persistence.Sql +{ + public partial class SqlPersistenceEngine + { + // The writer gate makes every committed checkpoint a safe ceiling, even when IDs have gaps. + private const string GetSafeCheckpointTip = "SELECT ISNULL(MAX(CheckpointNumber), CONVERT(bigint, 0)) FROM Commits;"; + + /// + public bool SupportsSafeCheckpointPolling => + GetType() == typeof(SqlPersistenceEngine) && _dialect is MsSqlDialect { SupportsSafeCheckpointPolling: true }; + + /// + /// This engine does not have the qualified writer protocol enabled. + /// An ambient transaction is active. + public IEnumerable ReadForPolling(long afterCheckpoint, string? bucketId) + { + EnsureIndependentSafePolling(); + return ReadSafeCheckpointWindow(afterCheckpoint, bucketId); + } + + /// + /// This engine does not have the qualified writer protocol enabled. + /// An ambient transaction is active. + public Task ReadForPollingAsync(long afterCheckpoint, string? bucketId, IAsyncObserver observer, + CancellationToken cancellationToken = default) + { + EnsureIndependentSafePolling(); + cancellationToken.ThrowIfCancellationRequested(); + + var adapter = BuildICommitAsyncObserverAdapter(observer, cancellationToken); + return ExecuteQueryAsync(async (statement, records, token) => + { + var tip = (await statement.ExecuteScalarAsync(GetSafeCheckpointTip, token).ConfigureAwait(false)).ToLong(); + if (tip <= afterCheckpoint) + { + // An idle poll needs only the indexed ceiling lookup. + await records.OnCompletedAsync(token).ConfigureAwait(false); + return; + } + + BindSafeCheckpointWindow(statement, afterCheckpoint, tip, bucketId); + await ReadCheckpointPagesAsync(statement, bucketId is not null, bounded: true, records, token) + .ConfigureAwait(false); + }, adapter, cancellationToken, independentRead: true); + } + + /// Streams a fixed checkpoint window without opening a connection before enumeration. + private IEnumerable ReadSafeCheckpointWindow(long afterCheckpoint, string? bucketId) + { + // A caller can create the enumerable outside a transaction and enumerate it inside one. + EnsureIndependentSafePolling(); + var commits = ExecuteQuery(statement => + { + var tip = statement.ExecuteScalar(GetSafeCheckpointTip).ToLong(); + if (tip <= afterCheckpoint) + { + // No page enumerator will own these resources when the window is empty. + statement.Dispose(); + return Enumerable.Empty(); + } + + BindSafeCheckpointWindow(statement, afterCheckpoint, tip, bucketId); + return ReadCheckpointPages(statement, bucketId is not null, bounded: true) + .Select(row => row.GetCommit(_serializer, _eventSerializer, _dialect)); + }, independentRead: true); + + foreach (var commit in commits) + yield return commit; + } + + /// Binds the exclusive resume position and fixed committed ceiling for every page. + private void BindSafeCheckpointWindow(IDbStatement statement, long afterCheckpoint, long tip, string? bucketId) + { + if (bucketId is not null) + statement.AddParameter(_dialect.BucketId, bucketId, DbType.AnsiString); + statement.AddParameter(_dialect.FromCheckpointNumber, afterCheckpoint); + statement.AddParameter(_dialect.ToCheckpointNumber, tip); + } + + /// Rejects unsafe configurations before opening a polling connection. + private void EnsureIndependentSafePolling() + { + if (!SupportsSafeCheckpointPolling) + throw new NotSupportedException("Safe checkpoint polling requires the built-in SQL Server engine and dialect with safe polling enabled."); + + // An enlisted reader could otherwise publish its own uncommitted checkpoint. + if (Transaction.Current != null) + throw new InvalidOperationException("Run safe checkpoint polling outside the ambient transaction."); + } + } +} diff --git a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.cs b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.cs index 689bb76..1c3d25c 100644 --- a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.cs +++ b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.cs @@ -11,7 +11,7 @@ namespace NEventStore.Persistence.Sql /// /// Represents a persistence engine that stores and retrieves events from a SQL database. /// - public partial class SqlPersistenceEngine : IPersistStreams + public partial class SqlPersistenceEngine : IPersistStreams, ISafeCheckpointPolling { private static readonly ILogger Logger = LogFactory.BuildLogger(typeof(SqlPersistenceEngine)); private static readonly DateTime EpochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); @@ -482,10 +482,14 @@ private bool DetectDuplicate(CommitAttempt attempt) /// /// protected virtual IEnumerable ExecuteQuery(Func> query) + => ExecuteQuery(query, independentRead: false); + + /// Opens a committed query without creating an ambient scope for safe polling. + private IEnumerable ExecuteQuery(Func> query, bool independentRead) { ThrowWhenDisposed(); - TransactionScope? scope = OpenQueryScope(); + TransactionScope? scope = independentRead ? null : OpenQueryScope(); ConnectionScope? connection = null; DbTransaction? transaction = null; IDbStatement? statement = null; From 5673a826b8d7ef7abe62e8d7ed976c0ea973c0a7 Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 16:43:21 +0100 Subject: [PATCH 3/7] Verify SQL Server lock failure aborts before allocation Co-authored-by: Codex --- .../SafeCheckpointPollingTests.cs | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs b/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs index cd9358f..70b4bb1 100644 --- a/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs +++ b/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs @@ -155,6 +155,48 @@ await WithDatabase(true, async settings => }); } + [Test] + public async Task Failure_to_acquire_the_gate_does_not_insert_a_commit() + { + await WithDatabase(true, async settings => + { + var dialect = new MsSqlDialect(false, true); + using var reader = Open(settings, dialect); + reader.Initialize(); + + using var holder = new SqlConnection(settings); + await holder.OpenAsync(); + using var transaction = holder.BeginTransaction(); + using var lockCommand = holder.CreateCommand(); + lockCommand.Transaction = transaction; + lockCommand.CommandText = """ + DECLARE @result int; + EXEC @result = sys.sp_getapplock + @Resource = N'NEventStore:Commits:CheckpointWriter', + @LockMode = N'Exclusive', @LockOwner = N'Transaction', + @DbPrincipal = N'public'; + SELECT @result; + """; + Assert.That((int)(await lockCommand.ExecuteScalarAsync())!, Is.GreaterThanOrEqualTo(0)); + + using var timedOutWriter = Open(settings, new ImmediateLockTimeoutDialect()); + var failure = await Assert.ThrowsAsync(async () => + await Write(timedOutWriter, "timed-out", true)); + Assert.That((failure!.InnerException as SqlException)?.Number, Is.EqualTo(51072)); + + transaction.Rollback(); + Assert.That(((ISafeCheckpointPolling)reader).ReadForPolling(0, Bucket), Is.Empty); + Assert.That(await Write(reader, "timed-out", true), Is.EqualTo(1), + "the failed batch must not even allocate a checkpoint"); + }); + } + + private sealed class ImmediateLockTimeoutDialect() : MsSqlDialect(false, true) + { + // SET options issued by a parameterized command are scoped to that batch. + public override string PersistCommit => "SET LOCK_TIMEOUT 0;\n" + base.PersistCommit; + } + [Test] public void Safe_mode_rejects_disabled_or_unqualified_dialects_and_ambient_reads() { From 2332f118e03d10c6aa2e079965069f31eef7f2dc Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 16:57:24 +0100 Subject: [PATCH 4/7] Require safe polling without serializing independent writers Co-authored-by: Codex --- .../SafeCheckpointPollingTests.cs | 41 ++++++++++++------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs b/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs index 70b4bb1..ab6e7f4 100644 --- a/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs +++ b/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs @@ -88,7 +88,9 @@ await WithDatabase(rcsi, async settings => }); var delayed = HoldLowerWrite(settings, dialect, useAsync, ready, release); Task? competing = null; + Task? pendingPoll = null; long lower; + long higher; string? bucket = scoped ? Bucket : null; try { @@ -98,26 +100,34 @@ await WithDatabase(rcsi, async settings => using var writer = Open(settings, dialect); return await Write(writer, "higher", useAsync, scoped ? Bucket : "other-bucket"); }); - await AssertWriterIsWaiting(settings, timeout.Token); - + Assert.That(await Task.WhenAny(competing, Task.Delay(TimeSpan.FromSeconds(4), timeout.Token)), + Is.SameAs(competing), "a different writer can commit before the outer transaction completes"); + higher = await competing; + Assert.That(higher, Is.GreaterThan(lower)); if (rcsi) + Assert.That(await ReadLegacy(reader, seed, useAsync, bucket), Is.EqualTo(new[] { higher }), + "the higher checkpoint really was published first"); + + pendingPoll = Task.Run(async () => { var safe = (ISafeCheckpointPolling)reader; - var empty = new List(); - if (useAsync) await safe.ReadForPollingAsync(seed, bucket, Collect(empty), timeout.Token); - else empty.AddRange(safe.ReadForPolling(seed, bucket).Select(c => c.CheckpointToken)); - Assert.That(empty, Is.Empty, "the in-flight lower commit and its waiting successor are not visible"); - } + if (!useAsync) return safe.ReadForPolling(seed, bucket).Select(c => c.CheckpointToken).ToArray(); + var result = new List(); + await safe.ReadForPollingAsync(seed, bucket, Collect(result), timeout.Token); + return result.ToArray(); + }); + await AssertReaderFenceIsWaiting(settings, timeout.Token); + Assert.That(pendingPoll.IsCompleted, Is.False, "the reader must not expose the higher commit yet"); } finally { release.TrySetResult(commitLower); await delayed; if (competing != null) await competing; + if (pendingPoll != null) await pendingPoll; } - var higher = await competing!; - Assert.That(higher, Is.GreaterThan(lower)); + Assert.That(await pendingPoll!, Is.EqualTo(commitLower ? new[] { lower, higher } : new[] { higher })); var first = await PollOne(reader, seed, bucket, useAsync); Assert.That(first, Is.EqualTo(commitLower ? lower : higher)); using var restarted = Open(settings, dialect); @@ -238,7 +248,7 @@ private static Task HoldLowerWrite(string settings, MsSqlDialect dialect, bool u } }); - private static async Task AssertWriterIsWaiting(string settings, CancellationToken cancellationToken) + private static async Task AssertReaderFenceIsWaiting(string settings, CancellationToken cancellationToken) { using var probe = new SqlConnection(settings); await probe.OpenAsync(cancellationToken); @@ -254,7 +264,7 @@ SELECT COUNT(*) FROM sys.dm_tran_locks if ((int)(await command.ExecuteScalarAsync(cancellationToken))! > 0) return; await Task.Delay(25, cancellationToken); } - Assert.Fail("the second writer must wait for the application's transaction-owned checkpoint lock"); + Assert.Fail("the safe reader must wait for the in-flight writer at the checkpoint fence"); } private static async Task PollOne(IPersistStreams engine, long after, string? bucket, bool useAsync) @@ -305,11 +315,14 @@ private static async Task Write(IPersistStreams engine, string streamId, b return commit!.CheckpointToken; } - private static async Task ReadLegacy(IPersistStreams engine, long after, bool useAsync) + private static async Task ReadLegacy(IPersistStreams engine, long after, bool useAsync, string? bucket = Bucket) { - if (!useAsync) return engine.GetFrom(Bucket, after).Select(c => c.CheckpointToken).ToArray(); + if (!useAsync) + return (bucket == null ? engine.GetFrom(after) : engine.GetFrom(bucket, after)) + .Select(c => c.CheckpointToken).ToArray(); var results = new List(); - await engine.GetFromAsync(Bucket, after, Collect(results), CancellationToken.None); + if (bucket == null) await engine.GetFromAsync(after, Collect(results), CancellationToken.None); + else await engine.GetFromAsync(bucket, after, Collect(results), CancellationToken.None); return results.ToArray(); } From c93c546da19a5dc83a2b856cca7209946d93002b Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 16:57:32 +0100 Subject: [PATCH 5/7] Fence safe polls without serializing SQL Server writers Co-authored-by: Codex --- Changelog.md | 2 +- docs/SqlServer-Safe-Checkpoint-Polling.md | 123 ++++++++++-------- .../SafeCheckpointPollingTests.cs | 43 ++++++ .../SqlDialects/MsSqlDialect.cs | 38 ++++-- .../SqlPersistenceEngine.Async.cs | 5 + .../SqlPersistenceEngine.SafePolling.cs | 19 ++- 6 files changed, 160 insertions(+), 70 deletions(-) diff --git a/Changelog.md b/Changelog.md index 1eebe90..3b7582c 100644 --- a/Changelog.md +++ b/Changelog.md @@ -2,7 +2,7 @@ ## Unreleased -- Add opt-in safe checkpoint polling for the built-in SQL Server provider ([#72](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/72), [#21](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/21)). It preserves numeric checkpoints, but coordinates all writers in the store and can increase write latency under long transactions. See [Safe checkpoint polling on SQL Server](docs/SqlServer-Safe-Checkpoint-Polling.md) for rollout and limitations. +- Add opt-in safe checkpoint polling for the built-in SQL Server provider ([#72](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/72), [#21](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/21)). It preserves numeric checkpoints and concurrent writes; a safe poll may wait for in-flight transactions before capturing its checkpoint boundary. See [Safe checkpoint polling on SQL Server](docs/SqlServer-Safe-Checkpoint-Polling.md) for rollout and limitations. - 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) diff --git a/docs/SqlServer-Safe-Checkpoint-Polling.md b/docs/SqlServer-Safe-Checkpoint-Polling.md index 54ed25f..2498528 100644 --- a/docs/SqlServer-Safe-Checkpoint-Polling.md +++ b/docs/SqlServer-Safe-Checkpoint-Polling.md @@ -21,29 +21,33 @@ positions if legacy polling may already have missed commits. ## How it works -The writer takes an exclusive, transaction-owned application lock **before** -SQL Server assigns the checkpoint. The lock is scoped to the current database -and covers all buckets in its stock event store. It is released by the actual -commit or rollback, including at the end of an enlisted outer transaction. -Lock acquisition and insert are in one batch. If acquisition fails, the batch -does not insert. - -The safe reader captures a committed upper bound and uses ordered keyset -paging through that bound. The reader does not take the application lock. -Permanent gaps from rollbacks or deletions are allowed. The legacy -`READCOMMITTEDLOCK` option from #31 is not needed for this protocol and still -controls the legacy query hint independently. Under row-versioned -READ COMMITTED (RCSI), the reader can return the previously committed window -while a writer is in flight. Under lock-based READ COMMITTED, a reader can wait -for data locks when finding the ceiling or reading a page. +Writers take a **shared**, transaction-owned lock before SQL Server generates +the checkpoint. The lock covers all buckets in the database, and stays held +until the actual commit or rollback, including an enlisted outer transaction. +Shared locks let writers commit independently, so a higher checkpoint can +become visible first. Lock registration and insert share an existing batch and +transaction; a failed registration aborts the insert. + +A safe poll takes the **exclusive** lock on the same resource to establish its +checkpoint boundary. It waits until participating in-flight writers finish +and prevents new allocations while it reads the committed maximum. It then +releases the fence **before** opening any page or invoking a handler. After +release, new writes can proceed, and the poll uses #63's ordered keyset +reads through that fixed ceiling. A rollback leaves a legal gap, not a reason +to retry or delay after the fence is released. + +This works with both READ COMMITTED modes. The fence is necessary even with +RCSI: a normal versioned query would still see the higher commit first. The +legacy locking-read option from #31 is not needed for this protocol. ## Rollout and limits - Stop new appends and drain in-flight transactions while switching every - writer to the new protocol. A legacy writer, bulk load, or direct insert - that bypasses it can invalidate the guarantee. The reader cannot check other - processes' configuration. Keep all reads on the same primary database as the - writers and use normal durable commits. + writer and safe reader on this store to the new protocol. A legacy writer, + bulk load, or direct insert that bypasses it can invalidate the guarantee. + A reader from the earlier exclusive-writer draft is also incompatible with + shared writers. Keep all reads on the same primary database as the writers + and use normal durable commits. - Start safe reads and enumerate synchronous results outside ambient transactions. The provider rejects an ambient reader rather than exposing its own uncommitted writes. Ambient *writers* continue to use normal @@ -57,38 +61,49 @@ for data locks when finding the ceiling or reading a page. ## Performance trade-off -Safe polling adds one indexed ceiling lookup per poll and serializes writers -across the database. The application-lock call is in the existing append -batch, not a separate network round trip. The main cost is **time between -acquiring the lock and committing**. A long outer transaction, including any -synchronous projection work, can queue unrelated writers on other streams or -buckets. Legacy reads and default writes do not acquire this gate. A lock -wait or command timeout is a failed append, not permission to insert or to -skip a checkpoint. - -Measure qualified application workloads against the same schema and settings -with safe mode on and off: commits/second, p95/p99 end-to-end append time, -and reader polling lag. Include short provider-local transactions, concurrent -ambient writers, and real projection work held inside the outer transaction. -The insert-only application lock from the #72 discussion remains an alternative -to prove separately, not part of this guarantee. - -### Initial contention measurement - -A local SQL Server 2022 Developer / .NET 10 loopback run used warmed pooled -connections, distinct streams and buckets, one append per ambient transaction, -and three alternating-order trials per configuration. Listed rates and -percentiles are the medians of those trials. The 12 ms hold was a delay after -the append, not real projection SQL. These figures illustrate contention, not -production capacity or Azure SQL performance. - -| Writers | Post-append hold | Legacy commits/s | Safe commits/s | Legacy p95 / p99 | Safe p95 / p99 | -| --- | ---: | ---: | ---: | ---: | ---: | -| 1 | 0 ms | 533 | 520 | 2.93 / 5.60 ms | 3.51 / 5.53 ms | -| 8 | 0 ms | 2,264 | 895 | 5.67 / 14.46 ms | 12.31 / 19.27 ms | -| 8 | 12 ms | 521 | 74 | 18.21 / 21.04 ms | 116.46 / 134.78 ms | - -The hold case is the most relevant to #72's ambient-transaction concern. -Before opting in on a heavily contended store, measure its actual workload. -This protocol is a correctness-first choice, not a recommended default for -high-throughput writers. +The gate no longer serializes writers with one another. It does shift waiting +to polls: a long ambient transaction can delay the next safe window, and a +queued poll fence can delay incoming writers until earlier transactions +drain. This effect grows with polling frequency and transaction duration. Neither page streaming +nor projections run while the poll fence is held. There is one extra batch +per poll to capture the ceiling, not one per page. A failed gate does not +permit an append or provide a resume position. + +### Transactions and the MongoDB comparison + +There is no new SQL transaction on either path. The dialect uses the +existing append transaction (including ambient enlistment) and the existing +independent read transaction. Without any transaction-owned coordination, +releasing a session lock as the insert ends is only equivalent when that +statement itself commits. It is not equivalent for an ambient writer whose +transaction can stay open after the statement returns. + +MongoDB #118 can make writers compete for the same next key using its +document's unique ID. Here the stock SQL Server `IDENTITY` insert assigns +different IDs. An explicit `MAX(CheckpointNumber) + 1` allocator could use a +unique key and retries for short autocommit writes, but it would require +different identity/insert configuration and a durable floor so deleting the +highest commit cannot reuse a published checkpoint. Under ambient writes, +contenders for the same key would still wait for the other transaction. +That is not a drop-in optimization for this schema or transaction model. + +### Initial performance comparison + +Local SQL Server 2022 and .NET 10, pooled loopback connections, eight writers +on separate streams and buckets, and one append per ambient transaction. +Three trials per configuration; the hold was a delay after the append, +not actual projection SQL. The active reader repeatedly polled every 20 ms +after each completed poll. Times below are medians of the trial percentiles. + +| Workload | Exclusive writer lock | Shared writers + poll fence | Legacy, no guarantee | +| --- | ---: | ---: | ---: | +| No hold, no poller: commits/s | 901 | 1,732 | 2,157–2,510 | +| 12 ms hold, no poller: commits/s | 75 | 540 | 528–551 | +| 12 ms hold, one poller: commits/s | 77 | 473 | 520–528 | +| 12 ms hold, one poller: p95 append | 115 ms | 24 ms | 18–19 ms | +| 12 ms hold, one poller: p95 poll duration | 4 ms | 18 ms | about 6 ms | + +These are local workload comparisons, not production capacity or event +delivery latency estimates. Use representative transaction lengths and poller +counts for deployment decisions. In particular, a poll that waits for a long +ambient transaction can add latency to both readers and later writers. diff --git a/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs b/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs index ab6e7f4..38dec81 100644 --- a/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs +++ b/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs @@ -138,6 +138,49 @@ await WithDatabase(rcsi, async settings => }); } + [Test] + public async Task Canceling_a_waiting_poll_does_not_deliver_or_leave_the_fence_held() + { + await WithDatabase(true, async settings => + { + var dialect = new MsSqlDialect(false, true); + using var engine = Open(settings, dialect); + engine.Initialize(); + var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + using var cancellation = new CancellationTokenSource(); + using var signal = timeout.Token.Register(() => + { + ready.TrySetCanceled(); + release.TrySetCanceled(); + cancellation.Cancel(); + }); + var writer = HoldLowerWrite(settings, dialect, true, ready, release); + var safe = (ISafeCheckpointPolling)engine; + var received = new List(); + Task? waitingPoll = null; + long lower; + try + { + lower = await ready.Task; + waitingPoll = safe.ReadForPollingAsync(0, Bucket, Collect(received), cancellation.Token); + await AssertReaderFenceIsWaiting(settings, timeout.Token); + cancellation.Cancel(); + await Assert.CatchAsync(() => waitingPoll); + Assert.That(received, Is.Empty); + } + finally + { + release.TrySetResult(true); + await writer; + if (waitingPoll != null) + await Task.WhenAny(waitingPoll, Task.Delay(TimeSpan.FromSeconds(5))); + } + Assert.That(safe.ReadForPolling(0, Bucket).Select(c => c.CheckpointToken), Is.EqualTo(new[] { lower })); + }); + } + [Test] public async Task A_new_append_does_not_move_the_window_while_the_reader_is_paging() { diff --git a/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs b/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs index ba55f86..7209688 100644 --- a/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs +++ b/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs @@ -15,17 +15,35 @@ public class MsSqlDialect : CommonSqlDialect private readonly bool _useReadCommittedLockForCommitReads; private readonly string? _safePersistCommit; - // The lock is scoped to the current database, not to the bucket or the connection. - private const string AcquireCheckpointWriterLock = """ + // Choose one database-wide resource so an unresolved commit in any bucket is fenced. + private const string CheckpointLockResource = "NEventStore:Commits:CheckpointWriter"; + private static readonly string AcquireSharedWriterLock = AcquireCheckpointLock("Shared"); + + /// Captures a committed checkpoint ceiling after all participating writers finish. + /// Release the fence before opening the paged reader or invoking any handler. + internal static readonly string ReadCheckpointCeiling = AcquireCheckpointLock("Exclusive") + "\n" + $""" + DECLARE @checkpointCeiling bigint; + SELECT @checkpointCeiling = ISNULL(MAX(CheckpointNumber), CONVERT(bigint, 0)) FROM Commits; + EXEC @checkpointLockResult = sys.sp_releaseapplock + @Resource = N'{CheckpointLockResource}', @LockOwner = N'Transaction', + @DbPrincipal = N'public'; + IF @checkpointLockResult < 0 + THROW 51073, 'Could not release the NEventStore checkpoint fence.', 1; + SELECT @checkpointCeiling; + """; + + /// Gets the transaction-owned lock batch for a concurrent writer or a polling fence. + /// The SQL Server application lock mode. + /// A batch that aborts before the next statement if the lock cannot be acquired. + private static string AcquireCheckpointLock(string mode) => $""" DECLARE @checkpointLockResult int; EXEC @checkpointLockResult = sys.sp_getapplock - @Resource = N'NEventStore:Commits:CheckpointWriter', - @LockMode = N'Exclusive', @LockOwner = N'Transaction', + @Resource = N'{CheckpointLockResource}', + @LockMode = N'{mode}', @LockOwner = N'Transaction', @DbPrincipal = N'public'; IF @checkpointLockResult < 0 - THROW 51072, 'Could not acquire the NEventStore checkpoint writer lock.', 1; + THROW 51072, 'Could not acquire the NEventStore checkpoint lock.', 1; """; - /// Initializes the dialect with unchanged database read semantics. public MsSqlDialect() : this(false) { @@ -45,9 +63,9 @@ public MsSqlDialect(bool useReadCommittedLockForCommitReads) { } - /// Initializes the dialect with optional locking reads and ordered commit publication. + /// Initializes the dialect with optional locking reads and checkpoint fencing. /// Whether to request the legacy locking-read mitigation. - /// Whether to serialize checkpoint allocation through commit or rollback. + /// Whether to register in-flight writes until commit or rollback for safe polling. /// /// Every writer targeting the same commits table must use the safe-polling configuration. /// This is independent of the legacy locking-read mitigation. @@ -57,8 +75,8 @@ public MsSqlDialect(bool useReadCommittedLockForCommitReads, bool enableSafeChec _useReadCommittedLockForCommitReads = useReadCommittedLockForCommitReads; if (enableSafeCheckpointPolling) { - // Batch the gate and insert on the existing transaction: no extra network round trip. - _safePersistCommit = AcquireCheckpointWriterLock + "\n" + MsSqlStatements.PersistCommits; + // Shared registrations let writers overlap and keep the lock and insert in one round trip. + _safePersistCommit = AcquireSharedWriterLock + "\n" + MsSqlStatements.PersistCommits; } } diff --git a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs index a8d3b06..89c8509 100644 --- a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs +++ b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.Async.cs @@ -426,6 +426,11 @@ private async Task ExecuteQueryAsync( scope?.Complete(); } + catch (OperationCanceledException) when (independentRead && cancellationToken.IsCancellationRequested) + { + // Let safe polling stop cleanly; disposal rolls back any held polling fence. + throw; + } catch (Exception e) { if (Logger.IsEnabled(LogLevel.Debug)) diff --git a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.SafePolling.cs b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.SafePolling.cs index 46717c2..25e9063 100644 --- a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.SafePolling.cs +++ b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.SafePolling.cs @@ -1,14 +1,12 @@ using System.Data; using System.Transactions; +using Microsoft.Data.SqlClient; using NEventStore.Persistence.Sql.SqlDialects; namespace NEventStore.Persistence.Sql { public partial class SqlPersistenceEngine { - // The writer gate makes every committed checkpoint a safe ceiling, even when IDs have gaps. - private const string GetSafeCheckpointTip = "SELECT ISNULL(MAX(CheckpointNumber), CONVERT(bigint, 0)) FROM Commits;"; - /// public bool SupportsSafeCheckpointPolling => GetType() == typeof(SqlPersistenceEngine) && _dialect is MsSqlDialect { SupportsSafeCheckpointPolling: true }; @@ -34,7 +32,18 @@ public Task ReadForPollingAsync(long afterCheckpoint, string? bucketId, IAsyncOb var adapter = BuildICommitAsyncObserverAdapter(observer, cancellationToken); return ExecuteQueryAsync(async (statement, records, token) => { - var tip = (await statement.ExecuteScalarAsync(GetSafeCheckpointTip, token).ConfigureAwait(false)).ToLong(); + long tip; + try + { + tip = (await statement.ExecuteScalarAsync(MsSqlDialect.ReadCheckpointCeiling, token).ConfigureAwait(false)).ToLong(); + } + catch (SqlException error) when (token.IsCancellationRequested) + { + // SqlClient can report canceling a blocked application lock as a SQL error. + throw new OperationCanceledException("Waiting for the checkpoint fence was canceled.", error, token); + } + + token.ThrowIfCancellationRequested(); if (tip <= afterCheckpoint) { // An idle poll needs only the indexed ceiling lookup. @@ -55,7 +64,7 @@ private IEnumerable ReadSafeCheckpointWindow(long afterCheckpoint, stri EnsureIndependentSafePolling(); var commits = ExecuteQuery(statement => { - var tip = statement.ExecuteScalar(GetSafeCheckpointTip).ToLong(); + var tip = statement.ExecuteScalar(MsSqlDialect.ReadCheckpointCeiling).ToLong(); if (tip <= afterCheckpoint) { // No page enumerator will own these resources when the window is empty. From 131b9a91d6a0f932e9e745f9d9e3cc0f482ab9dd Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 18:18:54 +0100 Subject: [PATCH 6/7] Test safe checkpoint polling with derived SQL Server dialects Co-authored-by: Codex --- .../SafeCheckpointPollingTests.cs | 71 +++++++++++++++++-- 1 file changed, 66 insertions(+), 5 deletions(-) diff --git a/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs b/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs index 38dec81..f50fa46 100644 --- a/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs +++ b/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs @@ -1,7 +1,10 @@ #if NUNIT using System.Collections.Concurrent; using System.Diagnostics; +using System.Data; +using System.Data.Common; using System.Transactions; +using IsolationLevel = System.Transactions.IsolationLevel; using Microsoft.Data.SqlClient; using NEventStore.Persistence.AcceptanceTests; using NEventStore.Persistence.Sql; @@ -69,13 +72,18 @@ await WithDatabase(true, async settings => [TestCase(false, true, false, true)] [TestCase(false, false, false, false)] [TestCase(false, true, true, false)] + [TestCase(true, false, false, true, true)] + [TestCase(true, true, true, true, true)] + [TestCase(true, false, true, false, true)] + [TestCase(false, true, false, false, true)] public async Task Safe_polling_resumes_without_missing_commits_or_stalling_at_rollback_gaps( - bool rcsi, bool useAsync, bool scoped, bool commitLower) + bool rcsi, bool useAsync, bool scoped, bool commitLower, bool derived = false) { await WithDatabase(rcsi, async settings => { - var dialect = new MsSqlDialect(useReadCommittedLockForCommitReads: false, enableSafeCheckpointPolling: true); + var dialect = derived ? new DateTimeDialect() : new MsSqlDialect(false, true); using var reader = Open(settings, dialect); + Assert.That(((ISafeCheckpointPolling)reader).SupportsSafeCheckpointPolling, Is.True); reader.Initialize(); var seed = await Write(reader, "seed", useAsync); var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -254,10 +262,8 @@ private sealed class ImmediateLockTimeoutDialect() : MsSqlDialect(false, true) public void Safe_mode_rejects_disabled_or_unqualified_dialects_and_ambient_reads() { using var legacy = Open("Server=unused", new MsSqlDialect()); - using var derived = Open("Server=unused", new DerivedDialect()); var legacyReader = (ISafeCheckpointPolling)legacy; Assert.That(legacyReader.SupportsSafeCheckpointPolling, Is.False); - Assert.That(((ISafeCheckpointPolling)derived).SupportsSafeCheckpointPolling, Is.False); Assert.Throws(() => legacyReader.ReadForPolling(0, null)); using var engine = Open("Server=unused", new MsSqlDialect(false, true)); @@ -270,7 +276,62 @@ public void Safe_mode_rejects_disabled_or_unqualified_dialects_and_ambient_reads Assert.Throws(() => reader.ReadForPollingAsync(0, null, Collect([]))); } - private sealed class DerivedDialect() : MsSqlDialect(false, true); + [Test] + public void Derived_dialect_inherits_safe_polling_only_when_it_opts_in() + { + using var optedIn = Open("Server=unused", new DerivedDialect(true)); + using var legacy = Open("Server=unused", new DerivedDialect(false)); + Assert.That(((ISafeCheckpointPolling)optedIn).SupportsSafeCheckpointPolling, Is.True); + Assert.That(((ISafeCheckpointPolling)legacy).SupportsSafeCheckpointPolling, Is.False); + } + + [Test] + public void Derived_dialects_cannot_advertise_safe_polling_when_replacing_protocol_hooks() + { + MsSqlDialect[] dialects = [new ImmediateLockTimeoutDialect(), new ExplicitPersistDialect(), + new TransactionDialect(), new StatementDialect(), new OffsetDialect(), new NonPagingDialect()]; + foreach (var dialect in dialects) + { + using var engine = Open("Server=unused", dialect); + var reader = (ISafeCheckpointPolling)engine; + Assert.That(reader.SupportsSafeCheckpointPolling, Is.False, dialect.GetType().Name); + Assert.Throws(() => reader.ReadForPolling(0, null)); + Assert.Throws(() => reader.ReadForPollingAsync(0, null, Collect([]))); + } + } + + private class DerivedDialect(bool enabled) : MsSqlDialect(false, enabled); + + private sealed class DateTimeDialect() : DerivedDialect(true) + { + public override DateTime ToDateTime(object value) => base.ToDateTime(value).ToUniversalTime(); + } + + private sealed class ExplicitPersistDialect() : DerivedDialect(true), ISqlDialect + { + string ISqlDialect.PersistCommit => new MsSqlDialect().PersistCommit; + } + + private sealed class TransactionDialect() : DerivedDialect(true) + { + public override DbTransaction? OpenTransaction(DbConnection connection) => null; + } + + private sealed class StatementDialect() : DerivedDialect(true) + { + public override IDbStatement BuildStatement(TransactionScope? scope, ConnectionScope connection, + DbTransaction? transaction) => throw new NotImplementedException(); + } + + private sealed class OffsetDialect() : DerivedDialect(true) + { + protected override string? GetCheckpointKeysetQuery(bool scoped, bool bounded, int pageSize) => null; + } + + private sealed class NonPagingDialect() : DerivedDialect(true) + { + public override bool CanPage => false; + } private static Task HoldLowerWrite(string settings, MsSqlDialect dialect, bool useAsync, TaskCompletionSource ready, TaskCompletionSource release) => Task.Run(async () => From 979118a752be2ac8bb8a73644638c6456ae150ee Mon Sep 17 00:00:00 2001 From: Alessandro Giorgetti Date: Thu, 3 Dec 2026 18:19:02 +0100 Subject: [PATCH 7/7] Qualify derived SQL Server dialects that retain safe polling protocol Co-authored-by: Codex --- docs/SqlServer-Safe-Checkpoint-Polling.md | 33 ++++++++++++++-- .../SqlDialects/MsSqlDialect.cs | 38 +++++++++++++++++-- .../SqlPersistenceEngine.SafePolling.cs | 2 +- 3 files changed, 65 insertions(+), 8 deletions(-) diff --git a/docs/SqlServer-Safe-Checkpoint-Polling.md b/docs/SqlServer-Safe-Checkpoint-Polling.md index 2498528..b6413b4 100644 --- a/docs/SqlServer-Safe-Checkpoint-Polling.md +++ b/docs/SqlServer-Safe-Checkpoint-Polling.md @@ -1,6 +1,6 @@ # Safe checkpoint polling on SQL Server -Safe polling is opt-in. Enable it on the stock SQL Server dialect used by **every +Safe polling is opt-in. Enable it on the qualified SQL Server dialect used by **every writer** targeting the same `Commits` table, and on the persistence engine used by the poller: @@ -19,6 +19,30 @@ checkpoint only after successfully handling the commit. This does not make projection processing exactly-once. Verify or rewind existing projection positions if legacy polling may already have missed commits. +## Derived SQL Server dialects + +A subclass of `MsSqlDialect` can opt in by passing +`enableSafeCheckpointPolling: true` to the base constructor. A subclass that +inherits the stock protocol needs no other change. Date/time type or conversion +overrides are also allowed: + +```csharp +public sealed class ApplicationSqlDialect() + : MsSqlDialect(useReadCommittedLockForCommitReads: false, enableSafeCheckpointPolling: true) +{ + public override System.Data.DbType GetDateTimeDbType() => System.Data.DbType.DateTime2; +} +``` + +Qualification is conservative. Replacing SQL or transaction, statement, or +paging behavior (including an explicit `ISqlDialect` implementation, or an +override of `GetCheckpointKeysetQuery`) does not qualify, even if an override +calls the base method. The provider cannot verify custom SQL keeps the +writer registration, checkpoint ceiling, order, and scope. The check runs +once when an opted-in dialect is constructed; it does not run per append or +poll. Unqualified dialects keep their existing legacy paths, while requesting +safe polling fails instead of silently using those paths. + ## How it works Writers take a **shared**, transaction-owned lock before SQL Server generates @@ -52,9 +76,10 @@ legacy locking-read option from #31 is not needed for this protocol. transactions. The provider rejects an ambient reader rather than exposing its own uncommitted writes. Ambient *writers* continue to use normal transaction enlistment; the gate follows the enlistment. -- This qualification targets the built-in engine and `MsSqlDialect` on - SQL Server 2022 using the stock `Commits` layout. Custom engine or dialect - subclasses, other SQL engines, and Azure SQL are not qualified by this change. +- This qualification targets the built-in engine, `MsSqlDialect`, and the + compatible subclasses described above on SQL Server 2022 using the stock + `Commits` layout. Custom engines, other SQL engines, and Azure SQL are not + qualified by this change. - No schema migration or new checkpoint column is required. Do not reuse a saved checkpoint across `Purge`, `Drop`, identity resets, or recovery that loses commits already seen by a poller. diff --git a/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs b/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs index 7209688..828989f 100644 --- a/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs +++ b/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs @@ -68,7 +68,9 @@ public MsSqlDialect(bool useReadCommittedLockForCommitReads) /// Whether to register in-flight writes until commit or rollback for safe polling. /// /// Every writer targeting the same commits table must use the safe-polling configuration. - /// This is independent of the legacy locking-read mitigation. + /// Derived dialects can opt in if they inherit the SQL, execution and paging hooks. + /// Date/time conversion and parameter type overrides are supported. This setting is + /// independent of the legacy locking-read mitigation. /// public MsSqlDialect(bool useReadCommittedLockForCommitReads, bool enableSafeCheckpointPolling) { @@ -77,11 +79,41 @@ public MsSqlDialect(bool useReadCommittedLockForCommitReads, bool enableSafeChec { // Shared registrations let writers overlap and keep the lock and insert in one round trip. _safePersistCommit = AcquireSharedWriterLock + "\n" + MsSqlStatements.PersistCommits; + SupportsSafeCheckpointPolling = HasStockCheckpointProtocol(); } } - /// Gets whether this built-in dialect uses the qualified writer protocol. - internal bool SupportsSafeCheckpointPolling => _safePersistCommit != null && GetType() == typeof(MsSqlDialect); + /// Gets whether safe polling is enabled with the qualified SQL Server protocol. + internal bool SupportsSafeCheckpointPolling { get; } + + /// Checks that a derived dialect still dispatches to the qualified implementation. + /// Whether both the writer registration and the safe reader retain stock behavior. + private bool HasStockCheckpointProtocol() + { + var type = GetType(); + if (type == typeof(MsSqlDialect)) + return true; + + // Check the effective interface targets, not just virtual overrides: a subclass can + // explicitly reimplement ISqlDialect and bypass the stock insert or statement. + var stock = typeof(MsSqlDialect).GetInterfaceMap(typeof(ISqlDialect)); + var derived = type.GetInterfaceMap(typeof(ISqlDialect)); + for (int i = 0; i < derived.InterfaceMethods.Length; i++) + { + var member = derived.InterfaceMethods[i]; + if (member.Name is nameof(ToDateTime) or nameof(GetDateTimeDbType)) + continue; + + int stockIndex = Array.IndexOf(stock.InterfaceMethods, member); + if (!derived.TargetMethods[i].MethodHandle.Equals(stock.TargetMethods[stockIndex].MethodHandle)) + return false; + } + + // The protected seek hook is not on the interface. An override can drop the + // ceiling or fall back to offset paging, so it cannot claim safe polling. + return ((Func)GetCheckpointKeysetQuery).Method.DeclaringType + == typeof(CommonSqlDialect); + } /// public override string InitializeStorage diff --git a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.SafePolling.cs b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.SafePolling.cs index 25e9063..45174c4 100644 --- a/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.SafePolling.cs +++ b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.SafePolling.cs @@ -94,7 +94,7 @@ private void BindSafeCheckpointWindow(IDbStatement statement, long afterCheckpoi private void EnsureIndependentSafePolling() { if (!SupportsSafeCheckpointPolling) - throw new NotSupportedException("Safe checkpoint polling requires the built-in SQL Server engine and dialect with safe polling enabled."); + throw new NotSupportedException("Safe checkpoint polling requires the built-in SQL engine and an opted-in SQL Server dialect that inherits the stock checkpoint protocol."); // An enlisted reader could otherwise publish its own uncommitted checkpoint. if (Transaction.Current != null)