Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/SqlIdempotentAmbientTestsBase.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/SqlIdempotentAmbientTestsBase.cs ---- using System.Transactions; using redb.Route.Abstractions; using redb.Route.Sql.Connection; using redb.Route.Sql.Repositories; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql.E2E.Base; /// /// tells the idempotent consumer whether a rollback of the /// route transaction takes the key back by itself. It must say what the driver does: a false "no" makes the consumer delete /// the key after the rollback, and in a cluster that delete can hit the key another node has claimed meanwhile; a false /// "yes" leaves a key behind whose work never committed, and the redelivery is skipped as a duplicate. /// public abstract class SqlIdempotentAmbientTestsBase : IAsyncLifetime { private readonly string _table = "rsql_idem_" + Guid.NewGuid().ToString("N")[..12]; private readonly List _connectionStrings = []; /// The provider under test. protected abstract SqlE2EProvider Provider { get; } /// Whether the provider's connections enlist in an ambient transaction with the default connection string. protected abstract bool EnlistsByDefault { get; } public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { try { if (_connectionStrings.Count > 0) { await using var connection = await Factory(_connectionStrings[0]).CreateConnectionAsync(); await SqlE2EDatabase.ExecuteAsync(connection, null, $"DROP TABLE {_table}"); } } finally { (Provider as IDisposable)?.Dispose(); } } [Fact] public async Task JoinsAmbientTransaction_SaysWhatTheRollbackDoesWithTheKey() { var repository = Repository(Provider.ConnectionString); await repository.Add("warm-up"); // creates the table outside any transaction var keptAfterRollback = await AddInRolledBackScopeAsync(repository, "k1"); ((IIdempotentRepository)repository).JoinsAmbientTransaction.Should().Be(EnlistsByDefault, $"{Provider.Name} with its default connection string"); ((IIdempotentRepository)repository).JoinsAmbientTransaction.Should().Be(!keptAfterRollback, "the flag must match what the rollback did with the key: taken back when the connection enlisted, kept otherwise"); } /// Enlist=false keeps the connection out of the ambient transaction; the flag follows it. protected async Task AssertEnlistOffDoesNotJoin() { var repository = Repository(Provider.ConnectionString + ";Enlist=false"); await repository.Add("warm-up"); var keptAfterRollback = await AddInRolledBackScopeAsync(repository, "k1"); keptAfterRollback.Should().BeTrue("with Enlist=false the insert commits on its own, outside the route transaction"); ((IIdempotentRepository)repository).JoinsAmbientTransaction.Should().BeFalse("the consumer has to remove the key itself after the rollback"); } private static async Task AddInRolledBackScopeAsync(SqlIdempotentRepository repository, string key) { using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { (await repository.Add(key)).Should().BeTrue(); // The route failed: the scope ends without Complete(). } return await repository.Contains(key); } [Fact] public async Task Claim_TellsAClaimInFlightFromAConfirmedOne() { var repository = Repository(Provider.ConnectionString); (await repository.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Claimed); (await repository.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.InFlight); await repository.Confirm("c1"); (await repository.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Confirmed); await repository.Remove("c1"); (await repository.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Claimed); } [Fact] public async Task Claim_AnAbandonedClaim_IsTakenOver_AConfirmedOneNever() { var repository = Repository(Provider.ConnectionString); await repository.Add("orphan"); await repository.Add("done"); await repository.Confirm("done"); await Task.Delay(TimeSpan.FromSeconds(1.5)); (await repository.Claim("orphan", TimeSpan.FromSeconds(1))).Should().Be(IdempotentClaim.TakenOver); (await repository.Claim("orphan", TimeSpan.FromSeconds(1))).Should().Be(IdempotentClaim.InFlight, "the takeover is a fresh claim"); (await repository.Claim("done", TimeSpan.FromSeconds(1))).Should().Be(IdempotentClaim.Confirmed); } [Fact] public async Task Claim_TwoNodesTakingOverOneAbandonedClaim_OneWins_OneRowStays() { // Two repositories over one table, as two nodes are: both find the same stale row. It is written long abandoned and // the timeout is a minute, so however the callers spread (SQLite serializes them), the winner's fresh claim stays // inside it. var nodeA = Repository(Provider.ConnectionString); var nodeB = Repository(Provider.ConnectionString); await SeedAbandonedAsync(nodeA, "stale"); var outcomes = await Task.WhenAll(Enumerable.Range(0, 8).Select(i => Task.Run(() => (i % 2 == 0 ? nodeA : nodeB).Claim("stale", TimeSpan.FromMinutes(1))))); // One caller holds the claim: the one that took the stale entry over, or one that found it gone and claimed it anew. outcomes.Count(o => o is IdempotentClaim.TakenOver or IdempotentClaim.Claimed).Should().Be(1); outcomes.Count(o => o == IdempotentClaim.InFlight).Should().Be(outcomes.Length - 1); (await nodeA.Claim("stale", null)).Should().Be(IdempotentClaim.InFlight, "one unconfirmed row: the winner's fresh claim"); } /// A claim of left unconfirmed long ago, as a stopped node leaves it. private async Task SeedAbandonedAsync(SqlIdempotentRepository repository, string key) { await repository.Contains("warm-up"); // creates the table await using var connection = await Factory(Provider.ConnectionString).CreateConnectionAsync(); await SqlE2EDatabase.ExecuteAsync(connection, null, $"INSERT INTO {_table} (processor_name, message_key, created_at, confirmed) VALUES ('route-1', '{key}', '2000-01-01T00:00:00.0000000+00:00', 0)"); } [Fact] public async Task Add_ThatLosesTheKeyToAConcurrentInsert_IsADuplicate_NotAnError() { // Another session inserts the key and commits while node A's insert of it is under way. PostgreSQL then fails // node A's insert on the primary key (its existence check could not see the uncommitted row); SQL Server and SQLite // wait on the row and find it. Either way the key is held: a duplicate, not an exception for the route. var nodeA = Repository(Provider.ConnectionString); await nodeA.Add("warm-up"); // creates the table await using var other = await Factory(Provider.ConnectionString).CreateConnectionAsync(); await using var otherTx = await other.BeginTransactionAsync(); await SqlE2EDatabase.ExecuteAsync(other, otherTx, $"INSERT INTO {_table} (processor_name, message_key, created_at, confirmed) VALUES ('route-1', 'race', '2026-01-01T00:00:00.0000000+00:00', 0)"); var addA = Task.Run(() => nodeA.Add("race")); await Task.Delay(TimeSpan.FromMilliseconds(500)); await otherTx.CommitAsync(); (await addA).Should().BeFalse("the other session's row holds the key"); } [Fact] public async Task Claim_AnInsertThatWaitedPastTheTimeout_BecomesVisibleAsAFreshClaim() { // Another session holds the key, so node A's insert waits on it for longer than the timeout. The claim it then // commits is new: node B must find it in flight, not abandoned. var nodeA = Repository(Provider.ConnectionString); var nodeB = Repository(Provider.ConnectionString); await nodeA.Add("warm-up"); // creates the table await using var blocker = await Factory(Provider.ConnectionString).CreateConnectionAsync(); await using var hold = await blocker.BeginTransactionAsync(); await SqlE2EDatabase.ExecuteAsync(blocker, hold, $"INSERT INTO {_table} (processor_name, message_key, created_at, confirmed) VALUES ('route-1', 'slow', '2000-01-01T00:00:00.0000000+00:00', 0)"); var claimA = Task.Run(() => nodeA.Claim("slow", TimeSpan.FromSeconds(1))); await Task.Delay(TimeSpan.FromSeconds(1.5)); claimA.IsCompleted.Should().BeFalse("node A's insert waits on the key the other session holds"); await hold.RollbackAsync(); (await claimA).Should().Be(IdempotentClaim.Claimed); (await nodeB.Claim("slow", TimeSpan.FromSeconds(1))).Should().Be(IdempotentClaim.InFlight, "node A's claim became visible a moment ago, however long its insert waited"); } [ClaimRaceLoopFact] public async Task Claim_TwoNodesTakingOverOneAbandonedClaim_200Times_OneWinsEachTime() { var nodeA = Repository(Provider.ConnectionString); var nodeB = Repository(Provider.ConnectionString); for (var iteration = 0; iteration < 200; iteration++) { var key = $"stale-{iteration}"; await SeedAbandonedAsync(nodeA, key); var outcomes = await Task.WhenAll(Enumerable.Range(0, 8).Select(i => Task.Run(() => (i % 2 == 0 ? nodeA : nodeB).Claim(key, TimeSpan.FromMinutes(1))))); outcomes.Count(o => o is IdempotentClaim.TakenOver or IdempotentClaim.Claimed) .Should().Be(1, $"iteration {iteration}: {string.Join(",", outcomes)}"); } } private SqlIdempotentRepository Repository(string connectionString) { _connectionStrings.Add(connectionString); return new SqlIdempotentRepository(Factory(connectionString), new SqlIdempotentOptions { ProcessorName = "route-1", TableName = _table }); } private ISqlConnectionFactory Factory(string connectionString) => new SqlConnectionFactory(new SqlConnectionOptions { ConnectionString = connectionString, ProviderFactory = Provider.Factory }); } /// /// The claim race in a loop of 200: minutes per database, so it runs only with REDB_CLAIM_RACE_LOOP=1 and is /// skipped, visibly, otherwise. /// public sealed class ClaimRaceLoopFactAttribute : FactAttribute { public ClaimRaceLoopFactAttribute() { if (Environment.GetEnvironmentVariable("REDB_CLAIM_RACE_LOOP") != "1") Skip = "The 200-iteration claim race runs with REDB_CLAIM_RACE_LOOP=1."; } }