Skip to content

Implement safe checkpoint polling across all supported SQL engines #72

In progress

Description

@AGiorgetti

Goal and issue ownership

Deliver the SQL provider's part of NEventStore #425 using the optional safe-polling contract in core PR #555. This issue covers all five supported SQL engines in the current verification matrix. Azure SQL deployment verification is deferred to #14 and is not a completion requirement for this issue. #21 remains the original SQL Server bug report and can be closed once the SQL Server fix is verified and documented. Keep this issue open until the whole checklist below is qualified.

The SQL Server report in #21 and the Azure SQL report in #14 illustrate the problem: writer A obtains checkpoint 101 and stalls, writer B commits 102, and a poll saves 102. When A commits, the next poll starts after 102 and misses 101. #31 added an opt-in locking-read mitigation for SQL Server and Azure SQL; #63 replaced offset paging with keyset paging. Both are already merged. Neither orders visibility across transactions.

Shared contract

  • Preserve the existing long checkpoint and the existing behavior of legacy GetFrom* reads. Safe polling is opt-in. The provider must not let a reader advance past a lower matching commit that could still become visible. Permanent gaps are legal.
  • Reuse [Order 06][P2] Replace offset checkpoint paging with keyset paging #63's ordered keyset reads with a fixed, safe upper bound. Qualify both sync and async polling, globally and by bucket. Safe readers must not expose their own uncommitted ambient writes.
  • Report unsupported configurations explicitly. Do not silently fall back to legacy reads, use timed gap retries or use dirty counts as proof. Document the settings and writer participation needed for the guarantee, including a coordinated cutover where required. Safe polling cannot recover commits missed before cutover.

Engine qualification checklist

  • SQL Server: Start with a per-store transaction-owned writer gate acquired before the IDENTITY insert and held through the actual commit or rollback, including any outer ambient transaction. Verify lock-based READ COMMITTED and READ_COMMITTED_SNAPSHOT. Treat an insert-only lock plus locking reads as an alternative to qualify separately, not as the baseline guarantee. See the #72 discussion.
  • PostgreSQL: Evaluate a transaction-owned writer gate and verify monotone sequence issuance across connections, including the effect of sequence caching.
  • MySQL/InnoDB: Evaluate a per-store lock row held in the existing write transaction. Do not rely on AUTO_INCREMENT to order commits.
  • Oracle: Evaluate a transaction-owned gate and qualify the checkpoint sequence and insert trigger. State explicitly which sequence settings and deployments, including RAC if claimed, are supported.
  • SQLite: Verify whether the existing single-writer behavior suffices without an added gate, with an independent committed reader in both WAL and rollback-journal modes.

These mechanisms are candidates, not promises of support. Qualify in staged PRs with a shared acceptance suite. Keep the existing allocator where it can be proved safe; evaluate a transactional allocator separately if an engine cannot guarantee monotone issuance with its current allocator.

Test-first acceptance and completion

  1. Use independent connections and a deterministic barrier: stall the lower writer, attempt the higher write, poll, and resume with a fresh reader from the saved checkpoint. Prove the legacy miss where the engine permits overtaking; otherwise prove why the higher writer cannot publish first.
  2. Repeat with the lower writer rolling back. The reader must progress despite permanent gaps. Include global and bucket-scoped reads, sync and async, multiple pages, and removal of an earlier row between pages.
  3. Where the engine supports ambient writes, verify the guarantee holds through the outer transaction. Cover lock failure, cancellation, and unsupported configurations without advancing the saved position past unhandled commits. Measure throughput and tail latency under writer contention, especially with synchronous projection work in ambient transactions.
  4. Verify against the core #555 pollers. Before merging code that depends on #555, pin the merged core revision in the SQL submodule. Before release, set the SQL package dependency to a published core version that contains the contract and validate a package-only consumer.

Companion provider work: MongoDB #118 and PR #121. The contract is shared; MongoDB's write mechanism is not a SQL prerequisite.

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

