Path: redb-route/tests/redb.Route.Tests.Llm/Storage/RedbToolIdempotencyStoreTests.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.Llm/Storage/RedbToolIdempotencyStoreTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Extensions; using redb.Route.Llm.Storage.Redb; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.RedbCore; using redb.Route.RedbCore.Models; namespace redb.Route.Tests.Llm.Storage; /// /// Integration tests for with no redb name in force: the reservation and the /// cached output are kept together in the context's default redb (the fixture's). /// [Collection("StoragePro")] public sealed class RedbToolIdempotencyStoreTests { private const string ProcessorName = "llm-tool-idempotency"; private readonly StorageProFixture _fx; public RedbToolIdempotencyStoreTests(StorageProFixture fx) => _fx = fx; private RedbToolIdempotencyStore NewStore() => new(_fx.RouteContext); private static async Task> ReservationsIn(IRedbService redb, string key) { var rows = await redb.Query().Where(p => p.MessageKey == key).ToListAsync(); return rows.Select(r => r.Props).ToList(); } [Fact] public async Task Reserve_FirstCall_IsNew() { var store = NewStore(); var convId = $"c-{Guid.NewGuid():N}"; var res = await store.TryReserveAsync(convId, "tu-1"); res.IsNew.Should().BeTrue(); } [Fact] public async Task Reserve_AfterComplete_ReturnsCachedOutput() { var store = NewStore(); var convId = $"c-{Guid.NewGuid():N}"; var first = await store.TryReserveAsync(convId, "tu-2"); first.IsNew.Should().BeTrue(); await store.CompleteAsync(convId, "tu-2", """{"ok":true}"""); var second = await store.TryReserveAsync(convId, "tu-2"); second.IsNew.Should().BeFalse(); second.CachedOutputJson.Should().Be("""{"ok":true}"""); } [Fact] public async Task Release_AllowsRetry() { var store = NewStore(); var convId = $"c-{Guid.NewGuid():N}"; (await store.TryReserveAsync(convId, "tu-3")).IsNew.Should().BeTrue(); await store.ReleaseAsync(convId, "tu-3"); (await store.TryReserveAsync(convId, "tu-3")).IsNew.Should().BeTrue(); } [Fact] public async Task WithoutAName_TheReservationLandsInTheDefaultRedb_NextToTheOutput() { var store = NewStore(); var convId = $"c-{Guid.NewGuid():N}"; var key = $"llm-tool:{convId}:tu-1"; (await store.TryReserveAsync(convId, "tu-1")).IsNew.Should().BeTrue(); await store.CompleteAsync(convId, "tu-1", """{"r":1}"""); var reservation = (await ReservationsIn(_fx.Redb, key)).Should().ContainSingle().Subject; reservation.ProcessorName.Should().Be(ProcessorName); reservation.Confirmed.Should().BeTrue(); var outputs = await _fx.Redb.Query().WhereRedb(x => x.ValueUnique == RedbUniqueKey.Normalize(key)).ToListAsync(); outputs.Should().ContainSingle("the output row is in the same redb as the reservation") .Which.Props.OutputJson.Should().Be("""{"r":1}"""); } [Fact] public async Task ARepeatedCall_AfterTheStoreRestarts_IsAHitWithTheCachedOutput() { var convId = $"c-{Guid.NewGuid():N}"; var before = NewStore(); (await before.TryReserveAsync(convId, "tu-1")).IsNew.Should().BeTrue(); await before.CompleteAsync(convId, "tu-1", """{"sent":true}"""); var after = NewStore(); var again = await after.TryReserveAsync(convId, "tu-1"); again.IsNew.Should().BeFalse("the reservation is kept in redb, not in the process"); again.CachedOutputJson.Should().Be("""{"sent":true}"""); } [Fact] public async Task ParallelReservations_WithoutAName_SingleWin() { var convId = $"c-{Guid.NewGuid():N}"; var stores = Enumerable.Range(0, 8).Select(_ => NewStore()).ToList(); using var start = new ManualResetEventSlim(false); // Each call on an exchange of its own, as the engine makes them: the cached-output lookup of a loser resolves // the exchange's scoped redb, not the context's single instance. var tasks = stores.Select(s => Task.Run(async () => { await using var exchange = new Exchange(new Message(), _fx.ScopeFactory); start.Wait(); return await s.TryReserveAsync(convId, "tu-race", exchange); })).ToList(); start.Set(); var results = await Task.WhenAll(tasks); results.Count(r => r.IsNew).Should().Be(1, "the unique index lets exactly one reservation through"); (await ReservationsIn(_fx.Redb, $"llm-tool:{convId}:tu-race")).Should().ContainSingle(); } [Fact] public async Task AddRedbLlmStorage_Alone_WorksWithNoRepositoryInDi() { var services = new ServiceCollection(); services.AddSingleton(_fx.RouteContext); services.AddRedbLlmStorage(); await using var provider = services.BuildServiceProvider(); var store = provider.GetRequiredService(); var convId = $"c-{Guid.NewGuid():N}"; (await store.TryReserveAsync(convId, "tu-1")).IsNew.Should().BeTrue(); (await store.TryReserveAsync(convId, "tu-1")).IsNew.Should().BeFalse(); } [Fact] public async Task AContextThatCannotOpenARedbScope_FailsWithAMessageNamingAddRedbLlmStorage() { await using var bare = new RouteContext(); var store = new RedbToolIdempotencyStore(bare); var act = () => store.TryReserveAsync($"c-{Guid.NewGuid():N}", "tu-1"); var thrown = await act.Should().ThrowAsync(); thrown.Which.Message.Should().Contain("AddRedbLlmStorage") .And.Contain("default redb") .And.Contain("IRedbService is not registered"); } // ── Calls without an exchange: a scope of their own, never the context's single instance ── [Fact] public async Task ConcurrentReservations_WithoutAnExchange_SingleWin_AndTheLosersReadTheOutputSafely() { var convId = $"c-{Guid.NewGuid():N}"; var stores = Enumerable.Range(0, 8).Select(_ => NewStore()).ToList(); using var start = new ManualResetEventSlim(false); var tasks = stores.Select(s => Task.Run(async () => { start.Wait(); return await s.TryReserveAsync(convId, "tu-race"); })).ToList(); start.Set(); var results = await Task.WhenAll(tasks); results.Count(r => r.IsNew).Should().Be(1, "the unique index lets exactly one reservation through"); (await ReservationsIn(_fx.Redb, $"llm-tool:{convId}:tu-race")).Should().ContainSingle(); } [Fact] public async Task ConcurrentHits_WithoutAnExchange_AllReturnTheStoredOutput() { var convId = $"c-{Guid.NewGuid():N}"; var store = NewStore(); (await store.TryReserveAsync(convId, "tu-1")).IsNew.Should().BeTrue(); await store.CompleteAsync(convId, "tu-1", """{"done":1}"""); using var start = new ManualResetEventSlim(false); var tasks = Enumerable.Range(0, 8).Select(_ => Task.Run(async () => { start.Wait(); return await store.TryReserveAsync(convId, "tu-1"); })).ToList(); start.Set(); var results = await Task.WhenAll(tasks); results.Should().OnlyContain(r => !r.IsNew && r.CachedOutputJson == """{"done":1}"""); } [Fact] public async Task EvalRuns_SavedConcurrentlyWithoutAnExchange_AreAllKept() { var store = new RedbEvalRunStore(_fx.RouteContext); var scenario = $"s-{Guid.NewGuid():N}"; using var start = new ManualResetEventSlim(false); var tasks = Enumerable.Range(0, 8).Select(i => Task.Run(async () => { start.Wait(); await store.SaveAsync(new EvalRunRecord { RunId = $"{scenario}-{i}", Scenario = scenario, AgentFingerprint = "fp" }); })).ToList(); start.Set(); await Task.WhenAll(tasks); (await store.ListAsync(scenario, take: 50)).Should().HaveCount(8); } }