Repository navigation
Description
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
longcheckpoint and the existing behavior of legacyGetFrom*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
IDENTITYinsert 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_INCREMENTto 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
- 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.
- 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.
- 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.
- 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
AGiorgetti commentedon Dec 3, 2026
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:
READCOMMITTEDLOCKmay 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_getapplockper event store, across buckets, before theIDENTITYinsert. 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.
BIGINT IDENTITYBIGSERIALAUTO_INCREMENTBEFORE INSERTtrigger usingNEXTVALINTEGER PRIMARY KEY AUTOINCREMENTScope 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).
fschmied commentedon Dec 3, 2026
@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_getapplockonly around the IDENTITY insert, not for the full transaction, as long asREADCOMMITTEDLOCKfrom #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:
(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:
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).
fschmied commentedon Dec 3, 2026
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.
AGiorgetti commentedon Dec 3, 2026
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.
[-]Define and test a safe checkpoint resume position for SQL Server polling[/-][+]Implement safe checkpoint polling across all supported SQL engines[/+]AGiorgetti commentedon Dec 3, 2026
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
longcheckpoint 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.IDENTITYinsert, across buckets. Hold it through actual commit or rollback, including an outer ambient transaction.sp_getapplockavoids 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.CACHE > 1can let a session issue a cached lower number after another session issued a higher one, even if the inserts take turns.AUTOINCREMENTpath 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).
Reproduce SQL Server checkpoint overtaking (#72)
Add opt-in safe checkpoint polling for SQL Server (#72)
Qualify SQLite for safe checkpoint polling (#72)
Qualify PostgreSQL for safe checkpoint polling (#72)
Qualify MySQL/InnoDB for safe checkpoint polling (#72)
Qualify Oracle for safe checkpoint polling (#72)