diff --git a/Changelog.md b/Changelog.md index fce59a4..3b7582c 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 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) - 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/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/docs/SqlServer-Safe-Checkpoint-Polling.md b/docs/SqlServer-Safe-Checkpoint-Polling.md new file mode 100644 index 0000000..b6413b4 --- /dev/null +++ b/docs/SqlServer-Safe-Checkpoint-Polling.md @@ -0,0 +1,134 @@ +# Safe checkpoint polling on SQL Server + +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: + +```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. + +## 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 +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 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 + transaction enlistment; the gate follows the enlistment. +- 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. + +## Performance trade-off + +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/NEventStore.Persistence.MsSql.Core.Tests.csproj b/src/NEventStore.Persistence.MsSql.Tests/NEventStore.Persistence.MsSql.Core.Tests.csproj index b3af844..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 @@ -21,8 +21,8 @@ - - + + @@ -30,6 +30,7 @@ + diff --git a/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs b/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs new file mode 100644 index 0000000..f50fa46 --- /dev/null +++ b/src/NEventStore.Persistence.MsSql.Tests/SafeCheckpointPollingTests.cs @@ -0,0 +1,482 @@ +#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; +using NEventStore.PollingClient; +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 Legacy_polling_can_miss_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 = HoldLowerWrite(settings, new MsSqlDialect(), useAsync, ready, release); + 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(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)] + [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 derived = false) + { + await WithDatabase(rcsi, async settings => + { + 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); + 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; + Task? pendingPoll = null; + long lower; + long higher; + 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"); + }); + 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; + 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; + } + + 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); + 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 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() + { + 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 })); + }); + } + + [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() + { + using var legacy = Open("Server=unused", new MsSqlDialect()); + var legacyReader = (ISafeCheckpointPolling)legacy; + Assert.That(legacyReader.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([]))); + } + + [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 () => + { + 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 AssertReaderFenceIsWaiting(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 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) + { + 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 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, string? bucket = Bucket) + { + if (!useAsync) + return (bucket == null ? engine.GetFrom(after) : engine.GetFrom(bucket, after)) + .Select(c => c.CheckpointToken).ToArray(); + var results = new List(); + if (bucket == null) await engine.GetFromAsync(after, Collect(results), CancellationToken.None); + else 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.Sql/SqlDialects/MsSqlDialect.cs b/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs index b6ba0f0..828989f 100644 --- a/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs +++ b/src/NEventStore.Persistence.Sql/SqlDialects/MsSqlDialect.cs @@ -13,7 +13,37 @@ public class MsSqlDialect : CommonSqlDialect private const int UniqueIndexViolation = 2601; private const int UniqueKeyViolation = 2627; private readonly bool _useReadCommittedLockForCommitReads; + private readonly string? _safePersistCommit; + // 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'{CheckpointLockResource}', + @LockMode = N'{mode}', @LockOwner = N'Transaction', + @DbPrincipal = N'public'; + IF @checkpointLockResult < 0 + THROW 51072, 'Could not acquire the NEventStore checkpoint lock.', 1; + """; /// Initializes the dialect with unchanged database read semantics. public MsSqlDialect() : this(false) { @@ -29,8 +59,60 @@ 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 checkpoint fencing. + /// Whether to request the legacy locking-read mitigation. + /// 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. + /// 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) { _useReadCommittedLockForCommitReads = useReadCommittedLockForCommitReads; + if (enableSafeCheckpointPolling) + { + // Shared registrations let writers overlap and keep the lock and insert in one round trip. + _safePersistCommit = AcquireSharedWriterLock + "\n" + MsSqlStatements.PersistCommits; + SupportsSafeCheckpointPolling = HasStockCheckpointProtocol(); + } + } + + /// 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); } /// @@ -61,7 +143,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..89c8509 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)) @@ -418,6 +426,11 @@ protected virtual 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 new file mode 100644 index 0000000..45174c4 --- /dev/null +++ b/src/NEventStore.Persistence.Sql/SqlPersistenceEngine.SafePolling.cs @@ -0,0 +1,104 @@ +using System.Data; +using System.Transactions; +using Microsoft.Data.SqlClient; +using NEventStore.Persistence.Sql.SqlDialects; + +namespace NEventStore.Persistence.Sql +{ + public partial class SqlPersistenceEngine + { + /// + 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) => + { + 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. + 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(MsSqlDialect.ReadCheckpointCeiling).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 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) + 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; 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 @@ - - + +