Skip to content

Add safe checkpoint polling across SQL dialects (#72) - #75

Open
AGiorgetti wants to merge 14 commits into
developfrom
fix/72-sql-server-safe-checkpoint-polling
Open

AGiorgetti wants to merge 14 commits into
developfrom
fix/72-sql-server-safe-checkpoint-polling

Conversation

@AGiorgetti

@AGiorgetti AGiorgetti commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

Scope

SQL provider implementation for #72 and NEventStore/NEventStore#425. This draft carries one commit per additional dialect after the SQL Server slice. Azure SQL verification remains deferred to #14.

SQL Server

  • Writers acquire a shared, transaction-owned application lock before the existing IDENTITY insert. Independent writers can allocate and commit concurrently, and the shared lock stays held through actual commit or rollback, including ambient transactions. Registration and insert still share one batch; no new transaction, schema, checkpoint or writer-side round trip.
  • A safe poll uses an exclusive checkpoint fence to wait for in-flight writers, capture a committed ceiling, and release the lock before paging or running handlers. Then it uses [Order 06][P2] Replace offset checkpoint paging with keyset paging #63's bounded keyset reads. Make MsSqlDialect compatible with AzureSql and READ COMMITTED SNAPSHOT #31's hint is not required. Requested cancellation while waiting is propagated without delivering a checkpoint.
  • Enable the protocol across all writers and safe readers of a store. Neither a legacy writer that bypasses it nor a reader from the earlier exclusive-writer draft is supported in a mixed deployment. See the SQL Server guide.

SQLite

Uses SQLite’s single writer and the provider-created AUTOINCREMENT schema. No writer-side change or gate. The safe poll checks the schema and dirty-read setting and captures the committed ceiling in one scalar query before the bounded seek. See the SQLite guide for proof, scope, and measured SQL timings.

PostgreSQL

Shared transaction-owned advisory locks register writers before BIGSERIAL allocation. The independent reader fences pending writers and qualifies the primary, table, and CACHE 1 sequence before bounding the seek. See the PostgreSQL guide for the all-writer cutover, the sequence cache regression, and prepared versus unprepared SQL timings.

MySQL/InnoDB

Opt-in initialization installs an InnoDB gate row. Writers use a shared lock in the existing insert command. A safe read takes an exclusive lock in a short independent READ COMMITTED transaction, releases it before paging, and validates the gate and AUTO_INCREMENT column. See the MySQL guide for all-writer cutover and measured overhead.

Oracle

The existing insert trigger allocates the checkpoint from an ordered sequence. An empty gate table provides shared writer registration and a short exclusive read fence. Both PL/SQL blocks return their checkpoint via a 64-bit output binding. See the Oracle guide for existing-store sequence migration, privileges, and transaction costs.

The guarded Oracle ceiling plus commit took 1.19–1.39 ms per call across three local server-only timing runs on 100,000 rows. Insert comparisons varied across trials and do not support a reliable overhead figure. This is not a network or end-to-end poll measurement.

SQL Server performance

Eight writers with a simulated 12 ms hold inside each ambient transaction and one active poller: 77 → 473 commits/s and 115 → 24 ms p95 append, comparing this protocol against the earlier exclusive-writer draft. p95 poll duration increased 4 → 18 ms. Without a poller, the same writer workload improved from 75 → 540 commits/s. Local SQL Server 2022/.NET 10, pooled loopback, three trials; not a production estimate. Frequent or waiting poll fences can still delay subsequent writes.

There is no additional transaction. An optimistic explicit-key allocator like MongoDB #118 is not a drop-in replacement for the existing SQL Server IDENTITY schema: it needs a durable floor against ID reuse, and same-key contenders would still wait on an uncommitted ambient writer.

Verification

  • Eight overlap regressions failed under the old exclusive-writer protocol and pass here. Tests prove that the higher writer can commit first and the safe poll does not expose it before the lower writer commits or rolls back. They cover both READ COMMITTED modes, sync and async, global and bucket polling, and fresh-reader resume through core PR #555's pollers.

  • 20 focused tests passed on SQL Server 2022 / .NET 10, including compatible derived dialects and rejection of overrides that bypass the protocol. All five CI jobs passed on the SQL Server slice.

  • 171 SQLite tests passed locally on .NET 10, including 14 focused regressions across both clients, WAL and rollback journals. The .NET Framework 4.7.2 SQLite test project compiles.

  • 154 PostgreSQL tests passed on PostgreSQL 15.18 / .NET 10, including both built-in dialect paths, derived dialect, commit/rollback, two-session sequence caching, and allocation ordering. The .NET Framework 4.7.2 PostgreSQL test project compiles.

  • 153 MySQL tests passed on MySQL 8.0.46 / .NET 10, including six focused cases for ambient commit/rollback, waiting before allocation, an existing database upgrade, invalid gates, and a 64-bit checkpoint. The .NET Framework 4.7.2 MySQL test project compiles.

  • 156 Oracle tests passed per runtime against Oracle XE, including six regressions for ambient completion, waiting before allocation, a 64-bit checkpoint, and existing-store qualification. Native XE checks also verified the writer overlap and the blocked fence.

  • The CI run before the terminology-only cleanup passed all five jobs: Linux and Windows builds and 927 tests each on .NET 8, 9 and 10, no failures or skips.

Release follow-up: Alessandro will handle the later core #555 repin. Before release, set the SQL NuGet dependency floor to a published core containing the contract and verify a package-only consumer.

Co-authored by Alessandro Giorgetti and Codex (OpenAI).

AGiorgetti and others added 5 commits December 3, 2026 16:40
Co-authored-by: Codex <codex@openai.com>
Co-authored-by: Codex <codex@openai.com>
Co-authored-by: Codex <codex@openai.com>
Co-authored-by: Codex <codex@openai.com>
Co-authored-by: Codex <codex@openai.com>

Copy link
Copy Markdown
Member Author

Why this PR uses shared writer locks and a short polling fence

The aim for #21 and the SQL Server part of #72 is to preserve the existing long checkpoint and prevent a safe poller from saving 102 while a lower matching commit at 101 can still become visible. Rollback and deletion gaps are fine; we do not wait for missing numbers to appear.

  • Writes stay concurrent. Each writer takes a shared, transaction-owned application lock for the database before the existing IDENTITY insert. The lock lasts through actual commit or rollback, including an enlisted outer transaction. Shared locks are compatible, so writers do not serialize behind one another. Registration and insert are in the same SQL batch and reuse the existing transaction: no new write round trip, transaction, schema, or cursor format.
  • The safe reader establishes the boundary. On an independent, non-ambient connection, it takes the exclusive lock, waits for in-flight writers to resolve, reads the committed maximum, and releases the lock before paging or invoking handlers. It then uses [Order 06][P2] Replace offset checkpoint paging with keyset paging #63's keyset reads over (after, ceiling]. This works without Make MsSqlDialect compatible with AzureSql and READ COMMITTED SNAPSHOT #31's READCOMMITTEDLOCK hint and does not rely on the query plan encountering a lower row lock first. A canceled or failed fence supplies no new checkpoint. The trade-off is that a long ambient write can delay the poll, and a queued poll can also delay later writers.
  • Keep the existing indexes. Actual SQL Server 2022 plans on 80,000 commits showed the ceiling reading the end of clustered PK_Commits (CheckpointNumber): one row, three logical reads. Global pages used an ordered clustered seek. Bucket-scoped pages of 128 used IX_Commits_Bucket_Checkpoint (BucketId, CheckpointNumber), then looked up the full commits. This does not justify adding a wide covering index for headers and payload. On upgraded stores, check that the bucket index actually exists: initialization skips schema creation if Commits already exists.

Fabian Schmied's insert-only lock proposal highlighted the cost of our earlier exclusive lock held through each writer's whole transaction. The separate prototype and benchmark passed 32 controlled cases with the locking hint on the stock SQL Server schema. The unhinted RCSI control exposed the higher checkpoint early. With eight writers, a 12 ms hold and an active poller, #75 measured 457 commits/s, the insert-only prototype 428, and the bounded version of that prototype 421. With no hold and no poller, the comparison was 2,160 vs. 1,002 commits/s. These are local results, not a production estimate or a proof for all query plans. The fence gives a correctness argument independent of the row access path and had higher write throughput in those runs.

A MongoDB-style optimistic allocator is not a drop-in replacement here: SQL Server IDENTITY gives competing writers different values. Switching to explicit keys would need an allocator and a durable floor against checkpoint reuse, and same-key contenders could still wait on an open ambient transaction.

Safe mode stays opt-in. Drain incompatible in-flight writes before enabling it, and switch all writers and safe readers using the same store. Legacy polling is unchanged and does not acquire this guarantee automatically. The implementation is scoped to the built-in SQL Server path; other engines remain tracked in #72 and Azure SQL verification is deferred to #14. See the SQL Server guide.

Co-authored by Alessandro Giorgetti and Codex (OpenAI).

AGiorgetti and others added 3 commits December 3, 2026 18:18
@AGiorgetti AGiorgetti changed the title Add opt-in safe checkpoint polling for SQL Server (#72) Add safe checkpoint polling across SQL dialects (#72) Dec 4, 2026
AGiorgetti and others added 6 commits December 4, 2026 11:34
Co-authored-by: Codex <codex@openai.com>
Co-authored-by: Codex <codex@openai.com>
Co-authored-by: Codex <codex@openai.com>
Co-authored-by: Codex <codex@openai.com>
Exercise 8.0, 8.4, and 9.7 against real InnoDB. Keep MySQL 5.7 excluded because its allocator can reuse a deleted checkpoint after a server restart.

Co-authored-by: Codex <codex@openai.com>
Use interleaved buckets and a one-commit page with both core pollers on all five SQL engines. Without bucket filtering the SQLite cases resume at the other bucket checkpoint.

Co-authored-by: Codex <codex@openai.com>
@AGiorgetti
AGiorgetti marked this pull request as ready for review December 4, 2026 14:50
@AGiorgetti
AGiorgetti requested a balanced review from Copilot December 4, 2026 14:50

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The new CI job uses mutable action tags, allowing executable workflow code to change without a repository update; checkout and setup-dotnet must be pinned to verified full commit SHAs.

1 open issue
What changed in this PR

Adds opt-in safe checkpoint polling across all five SQL providers for #72, building on existing keyset paging to prevent skipped commits when transactions complete out of order. Legacy polling remains unchanged; Azure SQL verification stays deferred.

Changes:

  • Adds dialect-specific checkpoint fences and configuration checks.
  • Adds concurrency, rollback, cancellation, and poller-resume regressions.
  • Documents deployment requirements and expands MySQL CI coverage.
File Description
src/​NEventStore.Persistence.Sqlite.Tests/​SafeCheckpointPollingTests.cs Tests SQLite visibility, resume, and configuration rejection.
src/​NEventStore.Persistence.Sqlite.Tests/​NEventStore.Persistence.Sqlite.Core.Tests.csproj Updates test dependencies and adds shared helpers.
src/​NEventStore.Persistence.Sql/​SqlPersistenceEngine.SafePolling.cs Implements independent, bounded safe polling.
src/​NEventStore.Persistence.Sql/​SqlPersistenceEngine.cs Exposes the contract and independent synchronous queries.
src/​NEventStore.Persistence.Sql/​SqlPersistenceEngine.Async.cs Supports independent asynchronous queries and cancellation.
src/​NEventStore.Persistence.Sql/​SqlDialects/​SqliteDialect.cs Adds opt-in schema and read-isolation checks.
src/​NEventStore.Persistence.Sql/​SqlDialects/​PostgreSqlDialect.cs Enables safe polling for both PostgreSQL dialects.
src/​NEventStore.Persistence.Sql/​SqlDialects/​PostgreSqlCheckpointProtocol.cs Adds advisory locks and sequence qualification.
src/​NEventStore.Persistence.Sql/​SqlDialects/​OracleNativeDialect.cs Integrates Oracle protocol initialization and writes.
src/​NEventStore.Persistence.Sql/​SqlDialects/​OracleDbStatement.cs Binds 64-bit checkpoint outputs from PL/SQL.
src/​NEventStore.Persistence.Sql/​SqlDialects/​OracleCheckpointProtocol.cs Adds Oracle gates and allocator checks.
src/​NEventStore.Persistence.Sql/​SqlDialects/​MySqlDialect.cs Integrates MySQL gate setup and writes.
src/​NEventStore.Persistence.Sql/​SqlDialects/​MySqlCheckpointProtocol.cs Adds InnoDB locking and allocator qualification.
src/​NEventStore.Persistence.Sql/​SqlDialects/​MsSqlDialect.cs Adds shared writer locks and exclusive reader fences.
src/​NEventStore.Persistence.Sql/​SqlDialects/​CommonSqlDialect.cs Checks inherited protocol compatibility.
src/​NEventStore.Persistence.Sql.Tests/​NEventStore.Persistence.Sql.Core.Tests.csproj References core polling clients.
src/​NEventStore.Persistence.Sql.Tests/​BucketPollingAssertions.cs Shares bucket-scoped stop-and-resume assertions.
src/​NEventStore.Persistence.PostgreSql.Tests/​SafeCheckpointPollingTests.cs Tests PostgreSQL ordering, fencing, and sequence caching.
src/​NEventStore.Persistence.PostgreSql.Tests/​NEventStore.Persistence.PostgreSql.Core.Tests.csproj Updates test dependencies.
src/​NEventStore.Persistence.Oracle.Tests/​SafeCheckpointPollingTests.cs Tests Oracle fencing, upgrades, and 64-bit checkpoints.
src/​NEventStore.Persistence.Oracle.Tests/​NEventStore.Persistence.Oracle.Core.Tests.csproj Updates test dependencies.
src/​NEventStore.Persistence.MySql.Tests/​SafeCheckpointPollingTests.cs Tests MySQL fencing, gate validation, and resume behavior.
src/​NEventStore.Persistence.MySql.Tests/​NEventStore.Persistence.MySql.Core.Tests.csproj Updates test dependencies.
src/​NEventStore.Persistence.MsSql.Tests/​SafeCheckpointPollingTests.cs Tests overlap, rollback, cancellation, and dialect compatibility.
src/​NEventStore.Persistence.MsSql.Tests/​NEventStore.Persistence.MsSql.Core.Tests.csproj Updates dependencies and references polling clients.
docs/​SqlServer-Safe-Checkpoint-Polling.md Explains SQL Server rollout, guarantees, and performance.
docs/​Sqlite-Safe-Checkpoint-Polling.md Explains SQLite qualification and single-writer guarantees.
docs/​PostgreSql-Safe-Checkpoint-Polling.md Documents PostgreSQL locking and sequence requirements.
docs/​Oracle-Safe-Checkpoint-Polling.md Documents Oracle gates and sequence migration.
docs/​MySql-Safe-Checkpoint-Polling.md Documents MySQL requirements, rollout, and costs.
Changelog.md Announces safe polling for all five providers.
.github/​workflows/​ci.yml Uses MySQL 8.4 and adds 8.0/9.7 integration jobs.

Review effort: Balanced

Comment thread .github/workflows/ci.yml Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants