Path: redb/redb.Tests.Integration/Tests/Base/KeyCacheRepeatTestsBase.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Tests.Integration/Tests/Base/KeyCacheRepeatTestsBase.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// The key cache of a process hands out an id another row already has: the database got rows since this process cached /// its block (a restore of an older backup sets the sequence back, another process takes the same range). The save of a /// new object then fails on the primary key of _objects. It must fail once with the clear error, reset the key /// cache and give the object its id 0 back, so the next save takes a fresh id; on PostgreSQL and SQL Server the primary /// key violation is also a unique violation and was translated as one, the cache kept its stale block and every next /// create failed again. /// /// The restore is reproduced in one database: process A (its own connection string, so its own key cache) takes its /// block, the sequence is set back below it, process B (another connection string) takes the same range and saves. /// The sequence is put back at least to its old top afterwards, so nothing else of the collection meets the range. /// /// public abstract class KeyCacheRepeatTestsBase { /// A Pro service on the test database under a connection string of its own (its own key cache domain). protected abstract ServiceProvider Build(string applicationName); /// The value the sequence handed out last. protected abstract string SequenceTopSql { get; } /// Sets the sequence so that its next value is . protected abstract string SequenceRestartSql(long next); [Fact] public async Task ARestoredRange_TheNextSave_FailsOnceResetsTheCacheAndLeavesTheOtherRows() => await RunAsync(async (a, created) => await a.SaveAsync(created), inCallersTransaction: false); [Fact] public async Task ARestoredRange_TheNextSaveInTheCallersTransaction_FailsOnceAndTheTransactionGoesOn() => await RunAsync(async (a, created) => await a.SaveAsync(created), inCallersTransaction: true); [Fact] public async Task ARestoredRange_TheNextAddNewObjects_FailsOnceResetsTheCacheAndLeavesTheOtherRows() => await RunAsync(async (a, created) => (await a.AddNewObjectsAsync(new[] { created }))[0], inCallersTransaction: false); private async Task RunAsync(Func, Task> create, bool inCallersTransaction) { await using var providerA = Build($"keycache-a-{Guid.NewGuid():N}"); await using var providerB = Build($"keycache-b-{Guid.NewGuid():N}"); var a = providerA.GetRequiredService(); var b = providerB.GetRequiredService(); await a.InitializeAsync(); await a.SyncSchemeAsync(); await b.InitializeAsync(); await b.SyncSchemeAsync(); // A takes its block: the first id of it is handed out, the rest stays in A's cache. var held = (await a.Context.NextObjectIdBatchAsync(1))[0]; var top = await a.Context.ExecuteScalarAsync(SequenceTopSql); top.Should().BeGreaterThan(held, "precondition: A cached a block above the id it took"); var bIds = new List(); long id = 0; try { // The restore: the sequence goes back below A's block, B takes the same range and saves. await a.Context.ExecuteAsync(SequenceRestartSql(held + 1)); for (var i = 0; i < 5; i++) bIds.Add(await b.SaveAsync(new RedbObject { name = $"keycache-b-{i}", Props = new SimpleProps { Title = $"b{i}" } })); bIds.Should().Contain(held + 1, "precondition: B took the ids A holds next"); var created = new RedbObject { name = "keycache-a-new", Props = new SimpleProps { Title = "after the restore" } }; if (inCallersTransaction) { await using var tx = await a.Context.BeginTransactionAsync(); var first = async () => await create(a, created); await first.Should().ThrowAsync().WithMessage("*key cache*restore or an import*"); created.Id.Should().Be(0, "the failed save gives the object its id 0 back"); id = await create(a, created); await tx.CommitAsync(); } else { var first = async () => await create(a, created); await first.Should().ThrowAsync().WithMessage("*key cache*restore or an import*"); created.Id.Should().Be(0, "the failed save gives the object its id 0 back"); id = await create(a, created); } bIds.Should().NotContain(id, "the reset cache takes a fresh range"); (await a.LoadAsync(id))!.Props.Title.Should().Be("after the restore"); for (var i = 0; i < bIds.Count; i++) (await b.LoadAsync(bIds[i]))!.name.Should().Be($"keycache-b-{i}", "B's rows are left as they were"); } finally { var now = await a.Context.ExecuteScalarAsync(SequenceTopSql); await a.Context.ExecuteAsync(SequenceRestartSql(Math.Max(top, now) + 1)); await b.DeleteAsync(id == 0 ? bIds : bIds.Append(id)); } } }