Path: redb-route/tests/redb.Route.Tests.Llm/Storage/NamedRedbRoutingTests.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/NamedRedbRoutingTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Observability; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Extensions; using redb.Route.Processors; using redb.Route.RedbCore.Extensions; using redb.Route.RedbCore.Models; using redb.Route.RedbCore; using redb.Route.RedbCore.Repositories; using redb.Core.Models.Entities; using redb.Route.Llm.Storage.Redb; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.Storage; /// /// The agent's memory in a named redb instance of its own: ?redb= on the endpoint decides for everything the /// endpoint writes, the tool-call audit and the accumulated cost of the conversation included, and nothing lands in the /// default (business) instance. The stores are built as AddRedbLlmStorage() builds them, without a name. /// [Collection("StoragePro")] public sealed class NamedRedbRoutingTests : IClassFixture { private readonly StorageProFixture _fx; private readonly NamedRedbFixture _named; public NamedRedbRoutingTests(StorageProFixture fx, NamedRedbFixture named) { _fx = fx; _named = named; named.AttachTo(fx.RouteContext); } private static EchoToolRoute EchoTool() => new( toolName: "echo", description: "echo back the result", inputSchema: """{"type":"object","properties":{"v":{"type":"number"}}}""", replyJson: """{"r":42}"""); private async Task RunAsync(LiveLlmHost host, FakeProvider fake, string llmUri, string conversationId) { host.Context.AddToRegistry("fake", new LlmConnectionFactory { Name = "fake", Provider = "fake", ModelId = fake.ModelId, PrebuiltProvider = fake }); await host.StartAsync(EchoTool(), r => r.From("direct:agent").To(llmUri).To("mock:done")); await host.SendAsync("direct:agent", "go", new Dictionary { [LlmHeaders.ConversationId] = conversationId }); } private static string AgentUri() => LlmDsl.Factory("fake").Tools("echo").ConversationFromHeader().Budget(inputTokens: 100000).AsUri() + "&redb=" + NamedRedbFixture.Name; [Fact] public async Task The_tool_call_audit_lands_in_the_instance_redb_names() { var conversationId = $"c-{Guid.NewGuid():N}"; var fake = new FakeProvider().EnqueueToolUse("echo", "{\"v\":1}").EnqueueText("done"); await using var host = LiveLlmHost.Build(observer: new RedbAuditObserver(_fx.RouteContext)); await RunAsync(host, fake, AgentUri(), conversationId); var named = await _named.Redb.Query().Where(p => p.ConversationId == conversationId).ToListAsync(); var business = await _fx.Redb.Query().Where(p => p.ConversationId == conversationId).ToListAsync(); named.Should().ContainSingle("the endpoint names the agent's instance"); business.Should().BeEmpty("the tool's input and output must not reach the business database"); } [Fact] public async Task The_conversation_cost_lands_in_the_instance_redb_names() { var conversationId = $"c-{Guid.NewGuid():N}"; var fake = new FakeProvider().EnqueueText("done", tokensIn: 7, tokensOut: 3); await using var host = LiveLlmHost.Build( budget: new StoreBudgetEnforcer(new RedbCostBudgetStore(_fx.RouteContext))); await RunAsync(host, fake, AgentUri(), conversationId); var named = await new RedbCostBudgetStore(_fx.RouteContext, NamedRedbFixture.Name).GetUsageAsync(conversationId); var business = await new RedbCostBudgetStore(_fx.RouteContext).GetUsageAsync(conversationId); named.InputTokens.Should().Be(7, "the endpoint names the agent's instance"); business.InputTokens.Should().Be(0, "nothing of the conversation's cost reaches the business database"); } // ── The registration-level name: AddRedbLlmStorage(name) ── private ServiceProvider StorageRegisteredUnder(string redbName) { var services = new ServiceCollection(); services.AddSingleton(_fx.RouteContext); services.AddRedbLlmStorage(redbName); return services.BuildServiceProvider(); } private static AgentToolInvocationContext ToolCall(string conversationId, string? redbName) => new() { Run = new AgentRunContext { ConversationId = conversationId, FactoryName = "test", ProviderId = "test", ModelId = "test-model", ExchangeId = $"x-{Guid.NewGuid():N}", RedbName = redbName }, Tool = new LlmToolCapability { Name = "echo", Description = "t", InputSchema = "{}" }, InputJson = """{"in":1}""", OutputJson = """{"ok":true}""", ToolUseId = "tu-1", Duration = TimeSpan.FromMilliseconds(5) }; [Fact] public async Task A_registration_name_is_where_the_audit_and_the_cost_go_without_redb_on_the_uri() { await using var sp = StorageRegisteredUnder(NamedRedbFixture.Name); var conversationId = $"c-{Guid.NewGuid():N}"; await sp.GetRequiredService().OnToolInvokedAsync(ToolCall(conversationId, redbName: null)); await sp.GetRequiredService().AddAsync(conversationId, new AgentUsage(5, 1, 0m)); (await _named.Redb.Query().Where(p => p.ConversationId == conversationId).ToListAsync()) .Should().ContainSingle(); (await _fx.Redb.Query().Where(p => p.ConversationId == conversationId).ToListAsync()) .Should().BeEmpty(); (await new RedbCostBudgetStore(_fx.RouteContext, NamedRedbFixture.Name).GetUsageAsync(conversationId)) .InputTokens.Should().Be(5); } [Fact] public async Task Redb_on_the_uri_wins_over_the_registration_name() { // The registration names the business instance; the run names the agent's, and the run decides. _fx.RouteContext.RegisterRedbService("business", _fx.Redb); await using var sp = StorageRegisteredUnder("business"); var conversationId = $"c-{Guid.NewGuid():N}"; await sp.GetRequiredService().OnToolInvokedAsync(ToolCall(conversationId, NamedRedbFixture.Name)); (await _named.Redb.Query().Where(p => p.ConversationId == conversationId).ToListAsync()) .Should().ContainSingle(); (await _fx.Redb.Query().Where(p => p.ConversationId == conversationId).ToListAsync()) .Should().BeEmpty(); } // ── The tool idempotency reservation follows the redb name in force ── private static IExchange ExchangeNaming(string? redbName) { var exchange = new Exchange(new Message(null)); if (redbName is not null) exchange.Properties[LlmKeys.RedbName] = redbName; return exchange; } private async Task> ReservationsIn(IRedbService redb, string conversationId) { var key = $"llm-tool:{conversationId}:tu-1"; var rows = await redb.Query().Where(p => p.MessageKey == key).ToListAsync(); return rows.Select(r => r.Props).ToList(); } [Fact] public async Task The_tool_idempotency_reservation_lands_in_the_instance_redb_names() { var store = new RedbToolIdempotencyStore(_fx.RouteContext); var conversationId = $"c-{Guid.NewGuid():N}"; var exchange = ExchangeNaming(NamedRedbFixture.Name); (await store.TryReserveAsync(conversationId, "tu-1", exchange)).IsNew.Should().BeTrue(); await store.CompleteAsync(conversationId, "tu-1", """{"r":1}""", exchange); var again = await store.TryReserveAsync(conversationId, "tu-1", exchange); again.IsNew.Should().BeFalse("the named instance holds the confirmed reservation"); again.CachedOutputJson.Should().Be("""{"r":1}"""); (await ReservationsIn(_named.Redb, conversationId)).Should().ContainSingle().Which.Confirmed.Should().BeTrue(); (await ReservationsIn(_fx.Redb, conversationId)).Should().BeEmpty( "a redb name is in force, so the reservation does not go to the default redb"); } [Fact] public async Task A_registration_name_is_where_the_reservation_goes_without_redb_on_the_uri() { var store = new RedbToolIdempotencyStore(_fx.RouteContext, NamedRedbFixture.Name); var conversationId = $"c-{Guid.NewGuid():N}"; (await store.TryReserveAsync(conversationId, "tu-1", ExchangeNaming(null))).IsNew.Should().BeTrue(); (await ReservationsIn(_named.Redb, conversationId)).Should().ContainSingle(); (await ReservationsIn(_fx.Redb, conversationId)).Should().BeEmpty(); } [Fact] public async Task Without_a_redb_name_the_reservation_lands_in_the_default_redb() { var store = new RedbToolIdempotencyStore(_fx.RouteContext); var conversationId = $"c-{Guid.NewGuid():N}"; (await store.TryReserveAsync(conversationId, "tu-1", ExchangeNaming(null))).IsNew.Should().BeTrue(); (await ReservationsIn(_fx.Redb, conversationId)).Should().ContainSingle() .Which.ProcessorName.Should().Be("llm-tool-idempotency"); (await ReservationsIn(_named.Redb, conversationId)).Should().BeEmpty(); } [Fact] public async Task Rows_the_named_path_wrote_before_are_still_found() { // What the named path has written since it moved there: an entry of the redb.Route idempotent repository with // processor name llm-tool-idempotency over the named instance, and the output row beside it. var conversationId = $"c-{Guid.NewGuid():N}"; var key = $"llm-tool:{conversationId}:tu-1"; var earlier = new RedbIdempotentRepository( () => _fx.RouteContext.CreateRedbScope(NamedRedbFixture.Name), new RedbIdempotentOptions { ProcessorName = "llm-tool-idempotency" }); (await earlier.Add(key)).Should().BeTrue(); await earlier.Confirm(key); await _named.Redb.SaveAsync(new RedbObject { value_string = key, ValueUnique = RedbUniqueKey.Normalize(key), Props = new ToolIdempotencyProps { OutputJson = """{"earlier":true}""", CreatedAtUtc = DateTimeOffset.UtcNow } }); var store = new RedbToolIdempotencyStore(_fx.RouteContext, NamedRedbFixture.Name); var again = await store.TryReserveAsync(conversationId, "tu-1", ExchangeNaming(null)); again.IsNew.Should().BeFalse("the earlier reservation is found under the same processor name and key"); again.CachedOutputJson.Should().Be("""{"earlier":true}"""); } }