Path: redb-route/tests/redb.Route.Tests.Core/Integration/RedbIdempotentRepositoryIntegrationTests.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.Core/Integration/RedbIdempotentRepositoryIntegrationTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.RedbCore.Models; using redb.Route.RedbCore.Repositories; namespace redb.Route.Tests.Core.Integration; /// /// Integration tests for running against a real database. /// Subclassed per provider (Postgres, MsSql). /// Each test instance uses a unique prefix so multiple TFM runners can execute in parallel /// without interfering (no global cleanup required). /// public abstract class RedbIdempotentRepositoryIntegrationTests : IAsyncLifetime { private readonly IRedbService _redb; private readonly IServiceScopeFactory _scopeFactory; /// Unique prefix for this test instance — isolates data across parallel runs. private readonly string _id = Guid.NewGuid().ToString("N")[..8]; protected RedbIdempotentRepositoryIntegrationTests(IRedbService redb, IServiceScopeFactory scopeFactory) { _redb = redb; _scopeFactory = scopeFactory; } private string P(string name) => $"{_id}-{name}"; private RedbIdempotentRepository CreateRepository(string processor = "test-proc", TimeSpan? ttl = null) { var options = new RedbIdempotentOptions { ProcessorName = P(processor), Ttl = ttl }; return new RedbIdempotentRepository(_scopeFactory, options); } public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { // Clean up only entries created by this test instance (matching our unique prefix). // StartsWith is supported by redb Pro LINQ provider → translates to LIKE 'prefix%'. try { var all = await _redb.Query() .Where(e => e.ProcessorName!.StartsWith(_id)) .ToListAsync(); if (all.Count > 0) await _redb.DeleteAsync((IEnumerable)all); } catch { // Parallel TFM runs may cause deadlocks during cleanup — safe to ignore } } // ─── Add ─────────────────────────────────────────────── [Fact] public async Task Add_NewKey_ReturnsTrue() { var repo = CreateRepository(); var result = await repo.Add("msg-1"); result.Should().BeTrue(); } [Fact] public async Task Add_DuplicateKey_ReturnsFalse() { var repo = CreateRepository(); await repo.Add("msg-dup"); var result = await repo.Add("msg-dup"); result.Should().BeFalse(); } [Fact] public async Task Add_SameKeyDifferentProcessor_ReturnsTrue() { var repo1 = CreateRepository("proc-A"); var repo2 = CreateRepository("proc-B"); await repo1.Add("shared-key"); var result = await repo2.Add("shared-key"); result.Should().BeTrue(); } // ─── Contains ────────────────────────────────────────── [Fact] public async Task Contains_AfterAdd_ReturnsTrue() { var repo = CreateRepository(); await repo.Add("msg-exists"); (await repo.Contains("msg-exists")).Should().BeTrue(); } [Fact] public async Task Contains_NonExistentKey_ReturnsFalse() { var repo = CreateRepository(); (await repo.Contains("never-added")).Should().BeFalse(); } // ─── Confirm ────────────────────────────────────────── [Fact] public async Task Confirm_SetsConfirmedFlag() { var repo = CreateRepository(); await repo.Add("msg-confirm"); await repo.Confirm("msg-confirm"); // Verify via direct query — match by processor prefix to isolate var procName = P("test-proc"); var items = await _redb.Query() .Where(e => e.MessageKey == "msg-confirm" && e.ProcessorName == procName) .ToListAsync(); items.Should().ContainSingle() .Which.Props.Confirmed.Should().BeTrue(); } // ─── Remove ────────────────────────────────────────── [Fact] public async Task Remove_DeletesEntry() { var repo = CreateRepository(); await repo.Add("msg-remove"); await repo.Remove("msg-remove"); (await repo.Contains("msg-remove")).Should().BeFalse(); } [Fact] public async Task Remove_NonExistentKey_DoesNotThrow() { var repo = CreateRepository(); var act = () => repo.Remove("ghost"); await act.Should().NotThrowAsync(); } // ─── Clear ────────────────────────────────────────── [Fact] public async Task Clear_RemovesAllEntriesForProcessor() { var repo = CreateRepository("clear-proc"); await repo.Add("c1"); await repo.Add("c2"); await repo.Add("c3"); await repo.Clear(); (await repo.Contains("c1")).Should().BeFalse(); (await repo.Contains("c2")).Should().BeFalse(); (await repo.Contains("c3")).Should().BeFalse(); } [Fact] public async Task Clear_DoesNotAffectOtherProcessors() { var repo1 = CreateRepository("isolate-A"); var repo2 = CreateRepository("isolate-B"); await repo1.Add("x"); await repo2.Add("y"); await repo1.Clear(); (await repo2.Contains("y")).Should().BeTrue(); } // ─── Concurrency: one key, one winner ───────────────── [Fact] public async Task Add_ParallelSameKey_ExactlyOneWins_SingleRowStored() { var repo = CreateRepository("race-proc"); // Prime the scheme outside the measured races so scheme sync doesn't add noise. await repo.Add("race-warmup"); for (var i = 0; i < 10; i++) { var key = $"race-key-{i}"; var results = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => repo.Add(key))); results.Count(r => r).Should().Be(1, $"exactly one of the concurrent Add('{key}') calls may claim the key"); var entryName = RedbIdempotentRepository.ComposeEntryName(P("race-proc"), key); var rows = await _redb.Query() .WhereRedb(x => x.Name == entryName) .ToListAsync(); rows.Should().ContainSingle( $"the unique index must let exactly one row through for '{key}'"); } } [Fact] public async Task Add_UniqueKeyAlreadyCommittedByRaceWinner_ReturnsFalse() { // Deterministic replay of the TOCTOU window: the winner's row is already committed // with our unique key, but under a name the Add lookup does not see. The insert must // hit UIX__objects__scheme_unique and come back as a calm "duplicate" — no exception. var repo = CreateRepository("toctou-proc"); await repo.Add("toctou-warmup"); const string key = "toctou-key"; var procName = P("toctou-proc"); var entryName = RedbIdempotentRepository.ComposeEntryName(procName, key); var winner = new RedbObject { name = P("toctou-winner-row"), ValueUnique = entryName, Props = new IdempotentEntryProps { ProcessorName = procName, MessageKey = key, CreatedAt = DateTimeOffset.UtcNow, Confirmed = false } }; await _redb.SaveAsync(winner); var result = await repo.Add(key); result.Should().BeFalse("the key is already claimed by the committed row"); } // ─── Long client keys ───────────────────────────────── [Fact] public async Task Add_LongKey_NormalizedAndStillIdempotent() { var repo = CreateRepository("long-proc"); var prefix = new string('k', 600); var key1 = prefix + "-first"; var key2 = prefix + "-second"; (await repo.Add(key1)).Should().BeTrue(); (await repo.Add(key1)).Should().BeFalse("the same long key must be recognized as a duplicate"); (await repo.Add(key2)).Should().BeTrue("a long key differing only past the readable prefix is distinct"); (await repo.Contains(key1)).Should().BeTrue(); await repo.Remove(key1); (await repo.Contains(key1)).Should().BeFalse(); (await repo.Contains(key2)).Should().BeTrue(); } // ─── TTL cleanup ─────────────────────────────────────── [Fact] public async Task Add_WithTtl_CleansUpExpiredEntries() { // Create repo with short TTL var repo = CreateRepository("ttl-proc", ttl: TimeSpan.FromSeconds(2)); // Add an entry that will become "old" after TTL elapses await repo.Add("old-msg"); (await repo.Contains("old-msg")).Should().BeTrue(); // Wait for TTL to expire await Task.Delay(TimeSpan.FromSeconds(3)); // Add a new key — this triggers cleanup of expired entries await repo.Add("new-msg"); // Old entry should be cleaned up by TTL (await repo.Contains("old-msg")).Should().BeFalse(); // New entry should exist (await repo.Contains("new-msg")).Should().BeTrue(); } // ─── End-to-end workflow ────────────────────────────── [Fact] public async Task FullWorkflow_AddContainConfirmRemove() { var repo = CreateRepository("e2e-proc"); // Add (await repo.Add("wf-1")).Should().BeTrue(); // Contains (await repo.Contains("wf-1")).Should().BeTrue(); // Duplicate (await repo.Add("wf-1")).Should().BeFalse(); // Confirm await repo.Confirm("wf-1"); var procName = P("e2e-proc"); var items = await _redb.Query() .Where(e => e.MessageKey == "wf-1" && e.ProcessorName == procName) .ToListAsync(); items.Should().ContainSingle().Which.Props.Confirmed.Should().BeTrue(); // Remove await repo.Remove("wf-1"); (await repo.Contains("wf-1")).Should().BeFalse(); } [Fact] public async Task MultipleKeys_IndependentLifecycle() { var repo = CreateRepository("multi-proc"); await repo.Add("k1"); await repo.Add("k2"); await repo.Add("k3"); await repo.Remove("k2"); (await repo.Contains("k1")).Should().BeTrue(); (await repo.Contains("k2")).Should().BeFalse(); (await repo.Contains("k3")).Should().BeTrue(); } // ─── Claim ───────────────────────────────────────────── [Fact] public async Task Claim_TellsAClaimInFlightFromAConfirmedOne() { var repo = CreateRepository("claim-proc"); (await repo.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Claimed); (await repo.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.InFlight); await repo.Confirm("c1"); (await repo.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Confirmed); await repo.Remove("c1"); (await repo.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Claimed); } [Fact] public async Task Claim_AnAbandonedClaim_IsTakenOver_AConfirmedOneNever() { var repo = CreateRepository("takeover-proc"); await repo.Add("orphan"); await repo.Add("done"); await repo.Confirm("done"); await Task.Delay(TimeSpan.FromSeconds(1.5)); (await repo.Claim("orphan", TimeSpan.FromSeconds(1))).Should().Be(IdempotentClaim.TakenOver); (await repo.Claim("orphan", TimeSpan.FromSeconds(1))).Should().Be(IdempotentClaim.InFlight, "the takeover is a fresh claim"); (await repo.Claim("done", TimeSpan.FromSeconds(1))).Should().Be(IdempotentClaim.Confirmed); } [Fact] public async Task Claim_TwoNodesTakingOverOneAbandonedClaim_OneWins_OneEntryStays() { // Two repositories over one database, as two nodes are: both read the same stale entry. It is written long // abandoned and the timeout is a minute, so however long the callers wait on each other's locks, the winner's fresh // claim stays inside it. var nodeA = CreateRepository("race-proc"); var nodeB = CreateRepository("race-proc"); await SeedAbandonedAsync(nodeA, "race-proc", "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); var procName = P("race-proc"); var entries = await _redb.Query() .Where(e => e.MessageKey == "stale" && e.ProcessorName == procName) .ToListAsync(); entries.Should().ContainSingle().Which.Props.Confirmed.Should().BeFalse(); } [Fact] public async Task Claim_AnInsertThatWaitedPastTheTimeout_BecomesVisibleAsAFreshClaim() { // Another session holds the entry's unique key (under another name, so node A's lookup by name does not wait on // it): node A's insert waits for longer than the timeout. The claim it then commits is new, and node B must find it // in flight, not abandoned. var nodeA = CreateRepository("slow-insert"); var nodeB = CreateRepository("slow-insert"); await nodeA.Contains("slow"); // syncs the scheme using var scope = _scopeFactory.CreateScope(); var blocker = scope.ServiceProvider.GetRequiredService(); var hold = await blocker.Context.BeginTransactionAsync(); await blocker.SaveAsync(new RedbObject { name = $"blocker-{_id}", ValueUnique = RedbIdempotentRepository.ComposeEntryName(P("slow-insert"), "slow"), Props = new IdempotentEntryProps { ProcessorName = P("blocker"), MessageKey = "slow", CreatedAt = DateTimeOffset.UtcNow }, }); 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 hold.DisposeAsync(); (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() { for (var iteration = 0; iteration < 200; iteration++) { var proc = $"race-loop-{iteration}"; var nodeA = CreateRepository(proc); var nodeB = CreateRepository(proc); await SeedAbandonedAsync(nodeA, proc, "stale"); var outcomes = await Task.WhenAll(Enumerable.Range(0, 8).Select(i => Task.Run(() => (i % 2 == 0 ? nodeA : nodeB).Claim("stale", TimeSpan.FromMinutes(1))))); outcomes.Count(o => o is IdempotentClaim.TakenOver or IdempotentClaim.Claimed) .Should().Be(1, $"iteration {iteration}: {string.Join(",", outcomes)}"); } } // ─── Lease: the claim id ─────────────────────────────── [Fact] public async Task Lease_StaleHolderAfterATakeover_ConfirmsNothing_TheNewHolderConfirms() { var nodeA = CreateRepository("lease-confirm"); var nodeB = CreateRepository("lease-confirm"); var first = await nodeA.Lease("m1", TimeSpan.FromMinutes(1)); first.Outcome.Should().Be(IdempotentClaim.Claimed); first.Token.Should().NotBeNullOrEmpty(); await AgeAsync("lease-confirm", "m1"); var second = await nodeB.Lease("m1", TimeSpan.FromMinutes(1)); second.Outcome.Should().Be(IdempotentClaim.TakenOver); second.Token.Should().NotBe(first.Token); (await nodeA.Confirm("m1", first.Token, default)).Should().BeFalse("node A's claim was taken over"); (await nodeA.Lease("m1", null)).Outcome.Should().Be(IdempotentClaim.InFlight, "node B's claim is still unconfirmed"); (await nodeB.Confirm("m1", second.Token, default)).Should().BeTrue(); (await nodeA.Lease("m1", null)).Outcome.Should().Be(IdempotentClaim.Confirmed); } [Fact] public async Task Lease_StaleHolderAfterATakeover_ReleasesNothing_TheNewHolderReleases() { var nodeA = CreateRepository("lease-release"); var nodeB = CreateRepository("lease-release"); var first = await nodeA.Lease("m2", TimeSpan.FromMinutes(1)); await AgeAsync("lease-release", "m2"); var second = await nodeB.Lease("m2", TimeSpan.FromMinutes(1)); second.Outcome.Should().Be(IdempotentClaim.TakenOver); (await nodeA.Release("m2", first.Token, default)).Should().BeFalse("node A's claim was taken over"); (await EntryAsync("lease-release", "m2"))!.Props.ClaimId.Should().Be(second.Token, "node B's claim stays"); (await nodeB.Release("m2", second.Token, default)).Should().BeTrue(); (await nodeA.Contains("m2")).Should().BeFalse(); } [Fact] public async Task Lease_EntryWithoutClaimId_IsClaimedAsBefore_AndNoTokenSettlesIt() { // An entry as a 4.7 node, or Add, writes it: no claim id. var repo = CreateRepository("lease-legacy"); (await repo.Add("legacy")).Should().BeTrue(); (await repo.Lease("legacy", TimeSpan.FromMinutes(1))).Should().Be(new IdempotentLease(IdempotentClaim.InFlight, null)); (await repo.Confirm("legacy", Guid.NewGuid().ToString("N"), default)).Should().BeFalse(); (await repo.Release("legacy", Guid.NewGuid().ToString("N"), default)).Should().BeFalse(); (await repo.Contains("legacy")).Should().BeTrue(); await AgeAsync("lease-legacy", "legacy"); var takeover = await repo.Lease("legacy", TimeSpan.FromMinutes(1)); takeover.Outcome.Should().Be(IdempotentClaim.TakenOver, "an abandoned entry without a claim id is taken over as before"); (await EntryAsync("lease-legacy", "legacy"))!.Props.ClaimId.Should().Be(takeover.Token); } [Fact] public async Task Lease_OldNode_UnconditionalConfirmAndRemove_StillWorkOnAClaimWithAnId() { // The rolling upgrade: a 4.8 node holds a claim with an id; a 4.7 node settles the key with the calls it has. var newNode = CreateRepository("lease-rolling"); var oldNode = CreateRepository("lease-rolling"); var held = await newNode.Lease("r1", TimeSpan.FromMinutes(1)); await oldNode.Confirm("r1"); (await newNode.Lease("r1", TimeSpan.FromMinutes(1))).Outcome.Should().Be(IdempotentClaim.Confirmed); (await newNode.Confirm("r1", held.Token, default)).Should().BeTrue("the entry still carries node A's claim id"); var again = await newNode.Lease("r2", TimeSpan.FromMinutes(1)); await oldNode.Remove("r2"); (await newNode.Release("r2", again.Token, default)).Should().BeFalse("the old node removed it already"); } /// Makes the entry of look abandoned: its stamp moves an hour back. private async Task AgeAsync(string processor, string key) { var entry = await EntryAsync(processor, key); entry.Should().NotBeNull(); entry!.Props.CreatedAt = DateTimeOffset.UtcNow.AddHours(-1); await _redb.SaveAsync(entry); } private async Task?> EntryAsync(string processor, string key) { var procName = P(processor); var entries = await _redb.Query() .Where(e => e.MessageKey == key && e.ProcessorName == procName) .ToListAsync(); return entries.SingleOrDefault(); } /// A claim of left unconfirmed an hour ago, as a stopped node leaves it. private async Task SeedAbandonedAsync(RedbIdempotentRepository repository, string processor, string key) { await repository.Contains(key); // syncs the scheme var name = RedbIdempotentRepository.ComposeEntryName(P(processor), key); await _redb.SaveAsync(new RedbObject { name = name, ValueUnique = name, Props = new IdempotentEntryProps { ProcessorName = P(processor), MessageKey = key, CreatedAt = DateTimeOffset.UtcNow.AddHours(-1) }, }); } } /// /// 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."; } }