← 输入框|github.com|刷新
Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion dependencies/NEventStore
Submodule NEventStore updated 29 files
+12 −0 Changelog.md
+3 −3 src/NEventStore.Persistence.AcceptanceTests/NEventStore.Persistence.AcceptanceTests.Core.csproj
+50 −0 src/NEventStore.Persistence.AcceptanceTests/SafeCheckpointPollingContract.cs
+58 −35 src/NEventStore.PollingClient/AsyncPollingClient.cs
+1 −1 src/NEventStore.PollingClient/NEventStore.PollingClient.csproj
+35 −15 src/NEventStore.PollingClient/PollingClient2.cs
+29 −0 src/NEventStore.PollingClient/README.MD
+17 −0 src/NEventStore.PollingClient/SafePolling.cs
+5 −5 src/NEventStore.Serialization.Binary.Tests/NEventStore.Serialization.Binary.Core.Tests.csproj
+1 −1 src/NEventStore.Serialization.Binary/NEventStore.Serialization.Binary.Core.csproj
+5 −5 src/NEventStore.Serialization.Bson.Tests/NEventStore.Serialization.Bson.Core.Tests.csproj
+1 −1 src/NEventStore.Serialization.Bson/NEventStore.Serialization.Bson.Core.csproj
+5 −5 src/NEventStore.Serialization.Gzip.Tests/NEventStore.Serialization.GZip.Core.Tests.csproj
+5 −5 src/NEventStore.Serialization.Json.Tests/NEventStore.Serialization.Json.Core.Tests.csproj
+1 −1 src/NEventStore.Serialization.Json/NEventStore.Serialization.Json.Core.csproj
+5 −5 src/NEventStore.Serialization.MsgPack.Tests/NEventStore.Serialization.MsgPack.Core.Tests.csproj
+2 −2 src/NEventStore.Serialization.MsgPack/NEventStore.Serialization.MsgPack.Core.csproj
+5 −5 src/NEventStore.Serialization.Rijndael.Tests/NEventStore.Serialization.Rijndael.Core.Tests.csproj
+5 −5 src/NEventStore.Serialization.SystemTextJson.Tests/NEventStore.Serialization.SystemTextJson.Core.Tests.csproj
+1 −1 src/NEventStore.Serialization.SystemTextJson/NEventStore.Serialization.SystemTextJson.Core.csproj
+211 −0 src/NEventStore.Tests/Client/SafePollingClientTests.cs
+7 −8 src/NEventStore.Tests/NEventStore.Core.Tests.csproj
+69 −0 src/NEventStore.Tests/Persistence/InMemory/SafeCheckpointPollingTests.cs
+20 −1 src/NEventStore/Diagnostics/PerformanceCounterPersistenceEngine.cs
+1 −1 src/NEventStore/NEventStore.Core.csproj
+1 −1 src/NEventStore/OptimisticEventStream.cs
+33 −0 src/NEventStore/Persistence/ISafeCheckpointPolling.cs
+160 −237 src/NEventStore/Persistence/InMemory/InMemoryPersistenceEngine.cs
+47 −3 src/NEventStore/Persistence/PipelineHooksAwarePersistStreamsDecorator.cs
134 changes: 134 additions & 0 deletions docs/SqlServer-Safe-Checkpoint-Polling.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,16 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="8.10.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.6.0" />
<PackageReference Include="NUnit" Version="4.6.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
<PackageReference Include="NUnit" Version="5.0.0" />
<PackageReference Include="NUnit3TestAdapter" Version="6.2.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\dependencies\NEventStore\src\NEventStore.Persistence.AcceptanceTests\NEventStore.Persistence.AcceptanceTests.Core.csproj" />
<ProjectReference Include="..\..\dependencies\NEventStore\src\NEventStore.Serialization.Binary\NEventStore.Serialization.Binary.Core.csproj" />
<ProjectReference Include="..\..\dependencies\NEventStore\src\NEventStore\NEventStore.Core.csproj" />
<ProjectReference Include="..\..\dependencies\NEventStore\src\NEventStore.PollingClient\NEventStore.PollingClient.csproj" />
<ProjectReference Include="..\NEventStore.Persistence.Sql.Tests\NEventStore.Persistence.Sql.Core.Tests.csproj" />
<ProjectReference Include="..\NEventStore.Persistence.Sql\NEventStore.Persistence.Sql.Core.csproj" />
</ItemGroup>
Expand Down
Loading
Loading