← 输入框|github.com|刷新
Skip to content
Merged
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
8 changes: 8 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,16 @@

## Unreleased

- Use ordered keyset paging for checkpoint reads on SQL Server, PostgreSQL, MySQL, Oracle, and SQLite. A deletion before the next page no longer shifts it, and zero page size reads without a page limit. Keep the existing behavior for non-checkpoint reads. No schema change. [#63](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/63)

- Add an opt-in SQL Server and Azure SQL mitigation for commit readers under `READ_COMMITTED_SNAPSHOT`. Choose `WithDialect(new MsSqlDialect(useReadCommittedLockForCommitReads: true))` to request locking for open-ended and bounded checkpoint reads, date-based reads, and stream revision reads. These reads can wait for an uncommitted insert; this does not guarantee checkpoint publication order. Default behavior, write and snapshot queries, and the schema are unchanged. [#31](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/31)

### Breaking Changes

- **Derived SQL dialects and checkpoint overrides (#63).** Keyset paging is now the default for subclasses of built-in SQL dialects that use the built-in statement executor. It **does not call** the old virtual checkpoint SQL properties, so filters, joins, or hints in those overrides will no longer be applied even though the subclass still compiles.
- Move the customization to `GetCheckpointKeysetQuery(bool scoped, bool bounded, int pageSize)` to use keyset paging, or return `null` for the affected shapes to keep the previous SQL and offset paging.
- Independent `ISqlDialect` implementations, dialects that disable paging, and separate custom statement wrappers retain their existing behavior. See the [migration guide and examples](docs/Checkpoint-Seek-Paging.md#upgrading-a-derived-dialect).

## 10.2.0

- Added explicit support for net8.0,net9.0,net10.0
Expand Down
199 changes: 199 additions & 0 deletions docs/Checkpoint-Seek-Paging.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
# Checkpoint seek paging

The built-in SQL Server, PostgreSQL, MySQL, Oracle, and SQLite dialects read the
next page with `CheckpointNumber > last returned checkpoint`, ordered by
checkpoint. Bucket filters and inclusive upper bounds are carried across
pages. `PageSize = 0` sends one ordered query with no page limit.

This changes only checkpoint reads. Seek paging
does not make a late lower checkpoint visible before a higher one, does not
provide snapshot isolation across pages, and does not restore already deleted
commits. Ordered publication is tracked in [#72](https://github.com/NEventStore/NEventStore.Persistence.SQL/issues/72).

## Upgrading a derived dialect

**Breaking change:** subclasses of the built-in SQL Server, PostgreSQL, MySQL,
Oracle, and SQLite dialects inherit keyset paging when they use the built-in
statement executor. Keyset paging bypasses the four old virtual checkpoint SQL
properties. If one of your overrides adds a filter, join, or hint, migrate it to
the new hook or return `null` to keep that query on offset paging. Otherwise its
customization will no longer be applied, even though your subclass still compiles.

### 1. Inherit keyset paging without changing your queries

If your subclass only customizes unrelated behavior, leave the checkpoint hook
alone. The new keyset paging is inherited. This example keeps the SQL Server
read-locking option explicit:

```csharp
using NEventStore.Persistence.Sql.SqlDialects;

public sealed class ApplicationSqlDialect : MsSqlDialect
{
public ApplicationSqlDialect(bool useCommitReadLocking = false)
: base(useReadCommittedLockForCommitReads: useCommitReadLocking)
{
}
}
```

Register the subclass as before, for example
`.WithDialect(new ApplicationSqlDialect())` on your SQL persistence wireup.

### 2. Keep existing offset SQL

If you need to preserve several legacy checkpoint SQL overrides for now, add
the following override to your existing dialect. It makes all four checkpoint
query shapes use the old virtual properties and offset paging:

```csharp
using NEventStore.Persistence.Sql.SqlDialects;

public class CompatibilitySqlDialect : MsSqlDialect
{
// Keep any existing GetCommitsFrom...Checkpoint overrides in this class.
protected override string? GetCheckpointKeysetQuery(
bool scoped, bool bounded, int pageSize) => null;
}
```

You can also opt out for only the shape whose SQL you haven't migrated. This
example keeps a custom global, open-ended feed on offset paging, while other
checkpoint reads still use keyset paging:

```csharp
using NEventStore.Persistence.Sql.SqlDialects;

public sealed class LegacyGlobalFeedDialect : MsSqlDialect
{
public override string GetCommitsFromCheckpoint =>
base.GetCommitsFromCheckpoint.Replace(
"FROM Commits", "FROM Commits WITH (READCOMMITTEDLOCK)");

protected override string? GetCheckpointKeysetQuery(
bool scoped, bool bounded, int pageSize) =>
!scoped && !bounded
? null
: base.GetCheckpointKeysetQuery(scoped, bounded, pageSize);
}
```

The two flags correspond to these public read methods, including their async equivalents:

| `scoped` | `bounded` | Checkpoint read | Legacy SQL property |
| --- | --- | --- | --- |
| `false` | `false` | `GetFrom(after)` | `GetCommitsFromCheckpoint` |
| `true` | `false` | `GetFrom(bucket, after)` | `GetCommitsFromBucketAndCheckpoint` |
| `false` | `true` | `GetFromTo(after, upper)` | `GetCommitsFromToCheckpoint` |
| `true` | `true` | `GetFromTo(bucket, after, upper)` | `GetCommitsFromToBucketAndCheckpoint` |

### 3. Carry a custom filter into the built-in keyset query

If the change is small, call the base hook and adapt its SQL. This example
excludes the fixed `maintenance` bucket from global feeds without changing
bucket-scoped reads. The built-in query retains its bounds, ordering, page limit,
and any configured SQL Server read-locking hint:

```csharp
using System;
using NEventStore.Persistence.Sql.SqlDialects;

public sealed class ApplicationFeedDialect : MsSqlDialect
{
protected override string? GetCheckpointKeysetQuery(
bool scoped, bool bounded, int pageSize)
{
var sql = base.GetCheckpointKeysetQuery(scoped, bounded, pageSize);
if (scoped || sql is null)
return sql;

const string where = "WHERE ";
int index = sql.IndexOf(where, StringComparison.Ordinal);
if (index < 0)
throw new InvalidOperationException("The checkpoint query has no WHERE clause.");

// This is a fixed application filter, not interpolated user input.
return sql.Insert(index + where.Length, "BucketId <> 'maintenance' AND ");
}
}
```

This rewrite is specific to the built-in SQL Server query shape. Test it if
you upgrade the provider or change the base dialect.

### 4. Supply a complete keyset query

For a larger change, return your own SQL. This example supplies both global
query shapes and delegates bucket-scoped reads to the built-in query:

```csharp
using NEventStore.Persistence.Sql.SqlDialects;

public sealed class CustomGlobalFeedDialect : MsSqlDialect
{
protected override string? GetCheckpointKeysetQuery(
bool scoped, bool bounded, int pageSize)
{
if (scoped)
return base.GetCheckpointKeysetQuery(scoped, bounded, pageSize);

var lower = bounded ? FromCheckpointNumber : CheckpointNumber;
var upper = bounded ? $" AND CheckpointNumber <= {ToCheckpointNumber}" : "";
var top = pageSize > 0 ? $"TOP ({Limit}) " : "";

return $"""
SELECT {top}BucketId, StreamId, StreamIdOriginal, StreamRevision,
CommitId, CommitSequence, CommitStamp, CheckpointNumber, Headers, Payload
FROM Commits
WHERE CheckpointNumber > {lower}{upper}
AND BucketId <> 'maintenance'
ORDER BY CheckpointNumber
""";
}
}
```

A complete query must:

- Return the standard commit columns in their existing order, including
`CheckpointNumber`, and return each matching checkpoint only once.
- Use the active lower-bound parameter with `>`, preserve the bucket predicate
for scoped reads and `<= ToCheckpointNumber` for bounded reads, and order by
checkpoint ascending.
- Use the dialect's `Limit` parameter only when `pageSize > 0`. Do not use
`Skip` or introduce other parameters that the statement does not bind.
- Explicitly include any provider-specific hints your custom query needs.
Returning complete SQL does not automatically add the SQL Server read-locking
hint. Call the base hook if you want to retain its configured hint.

After migrating, exercise sync and async reads, a range spanning multiple
pages, and `PageSize = 0`. Check the expected checkpoints in order and verify
that any filter, hint, or join from your old override is still in effect.

Subclasses that disable paging, independent `ISqlDialect` implementations,
and custom statement wrappers that don't use the built-in executor keep their
existing paging behavior; the new keyset hook is not used for those reads.

## Large catch-up comparison

1. Start the database services using [the Docker instructions](../docker/Readme.md)
or mirror the images and connection settings used by
[the CI workflow](../.github/workflows/ci.yml). SQLite uses a local file.
Use disposable stores and the same schema and indexes in both runs.
2. Seed at least 500,000 commits with identical payloads and checkpoints
distributed across multiple buckets. Keep the fixture read-only during
the performance comparison. Compare the parent revision (offset) with the
candidate (seek), on the same connection settings and runtime.
3. For each revision, read the same open-ended and bounded windows, globally
and for a quiet bucket, with page sizes 128 and 512. Test both a full
catch-up and deep pages after at least 400,000 global checkpoints.
Verify that returned checkpoints match in order before comparing timings.
4. Warm up each query shape, alternate the order of baseline and candidate,
and record at least 20 timings. Report total catch-up time, median and
p95 deep-page latency, and where available execution-plan rows examined
or logical reads. Don't compare the default offset against a seek on a
different index or with different result counts.
5. Check correctness separately: delete an already returned row between
pages. The next surviving commit must still be returned. This scenario
is covered by the SQLite WAL regression and is not part of the timing
sample.
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.Transactions.cs" Link="PersistenceTests.Transactions.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.Transactions.Async.cs" Link="PersistenceTests.Transactions.Async.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.InfinitePageSize.Async.cs" Link="PersistenceTests.InfinitePageSize.Async.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.CheckpointPaging.cs" Link="PersistenceTests.CheckpointPaging.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.Snapshots.cs" Link="PersistenceTests.Snapshots.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.Snapshots.Async.cs" Link="PersistenceTests.Snapshots.Async.cs" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
<Compile Include="..\..\dependencies\NEventStore\src\NEventStore.Persistence.AcceptanceTests\PersistenceTests.cs" Link="PersistenceTests.cs" />
<Compile Include="..\..\dependencies\NEventStore\src\NEventStore.Persistence.AcceptanceTests\PersistenceTests.Async.cs" Link="PersistenceTests.Async.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.InfinitePageSize.Async.cs" Link="PersistenceTests.InfinitePageSize.Async.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.CheckpointPaging.cs" Link="PersistenceTests.CheckpointPaging.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.Snapshots.cs" Link="PersistenceTests.Snapshots.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.Snapshots.Async.cs" Link="PersistenceTests.Snapshots.Async.cs" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
<Compile Include="..\..\dependencies\NEventStore\src\NEventStore.Persistence.AcceptanceTests\PersistenceTests.cs" Link="PersistenceTests.cs" />
<Compile Include="..\..\dependencies\NEventStore\src\NEventStore.Persistence.AcceptanceTests\PersistenceTests.Async.cs" Link="PersistenceTests.Async.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.InfinitePageSize.Async.cs" Link="PersistenceTests.InfinitePageSize.Async.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.CheckpointPaging.cs" Link="PersistenceTests.CheckpointPaging.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.Snapshots.cs" Link="PersistenceTests.Snapshots.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.Snapshots.Async.cs" Link="PersistenceTests.Snapshots.Async.cs" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
<Compile Include="..\..\dependencies\NEventStore\src\NEventStore.Persistence.AcceptanceTests\PersistenceTests.cs" Link="PersistenceTests.cs" />
<Compile Include="..\..\dependencies\NEventStore\src\NEventStore.Persistence.AcceptanceTests\PersistenceTests.Async.cs" Link="PersistenceTests.Async.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.InfinitePageSize.Async.cs" Link="PersistenceTests.InfinitePageSize.Async.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.CheckpointPaging.cs" Link="PersistenceTests.CheckpointPaging.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.Snapshots.cs" Link="PersistenceTests.Snapshots.cs" />
<Compile Include="..\NEventStore.Persistence.Sql.Tests\PersistenceTests.Snapshots.Async.cs" Link="PersistenceTests.Snapshots.Async.cs" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<Compile Remove="PersistenceTests.Transactions.Async.cs" />
<Compile Remove="PersistenceTests.Transactions.cs" />
<Compile Remove="PersistenceTests.InfinitePageSize.Async.cs" />
<Compile Remove="PersistenceTests.CheckpointPaging.cs" />
<Compile Remove="PersistenceTests.Snapshots.Async.cs" />
<Compile Remove="PersistenceTests.Snapshots.cs" />
</ItemGroup>
Expand All @@ -23,6 +24,7 @@
<None Include="PersistenceTests.Transactions.Async.cs" />
<None Include="PersistenceTests.Transactions.cs" />
<None Include="PersistenceTests.InfinitePageSize.Async.cs" />
<None Include="PersistenceTests.CheckpointPaging.cs" />
<None Include="PersistenceTests.Snapshots.Async.cs" />
<None Include="PersistenceTests.Snapshots.cs" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
#if NUNIT
using FluentAssertions;
using NUnit.Framework;

namespace NEventStore.Persistence.AcceptanceTests;

[TestFixture]
[NonParallelizable]
public sealed class CheckpointPagingTests
{
private const string SelectedBucket = "paging-a";
private const string OtherBucket = "paging-b";

[TestCase(2, false)]
[TestCase(2, true)]
[TestCase(0, false)]
[TestCase(0, true)]
public async Task Checkpoint_reads_preserve_order_scope_gaps_and_range_bounds(int pageSize, bool useAsync)
{
using var fixture = new PersistenceEngineFixture();
fixture.Initialize(pageSize);
var engine = fixture.Persistence!;
using var referenceReader = fixture.CreateCheckpointReferenceReader();
ICommit Write(string name, string bucket)
{
engine.Commit(name.BuildAttempt(bucketId: bucket)).Should().NotBeNull();
// Oracle's existing write result does not report the assigned checkpoint.
// Use a separate, paged stream reader so the expected value is independent of the tested query.
return referenceReader.GetFrom(bucket, name, 1, 1).Single();
}

var start = Write("start", SelectedBucket);
var b1 = Write("b1", OtherBucket);
var a1 = Write("a1", SelectedBucket);
var gap = Write("gap", SelectedBucket);
var b2 = Write("b2", OtherBucket);
var a2 = Write("a2", SelectedBucket);
var b3 = Write("b3", OtherBucket);
var a3 = Write("a3", SelectedBucket);
var a4 = Write("a4", SelectedBucket);
engine.DeleteStream(gap.BucketId, gap.StreamId);

var after = start.CheckpointToken;
var upper = a3.CheckpointToken;
(await ReadAsync(engine, after, useAsync: useAsync))
.Should().Equal(b1.CheckpointToken, a1.CheckpointToken, b2.CheckpointToken, a2.CheckpointToken, b3.CheckpointToken, upper, a4.CheckpointToken);
(await ReadAsync(engine, after, bucket: SelectedBucket, useAsync: useAsync))
.Should().Equal(a1.CheckpointToken, a2.CheckpointToken, upper, a4.CheckpointToken);
(await ReadAsync(engine, after, upper: upper, useAsync: useAsync))
.Should().Equal(b1.CheckpointToken, a1.CheckpointToken, b2.CheckpointToken, a2.CheckpointToken, b3.CheckpointToken, upper);
(await ReadAsync(engine, after, upper: upper, bucket: SelectedBucket, useAsync: useAsync))
.Should().Equal(a1.CheckpointToken, a2.CheckpointToken, upper);
(await ReadAsync(engine, upper, upper: upper, bucket: SelectedBucket, useAsync: useAsync))
.Should().BeEmpty();
}

internal static async Task<long[]> ReadAsync(IPersistStreams engine, long after, long? upper = null,
string? bucket = null, bool useAsync = false, Action<ICommit>? onRead = null)
{
var result = new List<long>();
void Record(ICommit commit)
{
result.Add(commit.CheckpointToken);
onRead?.Invoke(commit);
}

if (!useAsync)
{
var commits = (bucket, upper) switch
{
(null, null) => engine.GetFrom(after),
(null, long end) => engine.GetFromTo(after, end),
(string id, null) => engine.GetFrom(id, after),
(string id, long end) => engine.GetFromTo(id, after, end)
};
foreach (var commit in commits) Record(commit);
return result.ToArray();
}

using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));
var observer = new LambdaAsyncObserver<ICommit>((commit, _) =>
{
Record(commit);
return Task.FromResult(true);
}, (error, _) => Task.FromException(error));
await ((bucket, upper) switch
{
(null, null) => engine.GetFromAsync(after, observer, timeout.Token),
(null, long end) => engine.GetFromToAsync(after, end, observer, timeout.Token),
(string id, null) => engine.GetFromAsync(id, after, observer, timeout.Token),
(string id, long end) => engine.GetFromToAsync(id, after, end, observer, timeout.Token)
});
return result.ToArray();
}
}
public partial class PersistenceEngineFixture
{
// Use the initialized fixture's store without owning its schema or changing the tested page size.
internal IPersistStreams CreateCheckpointReferenceReader() => _createPersistence(2);
}
#endif
Loading
Loading