Activity

  1. AGiorgetti commented on Dec 3, 2026

    @AGiorgetti
    MemberAuthor

    Implementation boundary and qualification for core #425

    Core #425 / PR #555 requires ordered visibility of eligible commits, not gap-free identity values. SQL #21 is the allocation-order bug, SQL #14 is the Azure SQL report, and SQL #31 / PR #39 is a reader-side mitigation. Reuse #39's RCSI test scenario, not the broad hint rewrite: READCOMMITTEDLOCK may wait for an inserted, uncommitted row, but it does not stop a higher ID from becoming visible before a lower allocated row exists.

    Proposed SQL Server approach: acquire one transaction-owned sp_getapplock per event store, across buckets, before the IDENTITY insert. Hold it until the actual commit or rollback, including the outer ambient transaction. Writers bypassing the gate invalidate the guarantee; lock failure must not continue to an insert. The safe reader must not see its own uncommitted ambient writes. Seek after the last returned checkpoint within a fixed upper bound, ordered by checkpoint. SQL #63 can share this query shape but should track the broader paging work separately.

    Test first: reproduce the RCSI miss with independent connections and an open transaction holding the lower ID. Verify that with the gate the competing higher insert cannot publish first. Cover commit and rollback, fresh-reader resume, both READ COMMITTED modes, sync and async, all-bucket and bucket-scoped reads, and permanent gaps. Measure contention with concurrent and long-running ambient writers.

    Dialect Existing allocation Implication for safe polling
    SQL Server / Azure SQL BIGINT IDENTITY Allocation can precede publication; a reader hint does not order writers.
    PostgreSQL Sequence-backed BIGSERIAL A later transaction can commit first. Check sequence caching and issuance order before reusing a writer gate. Sequence docs
    MySQL/InnoDB AUTO_INCREMENT Allocation does not serialize transaction completion; any auto-increment lock runs to statement end, not transaction end. InnoDB docs
    Oracle BEFORE INSERT trigger using NEXTVAL Sequence allocation is independent of commit. Cached sequences and RAC ordering need explicit qualification. Sequence docs
    SQLite INTEGER PRIMARY KEY AUTOINCREMENT One writer per database removes this particular overtaking race under committed reads on an independent connection. Offset paging remains a separate problem. Isolation docs

    Scope this issue to SQL Server/Azure SQL. The other dialects must be proved separately; SQLite is a candidate for qualification without an additional writer gate.

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

  2. fschmied commented on Dec 3, 2026

    @fschmied

    Proposed SQL Server approach: acquire one transaction-owned sp_getapplock per event store, across buckets, before the IDENTITY insert. Hold it until the actual commit or rollback, including the outer ambient transaction. Writers bypassing the gate invalidate the guarantee; lock failure must not continue to an insert. The safe reader must not see its own uncommitted ambient writes. Seek after the last returned checkpoint within a fixed upper bound, ordered by checkpoint. #63 can share this query shape but should track the broader paging work separately.

    @AGiorgetti I think this approach would solve the issue for good, but I'd like to raise attention to the fact that it will also introduce a bottleneck for concurrent writes to the event store. For systems that require a lot of write throughput, this could be significant. It will definitely be relevant for systems that make use of NEventStore's support for synchronous read model updates via ambient transaction enlistment, which is actually a really nice feature of NEventStore, but which of course makes the write transactions longer.

    At least with SQL Server, I believe it might actually be sufficient to hold the sp_getapplock only around the IDENTITY insert, not for the full transaction, as long as READCOMMITTEDLOCK from #31 is enabled.

    Here's the sequence I gave in #21 (comment), which show how things could still go wrong once READCOMMITTEDLOCK is in place:

    1. Thread A: Get next CheckpointNumber (IDENTITY) => 17
    2. Thread B: Get next CheckpointNumber (IDENTITY) => 18
    3. Thread B: Take ROWLOCK on CLUSTERED index entry for value 18
    4. Thread C: Run into ROWLOCK of step 3, block due to READCOMMITTEDLOCK.
    5. Thread A: Take ROWLOCK on CLUSTERED index entry for value 17
    6. Not caring about the order, Threads A and B insert and commit their rows.

    (In my opinion, this is very unlikely because it requires a lot of things to happen between steps 1 and 5 while Thread A is interruped. In #21 (comment), I believe it happened because the CLUSTERED INDEX was changed, effectively disabling the synchronization mechanism. But still, even with the original CLUSTERED INDEX, it could happen, so it's a good idea to find a real solution.)

    If you insert a lock around the whole INSERT statement (which includes "Get next CheckpointNumber (IDENTITY)", "Take ROWLOCK on CLUSTERED index entry", "Insert"), the steps reorder and the issue is gone:

    1. Thread A: Take sp_applock => granted
    2. Thread A: Get next CheckpointNumber (IDENTITY) => 17
    3. Thread B: Take sp_applock => blocked
    4. Thread A: Take ROWLOCK on CLUSTERED index entry for value 17
    5. Thread A: Insert values with checkpoint number 17
    6. Thread A: Release sp_applock
    7. Thread B: (unblocked) Get next CheckpointNumber (IDENTITY) => 18
    8. Thread B: Take ROWLOCK on CLUSTERED index entry for value 18
    9. Thread C: Run into ROWLOCK of step 4, block due to READCOMMITTEDLOCK.
    10. Thread B: Insert values with checkpoint number 18
    11. Thread B: Release sp_applock
    12. Not caring about the order, Threads A and B commit their rows.

    This time, Thread C blocks on the checkpoint number 17, and all is good, no values skipped.

    Of course, I might be missing something, so double check. But if I'm right, it would be very beneficial for performance if this locking approach could be optimized at a dialect level.

    Note, again, that this relies on READCOMMITTEDLOCK (and on the original CLUSTERED INDEX on CheckpointNumber).

  3. fschmied commented on Dec 3, 2026

    @fschmied

    PS: I've left the team where we were using NEventStore, so I no longer have a stake in it. Just wanted to add my perspective as I put a lot of research into this back then.

    PPS: We actually never saw skipped commits in our production system once we had the READCOMMITTEDLOCK in place, I only reasoned about them in theory. In the end, we still built in a safety mechanism which was to simply rerun the polling query when we saw a gap in the checkpoint numbers. I reasoned that the additional roundtrip would add so much time for Thread A to take its ROWLOCK lock that it "couldn't realistically happen" any more.

  4. AGiorgetti commented on Dec 3, 2026

    @AGiorgetti
    MemberAuthor

    Hi @fschmied , I've just merged in develop the READCOMMOTTEDLOCK that I delayed for too long (all my production enviroments use no sql providers, so the SQL one was left behind, and it was easy for those that needed to implement the fix).

    All your insights and the comments on the issues are very helpful.

    I've recently hit the out of order commits problem again and I'decided that it was time to get rid of it once and for all (I hope). AI gives me time to explore several solutions that could work with many DB engines (given that my knowledge of them is not as strong as it was many years ago...), both SQL and NoSQL.

    It all started with this very old issue in NEventStore: #425.

  5. changed the title [-]Define and test a safe checkpoint resume position for SQL Server polling[/-] [+]Implement safe checkpoint polling across all supported SQL engines[/+] on Dec 3, 2026
  6. AGiorgetti commented on Dec 3, 2026

    @AGiorgetti
    MemberAuthor

    One safe-polling contract, five SQL engines

    The goal is to deliver the SQL part of core #425 / PR #555, not to make every dialect use a SQL Server application lock. Keep the existing long checkpoint and legacy APIs. In safe mode, reuse #63's ordered, bounded keyset reads on an independent committed read path. A poll must not deliver 102 if a lower matching commit at 101 can still become visible. Permanent gaps are legal, and an unsupported configuration must fail explicitly rather than fall back to legacy polling. #31 is a useful mitigation, not a proof of that guarantee.

    Engine Candidate and what to verify
    SQL Server Acquire a per-store transaction-owned gate before the IDENTITY insert, across buckets. Hold it through actual commit or rollback, including an outer ambient transaction. sp_getapplock avoids adding a lock table; a dedicated lock row is another option. The full-transaction design does not rely on #31. The insert-only lock proposal is worth testing for long ambient transactions, but would need separate proof that the bounded locking read encounters the lower row before delivering the higher one, including bucket-scoped query plans.
    PostgreSQL Take a transaction-owned gate before the sequence-backed insert. Verify sequence settings across connections: CACHE > 1 can let a session issue a cached lower number after another session issued a higher one, even if the inserts take turns.
    MySQL/InnoDB Use a dedicated per-store row locked in the same transaction before insert and held through commit or rollback. InnoDB's auto-increment behavior does not serialize transaction completion.
    Oracle Evaluate the same lock-row pattern, and qualify the trigger and sequence together. Don't assume a gate fixes unordered issuance across RAC instances. For RAC, verify an ordered sequence or a transactional allocator before claiming support.
    SQLite Start with no extra writer gate. SQLite serializes writers; test the existing AUTOINCREMENT path through the provider with an independent committed reader in both WAL and rollback-journal modes.

    Recommendation: Keep the existing allocators where we can prove they are safe, and share the read path, capability checks, and acceptance tests. If an engine cannot guarantee monotone issuance with its existing allocator, consider a transactional counter row: allocate the checkpoint and insert its commit in the same transaction. That avoids dependence on native sequence ordering, but it still serializes writers and requires migrating the affected insert, identity, or trigger setup. It is not the first choice.

    How we prove it: Start with SQL Server and use SQLite as the simplest second qualification. On every engine, stall a lower writer, attempt the higher write, poll, and resume with a fresh reader from the saved checkpoint. Repeat with rollback to prove permanent gaps don't stall polling. Cover sync and async, global and bucket-scoped reads, and both SQL Server READ COMMITTED modes. Where writes enlist in ambient transactions, verify lock lifetime and measure concurrent append throughput and tail latency with synchronous projection work. All writers sharing a store must participate in the selected protocol; the cutover must drain incompatible in-flight writes.

    #21 remains the original SQL Server bug report. Keep #72 open until all five engines in the checklist are qualified. Azure SQL verification is deferred to #14 and is not a completion requirement for #72.

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

  7. self-assigned this
    on Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions