Bundle: redb-route / tests/redb.Route.Tests.Llm (tests.redb.Route.Tests.Llm.txt), 102 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/tests/redb.Route.Tests.Llm/AgentEngineThinkingTests.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/AgentEngineThinkingTests.cs ---- using redb.Route.Llm.Engine.Storage; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm; /// /// A thinking block travels through the run and reaches the conversation record in the block's own /// field, with its signature, never as text. It is not an answer: it never reaches /// AgentResponse.Text or Out.Body. /// /// Every turn is written, including a turn the model spent entirely on thinking: the record keeps what /// happened (the thought, the usage, the stop reason). Whether such a turn is sent back to a provider /// is a request-shape question, answered by the provider request tests. /// /// public sealed class AgentEngineThinkingTests { private static AgentEngine Engine(IConversationStore? conversation = null) => new( logger: null, producerTemplate: null, observer: null, budget: null, approval: null, redaction: null, shadow: null, conversation: conversation, idempotency: null, approvalStore: null); private static LlmConnectionFactory Factory(FakeProvider provider) => new() { Provider = "fake", ModelId = provider.ModelId, PrebuiltProvider = provider }; private static LlmResponse Reply(LlmStopReason stop, params LlmContentBlock[] blocks) => new() { Content = blocks, StopReason = stop, Usage = new LlmUsage(3, 4) }; [Fact] public async Task ThinkingBlock_IsAppendedToConversation() { var store = new InMemoryConversationStore(); var provider = new FakeProvider().Enqueue(Reply(LlmStopReason.EndTurn, new LlmThinkingBlock("hidden chain of thought", "sig-1"), new LlmTextBlock("shipped"))); var response = await Engine(store).RunAsync(new AgentRequest { Factory = Factory(provider), Exchange = new Exchange(new Message("status of order 42?")), UserContent = [new LlmTextBlock("status of order 42?")], ConversationId = "conv-thinking" }); // The run itself keeps the block — that is what makes the next iteration of a tool loop work. response.Content.OfType().Should().ContainSingle(); var path = await store.LoadPathAsync("conv-thinking"); path.Should().HaveCount(2, "the prompt and the answer; a thinking block is not a third message"); // The record holds the block with its turn: the schema has a field for the thought and for the // signature. var stored = path[^1].Message.Content.OfType().Should().ContainSingle().Subject; stored.Text.Should().Be("hidden chain of thought"); stored.Signature.Should().Be("sig-1"); path[^1].Message.Content.OfType().Should().ContainSingle().Which.Text.Should().Be("shipped"); } [Fact] public async Task TurnWithNothingButThinking_IsWritten() { var store = new InMemoryConversationStore(); // The model spent the whole turn thinking and ran out of tokens before saying anything. The // turn is still part of what happened: its row carries the thought, the tokens it cost and the // stop reason that explains the empty answer. var provider = new FakeProvider().Enqueue(Reply(LlmStopReason.MaxTokens, new LlmThinkingBlock("still thinking"))); await Engine(store).RunAsync(new AgentRequest { Factory = Factory(provider), Exchange = new Exchange(new Message("status?")), UserContent = [new LlmTextBlock("status?")], ConversationId = "conv-silent" }); var path = await store.LoadPathAsync("conv-silent"); path.Should().HaveCount(2, "the prompt and the turn that was nothing but thinking"); var turn = path[1]; turn.Message.Role.Should().Be("assistant"); turn.Message.Content.Should().ContainSingle() .Which.Should().BeOfType().Which.Text.Should().Be("still thinking"); turn.Meta.StopReason.Should().Be(LlmStopReason.MaxTokens); turn.Meta.Usage.OutputTokens.Should().Be(4, "the tokens the turn cost are recorded with it"); } [Fact] public async Task VisibleAnswer_DoesNotContainThinkingText() { const string Secret = "SECRET chain of thought"; var provider = new FakeProvider(); for (var i = 0; i < 2; i++) provider.Enqueue(Reply(LlmStopReason.EndTurn, new LlmThinkingBlock(Secret), new LlmTextBlock("shipped"))); var response = await Engine().RunAsync(new AgentRequest { Factory = Factory(provider), Exchange = new Exchange(new Message("status?")), UserContent = [new LlmTextBlock("status?")] }); response.Text.Should().Be("shipped", "the answer is the text block, not the block that came first"); response.Text.Should().NotContain(Secret); // The same invariant at the edge of a route: what a caller reads is the answer. var ctx = new RouteContext(); var component = new LlmComponent(); ctx.AddComponent(component); ctx.AddToRegistry("fake", Factory(provider)); ctx.AddService(typeof(IAgentEngine), new AgentEngine()); var endpoint = (LlmEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("llm://fake")); var producer = (LlmProducer)endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("status?")); await producer.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().Be("shipped"); exchange.Out.Body!.ToString().Should().NotContain(Secret); } } Path: redb-route/tests/redb.Route.Tests.Llm/AnthropicModelProfileTests.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/AnthropicModelProfileTests.cs ---- namespace redb.Route.Tests.Llm; /// /// Classification of Anthropic model ids into contract tiers. The tier decides whether /// the sampling knobs (temperature/top_p) may be sent — current-generation models reject /// them with HTTP 400, so an unrecognised id must fail forward to Modern. /// public sealed class AnthropicModelProfileTests { [Theory] // Current generation — sampling removed (HTTP 400 if sent). [InlineData("claude-opus-5", AnthropicModelTier.Modern)] [InlineData("claude-sonnet-5", AnthropicModelTier.Modern)] [InlineData("claude-fable-5", AnthropicModelTier.Modern)] [InlineData("claude-opus-4-8", AnthropicModelTier.Modern)] [InlineData("claude-opus-4-7", AnthropicModelTier.Modern)] [InlineData("claude-opus-4-8-20251001", AnthropicModelTier.Modern)] // date snapshot suffix // Transitional — sampling still accepted. [InlineData("claude-opus-4-6", AnthropicModelTier.Transitional)] [InlineData("claude-sonnet-4-6", AnthropicModelTier.Transitional)] // Legacy — sampling accepted. [InlineData("claude-sonnet-4-5", AnthropicModelTier.Legacy)] [InlineData("claude-haiku-4-5", AnthropicModelTier.Legacy)] [InlineData("claude-haiku-4.5", AnthropicModelTier.Legacy)] // dot separator [InlineData("claude-3-7-sonnet-20250219", AnthropicModelTier.Legacy)] [InlineData("claude-3-5-sonnet-20241022", AnthropicModelTier.Legacy)] // Unknown / future id — fail forward to Modern (never send a now-removed field). [InlineData("claude-something-new", AnthropicModelTier.Modern)] [InlineData("", AnthropicModelTier.Modern)] public void Resolve_ClassifiesByGeneration(string modelId, AnthropicModelTier expected) { AnthropicModelProfile.Resolve(modelId).Tier.Should().Be(expected); } [Theory] // The sampling contract is three-state, not binary — 4.0–4.6 accept ONE knob. [InlineData("claude-opus-5", AnthropicSamplingPolicy.None)] [InlineData("claude-sonnet-5", AnthropicSamplingPolicy.None)] [InlineData("claude-opus-4-8", AnthropicSamplingPolicy.None)] [InlineData("claude-opus-4-7", AnthropicSamplingPolicy.None)] [InlineData("claude-opus-4-6", AnthropicSamplingPolicy.AtMostOne)] [InlineData("claude-sonnet-4-6", AnthropicSamplingPolicy.AtMostOne)] [InlineData("claude-sonnet-4-5", AnthropicSamplingPolicy.AtMostOne)] [InlineData("claude-haiku-4-5", AnthropicSamplingPolicy.AtMostOne)] [InlineData("claude-3-5-sonnet-20241022", AnthropicSamplingPolicy.Both)] [InlineData("claude-3-opus-20240229", AnthropicSamplingPolicy.Both)] [InlineData("claude-something-new", AnthropicSamplingPolicy.None)] public void Resolve_ClassifiesSamplingPolicy(string modelId, AnthropicSamplingPolicy expected) { AnthropicModelProfile.Resolve(modelId).Sampling.Should().Be(expected); } [Theory] [InlineData(AnthropicSamplingPolicy.None, false)] [InlineData(AnthropicSamplingPolicy.AtMostOne, true)] [InlineData(AnthropicSamplingPolicy.Both, true)] public void SamplingSupported_MatchesPolicy(AnthropicSamplingPolicy policy, bool expected) { new AnthropicModelProfile(AnthropicModelTier.Legacy, policy).SamplingSupported.Should().Be(expected); } [Theory] [InlineData("legacy", AnthropicModelTier.Legacy)] [InlineData("Transitional", AnthropicModelTier.Transitional)] [InlineData("MODERN", AnthropicModelTier.Modern)] public void Resolve_TierOverride_WinsOverModelId(string tierOverride, AnthropicModelTier expected) { // A modern id that would classify as Modern, forced to another tier by override. AnthropicModelProfile.Resolve("claude-opus-5", tierOverride).Tier.Should().Be(expected); } [Fact] public void Resolve_UnknownOverride_FallsBackToModelClassification() { AnthropicModelProfile.Resolve("claude-haiku-4-5", "nonsense").Tier .Should().Be(AnthropicModelTier.Legacy); } } Path: redb-route/tests/redb.Route.Tests.Llm/AnthropicProviderRequestTests.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/AnthropicProviderRequestTests.cs ---- using System.Net; using System.Text.Json.Nodes; namespace redb.Route.Tests.Llm; /// /// Verifies the shape of the outgoing Anthropic request body — in particular that the /// sampling knobs (temperature/top_p) are emitted only for models whose contract accepts /// them. Current-generation models reject those fields with HTTP 400, so a configured /// Temperature pointed at a modern model must NOT appear on the wire. /// public sealed class AnthropicProviderRequestTests { /// Captures the JSON body of the last request and returns a canned Anthropic reply. private sealed class CapturingHandler : HttpMessageHandler { public JsonObject? LastBody { get; private set; } public Version? LastVersion { get; private set; } public HttpVersionPolicy? LastVersionPolicy { get; private set; } protected override async Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { var raw = await request.Content!.ReadAsStringAsync(cancellationToken); LastBody = JsonNode.Parse(raw) as JsonObject; LastVersion = request.Version; LastVersionPolicy = request.VersionPolicy; return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent( """ {"id":"msg_1","content":[{"type":"text","text":"ok"}], "stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}} """) }; } } private static async Task CaptureBodyAsync( string modelId, double? temperature, double? topP, string? tierOverride = null, string? requestModelId = null) { var handler = new CapturingHandler(); var factory = new LlmConnectionFactory { Provider = "anthropic", ModelId = modelId, ApiKey = "test-key", ModelContractTier = tierOverride }; var provider = new AnthropicProvider(factory, new HttpClient(handler)); await provider.CompleteAsync(new LlmRequest { ModelId = requestModelId, Messages = [LlmMessage.User("hi")], Temperature = temperature, TopP = topP }); return handler.LastBody!; } [Fact] public async Task SystemPrompt_IsAPlainString_UntilCachingIsAskedFor() { var handler = new CapturingHandler(); var provider = new AnthropicProvider( new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-4-6", ApiKey = "k" }, new HttpClient(handler)); await provider.CompleteAsync(new LlmRequest { SystemPrompt = "constitution", Messages = [LlmMessage.User("hi")], }); // Default shape unchanged: a bare string. Switching everyone to the block form would be a // silent wire change for callers who never asked for caching. handler.LastBody!["system"]!.GetValue().Should().Be("constitution"); (handler.LastBody!["system"] is System.Text.Json.Nodes.JsonArray).Should().BeFalse(); } [Fact] public async Task CacheSystemPrompt_EmitsTheBlockFormWithCacheControl() { var handler = new CapturingHandler(); var provider = new AnthropicProvider( new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-4-6", ApiKey = "k" }, new HttpClient(handler)); await provider.CompleteAsync(new LlmRequest { SystemPrompt = "constitution", CacheSystemPrompt = true, Messages = [LlmMessage.User("hi")], }); // cache_control is a property OF a content block — a bare string has nowhere to hang it, // so asking for caching necessarily switches the shape. var system = handler.LastBody!["system"]!.AsArray(); system.Count.Should().Be(1); system[0]!["type"]!.GetValue().Should().Be("text"); system[0]!["text"]!.GetValue().Should().Be("constitution"); system[0]!["cache_control"]!["type"]!.GetValue().Should().Be("ephemeral"); } [Fact] public async Task CacheBreakpoint_OnAMessage_MarksItsLastBlock_AndNothingElse() { var handler = new CapturingHandler(); var provider = new AnthropicProvider( new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-4-6", ApiKey = "k" }, new HttpClient(handler)); await provider.CompleteAsync(new LlmRequest { SystemPrompt = "constitution", CacheSystemPrompt = true, Messages = [ LlmMessage.User("read it?"), new LlmMessage { Role = "assistant", Content = [new LlmTextBlock("part one"), new LlmTextBlock("part two")], CacheBreakpoint = true }, LlmMessage.User("hi"), ], }); var messages = handler.LastBody!["messages"]!.AsArray(); messages.Count.Should().Be(3); // The breakpoint sits on the LAST block of the marked message — the cached prefix runs up // to it inclusive — and on no other block of any other message. var marked = messages[1]!["content"]!.AsArray(); marked.Count.Should().Be(2); marked[0]!.AsObject().ContainsKey("cache_control").Should().BeFalse(); marked[1]!["cache_control"]!["type"]!.GetValue().Should().Be("ephemeral"); messages[0]!["content"]!.AsArray()[0]!.AsObject().ContainsKey("cache_control").Should().BeFalse(); messages[2]!["content"]!.AsArray()[0]!.AsObject().ContainsKey("cache_control").Should().BeFalse(); // Two breakpoints in the request: system and the marked message. Anthropic allows four. handler.LastBody!["system"]!.AsArray()[0]!["cache_control"].Should().NotBeNull(); } [Fact] public async Task ModernModel_DropsSamplingKnobs() { // The bug: connector sent temperature/top_p to a modern model → HTTP 400. var body = await CaptureBodyAsync("claude-opus-4-8", temperature: 0.7, topP: 0.9); body.ContainsKey("temperature").Should().BeFalse("modern models reject temperature (400)"); body.ContainsKey("top_p").Should().BeFalse("modern models reject top_p (400)"); } [Fact] public async Task Claude3_KeepsBothSamplingKnobs() { // Claude 3.x is the only generation that accepts temperature AND top_p together. var body = await CaptureBodyAsync("claude-3-5-sonnet-20241022", temperature: 0.5, topP: 0.8); body["temperature"]!.GetValue().Should().Be(0.5); body["top_p"]!.GetValue().Should().Be(0.8); } [Fact] public async Task Claude4x_WithBothKnobs_KeepsOnlyTemperature() { // Claude 4.0–4.6 reject temperature+top_p together (400); keep temperature, drop top_p. var body = await CaptureBodyAsync("claude-sonnet-4-6", temperature: 0.5, topP: 0.8); body["temperature"]!.GetValue().Should().Be(0.5); body.ContainsKey("top_p").Should().BeFalse("Claude 4.x accepts at most one sampling knob"); } [Fact] public async Task Claude4x_WithOnlyTopP_KeepsTopP() { var body = await CaptureBodyAsync("claude-haiku-4-5", temperature: null, topP: 0.8); body["top_p"]!.GetValue().Should().Be(0.8); body.ContainsKey("temperature").Should().BeFalse(); } [Fact] public async Task TierOverride_ForcesLegacyOnModernId() { var body = await CaptureBodyAsync("claude-opus-5", temperature: 0.3, topP: null, tierOverride: "legacy"); body["temperature"]!.GetValue().Should().Be(0.3); } [Fact] public async Task PerRequestModelOverride_IsClassifiedFresh() { // Factory is a legacy model (cached profile → sampling allowed), but the request // overrides to a modern id — the per-request resolve must win and drop sampling. var body = await CaptureBodyAsync( "claude-haiku-4-5", temperature: 0.5, topP: null, requestModelId: "claude-opus-4-8"); body["model"]!.GetValue().Should().Be("claude-opus-4-8"); body.ContainsKey("temperature").Should().BeFalse("the overridden modern model rejects sampling"); } [Fact] public async Task ModernModel_WithoutSampling_StillWorks() { var body = await CaptureBodyAsync("claude-opus-4-8", temperature: null, topP: null); body.ContainsKey("temperature").Should().BeFalse(); body["model"]!.GetValue().Should().Be("claude-opus-4-8"); } [Fact] public void DefaultTransport_UsesHttp2_WithKeepAlivePings() { // A non-streaming completion is tens of seconds of silence on the wire, and tunnels/NATs cut // a silent TLS connection at ~50 s. PING frames while the request is in flight are what keeps // a long answer alive — and they need HTTP/2 to exist at all. The delay must stay well under // the ~50 s cut so at least one ping always lands before it. var handler = AnthropicProvider.BuildDefaultHandler(); handler.KeepAlivePingPolicy.Should().Be(HttpKeepAlivePingPolicy.WithActiveRequests); handler.KeepAlivePingDelay.Should().BeGreaterThan(TimeSpan.Zero).And.BeLessThan(TimeSpan.FromSeconds(30)); handler.KeepAlivePingTimeout.Should().BeGreaterThan(TimeSpan.Zero); using var client = AnthropicProvider.BuildDefaultClient(new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-opus-4-8", ApiKey = "sk-test", RequestTimeoutMs = 90_000, }); client.DefaultRequestVersion.Should().Be(System.Net.HttpVersion.Version20); client.DefaultVersionPolicy.Should().Be(HttpVersionPolicy.RequestVersionOrLower, "HTTP/1.1 must stay the fallback"); client.Timeout.Should().Be(Timeout.InfiniteTimeSpan, "RequestTimeoutMs limits the whole call and is applied per call; the client's own Timeout would stop at the headers"); } [Fact] public async Task Request_CarriesTheClientsHttpVersion() { // HttpClient.DefaultRequestVersion never touches a hand-built HttpRequestMessage — it // starts at HTTP/1.1 regardless. The provider builds its own messages, so it must copy // the client's defaults onto them, or the HTTP/2 keep-alive pings silently never happen. var handler = new CapturingHandler(); var client = new HttpClient(handler) { DefaultRequestVersion = HttpVersion.Version20, DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower, }; var provider = new AnthropicProvider(new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-opus-4-8", ApiKey = "test-key", }, client); await provider.CompleteAsync(new LlmRequest { Messages = [LlmMessage.User("hi")] }); handler.LastVersion.Should().Be(HttpVersion.Version20); handler.LastVersionPolicy.Should().Be(HttpVersionPolicy.RequestVersionOrLower); } [Fact] public async Task EmptyMessages_AreSkipped_NotSentAsEmptyTextBlocks() { // One assistant reply with no text (the model spent max_tokens on thinking) used to be // rendered as {"type":"text","text":""}, which the API rejects with 400 — and since the // reply was persisted, EVERY later call of that conversation failed. Empty and // whitespace-only messages must simply not be sent; consecutive same-role turns are fine. var handler = new CapturingHandler(); var provider = new AnthropicProvider(new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-opus-4-8", ApiKey = "test-key", }, new HttpClient(handler)); await provider.CompleteAsync(new LlmRequest { Messages = [ LlmMessage.User("первый вопрос"), new LlmMessage { Role = "assistant", Content = [new LlmTextBlock(string.Empty)] }, LlmMessage.User("второй вопрос"), new LlmMessage { Role = "assistant", Content = [new LlmTextBlock(" ")] }, new LlmMessage { Role = "assistant", Content = [] }, LlmMessage.User("третий вопрос"), ], }); var messages = handler.LastBody!["messages"]!.AsArray(); messages.Count.Should().Be(3, "the three empty assistant replies are not sent"); messages.Should().OnlyContain(m => m!["role"]!.GetValue() == "user"); foreach (var message in messages) foreach (var block in message!["content"]!.AsArray()) if (block!["type"]!.GetValue() == "text") block["text"]!.GetValue().Should().NotBeNullOrWhiteSpace(); } [Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] public async Task Effort_Unset_SendsNoOutputConfig(string? effort) { var handler = new CapturingHandler(); var provider = new AnthropicProvider(new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-5", ApiKey = "test-key", Effort = effort, }, new HttpClient(handler)); await provider.CompleteAsync(new LlmRequest { Messages = [LlmMessage.User("hi")] }); handler.LastBody!.ContainsKey("output_config").Should().BeFalse("the provider's default effort must stay the provider's"); } [Fact] public async Task Effort_Set_GoesInsideOutputConfig() { // Thinking tokens count against max_tokens; at the default (high) effort Sonnet 5 spent // all 4096 on thinking and answered with nothing. The knob lives in output_config, not // top-level, and is sent only for the factory that asked for it. var handler = new CapturingHandler(); var provider = new AnthropicProvider(new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-5", ApiKey = "test-key", Effort = " medium ", }, new HttpClient(handler)); await provider.CompleteAsync(new LlmRequest { Messages = [LlmMessage.User("hi")] }); handler.LastBody!["output_config"]!["effort"]!.GetValue().Should().Be("medium"); handler.LastBody!.ContainsKey("effort").Should().BeFalse("effort is not a top-level field"); } /// /// Captures the body of every request and answers with the scripted body per call — the second /// request is the one under test, so one canned reply is not enough. /// private sealed class ScriptedHandler : HttpMessageHandler { private readonly string[] _bodies; private int _calls; public ScriptedHandler(params string[] bodies) => _bodies = bodies; public List Bodies { get; } = []; protected override async Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { Bodies.Add(JsonNode.Parse(await request.Content!.ReadAsStringAsync(cancellationToken))!.AsObject()); var body = _bodies[Math.Min(_calls++, _bodies.Length - 1)]; return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body) }; } } private static LlmToolCapability LookupTool() => new() { Name = "order_lookup", Description = "Look up an order by id.", InputSchema = """{"type":"object","properties":{"orderId":{"type":"string"}},"required":["orderId"]}""" }; [Fact] public async Task Anthropic_SecondRequest_CarriesSignedThinkingBlock() { // The model thinks, then asks for a tool. The thinking it produced comes back signed, and // the API verifies that signature: the block has to travel on untouched, in the order the // API issued it, or the second call of a tool loop is rejected with 400. var handler = new ScriptedHandler( """ {"id":"msg_1","content":[ {"type":"thinking","thinking":"the user wants an order status","signature":"sig-abc"}, {"type":"text","text":"let me look"}, {"type":"tool_use","id":"tu_1","name":"order_lookup","input":{"orderId":"42"}}], "stop_reason":"tool_use","usage":{"input_tokens":10,"output_tokens":5}} """); var provider = new AnthropicProvider( new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-4-6", ApiKey = "test-key" }, new HttpClient(handler)); var first = await provider.CompleteAsync(new LlmRequest { Messages = [LlmMessage.User("what is the status of order 42?")], Tools = [LookupTool()] }); var thinking = first.Content.OfType().Should().ContainSingle( "the thinking block is parsed as a block of its own").Which; thinking.Text.Should().Be("the user wants an order status"); thinking.Signature.Should().Be("sig-abc"); // Thinking is not the answer: the visible text is what the model said afterwards. first.Content.OfType().Should().ContainSingle().Which.Text.Should().Be("let me look"); // Second call of the same run: history + the tool result. await provider.CompleteAsync(new LlmRequest { Messages = [ LlmMessage.User("what is the status of order 42?"), new LlmMessage { Role = "assistant", Content = first.Content }, new LlmMessage { Role = "user", Content = [new LlmToolResultBlock("tu_1", """{"status":"shipped"}""")] } ], Tools = [LookupTool()] }); var sent = handler.Bodies[1]["messages"]!.AsArray()[1]!["content"]!.AsArray(); sent.Should().HaveCount(3); sent[0]!["type"]!.GetValue().Should().Be("thinking"); sent[0]!["thinking"]!.GetValue().Should().Be("the user wants an order status"); sent[0]!["signature"]!.GetValue().Should().Be("sig-abc"); sent[1]!["type"]!.GetValue().Should().Be("text"); sent[2]!["type"]!.GetValue().Should().Be("tool_use"); } [Fact] public async Task Anthropic_RedactedAndOmittedThinking_GoBackVerbatim() { // Two shapes the signed-block test does not cover. With display "omitted" (the default on // models that think on their own) the thinking text is empty and the signature is what // travels; a redacted_thinking block carries an encrypted payload in "data" and no text. Both // must come back field for field, or the API cannot verify them. var handler = new ScriptedHandler( """ {"id":"msg_1","content":[ {"type":"thinking","thinking":"","signature":"sig-omitted"}, {"type":"redacted_thinking","data":"EncryptedPayload=="}, {"type":"tool_use","id":"tu_1","name":"order_lookup","input":{"orderId":"42"}}], "stop_reason":"tool_use","usage":{"input_tokens":10,"output_tokens":5}} """); var provider = new AnthropicProvider( new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-5", ApiKey = "test-key" }, new HttpClient(handler)); var first = await provider.CompleteAsync(new LlmRequest { Messages = [LlmMessage.User("what is the status of order 42?")], Tools = [LookupTool()] }); var parsed = first.Content.OfType().ToList(); parsed.Should().HaveCount(2); parsed[0].Text.Should().BeEmpty(); parsed[0].Signature.Should().Be("sig-omitted"); parsed[1].IsRedacted.Should().BeTrue(); parsed[1].RedactedData.Should().Be("EncryptedPayload=="); await provider.CompleteAsync(new LlmRequest { Messages = [ LlmMessage.User("what is the status of order 42?"), new LlmMessage { Role = "assistant", Content = first.Content }, new LlmMessage { Role = "user", Content = [new LlmToolResultBlock("tu_1", """{"status":"shipped"}""")] } ], Tools = [LookupTool()] }); var sent = handler.Bodies[1]["messages"]!.AsArray()[1]!["content"]!.AsArray(); sent.Should().HaveCount(3); var omitted = sent[0]!.AsObject(); omitted.Count.Should().Be(3, "type, thinking and signature, nothing added"); omitted["type"]!.GetValue().Should().Be("thinking"); omitted["thinking"]!.GetValue().Should().BeEmpty(); omitted["signature"]!.GetValue().Should().Be("sig-omitted"); var redacted = sent[1]!.AsObject(); redacted.Count.Should().Be(2, "type and data: a redacted block has no text to send"); redacted["type"]!.GetValue().Should().Be("redacted_thinking"); redacted["data"]!.GetValue().Should().Be("EncryptedPayload=="); sent[2]!["type"]!.GetValue().Should().Be("tool_use"); } [Fact] public async Task UnsignedThinkingBlock_HasNoAnthropicForm_IsNotSent() { // A conversation continued here after a provider switch can carry unsigned blocks (DeepSeek // reasoning_content). The Anthropic wire has no form for them: a thinking block without a // signature is a 400. So the block is not written into the request, and the rest of the turn // goes on unchanged. var handler = new CapturingHandler(); var provider = new AnthropicProvider( new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-5", ApiKey = "test-key" }, new HttpClient(handler)); await provider.CompleteAsync(new LlmRequest { Messages = [ LlmMessage.User("status of order 42?"), new LlmMessage { Role = "assistant", Content = [new LlmThinkingBlock("deepseek reasoning"), new LlmTextBlock("shipped")] }, LlmMessage.User("and order 43?") ] }); var messages = handler.LastBody!["messages"]!.AsArray(); messages.Count.Should().Be(3, "the turn itself is sent"); var turn = messages[1]!["content"]!.AsArray(); turn.Count.Should().Be(1, "only the text: an unsigned thinking block has no Anthropic form"); turn[0]!["type"]!.GetValue().Should().Be("text"); turn[0]!["text"]!.GetValue().Should().Be("shipped"); } [Fact] public async Task ThinkingOnlyTurn_IsNotSent() { // The model spent the whole turn thinking and said nothing. The turn is kept in the record, but // a message with no text and no tool call has nothing to continue from, and sending it would // put a message the API may refuse into every later request of the conversation (the class of // 2026-09-07). Signed and redacted alike: the turn is left out of the request. var handler = new CapturingHandler(); var provider = new AnthropicProvider( new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-5", ApiKey = "test-key" }, new HttpClient(handler)); await provider.CompleteAsync(new LlmRequest { Messages = [ LlmMessage.User("status of order 42?"), new LlmMessage { Role = "assistant", Content = [new LlmThinkingBlock("ran out of tokens", "sig-1")] }, LlmMessage.User("and now?"), new LlmMessage { Role = "assistant", Content = [new LlmThinkingBlock(string.Empty, RedactedData: "opaque")] }, LlmMessage.User("still there?") ] }); var messages = handler.LastBody!["messages"]!.AsArray(); messages.Count.Should().Be(3, "the two turns of nothing but thinking are not sent"); messages.Should().OnlyContain(m => m!["role"]!.GetValue() == "user"); } [Fact] public async Task OldHistory_WithoutThinkingBlocks_RequestShapeIsRecorded() { // A conversation written before phase 16 carries text only. Nothing new may appear on the // wire for it: no thinking block, no empty text block, no top-level thinking knob. Whether // an old history is ACCEPTED is what the 16.0a live probe answers — a unit test can only // pin the shape we send. var handler = new ScriptedHandler( """ {"id":"msg_1","content":[{"type":"text","text":"ok"}], "stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}} """); var provider = new AnthropicProvider( new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-4-6", ApiKey = "test-key" }, new HttpClient(handler)); await provider.CompleteAsync(new LlmRequest { Messages = [ LlmMessage.User("hi"), LlmMessage.Assistant("hello"), LlmMessage.User("and now?") ] }); var body = handler.Bodies[0]; body.ContainsKey("thinking").Should().BeFalse("we do not ask the model to think; that is decision 15"); var messages = body["messages"]!.AsArray(); messages.Should().HaveCount(3, "three non-empty turns, nothing added and nothing dropped"); messages[1]!["content"]!.AsArray().Should().HaveCount(1, "no thinking block, no empty text block"); messages[1]!["content"]!.AsArray()[0]!["type"]!.GetValue().Should().Be("text"); messages[1]!["content"]!.AsArray()[0]!["text"]!.GetValue().Should().Be("hello"); } } Path: redb-route/tests/redb.Route.Tests.Llm/CachedPromptUsageTests.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/CachedPromptUsageTests.cs ---- using System.Net; using System.Text; namespace redb.Route.Tests.Llm; /// /// A prompt served from the provider's cache reaches on the OpenAI-compatible path too /// (issue #11). LlmUsage.InputTokens is the uncached remainder, not the whole prompt, so the cached part is /// taken out of it: a cost calculator or an audit built on these numbers would otherwise bill a cached prefix at full /// price. DeepSeek reports the split in its own fields, OpenAI in prompt_tokens_details; both mean the same. /// public sealed class CachedPromptUsageTests { private sealed class FixedHandler(string body, string mediaType) : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body, Encoding.UTF8, mediaType) }); } private static OpenAiProvider Provider(string body, string mediaType = "application/json") => new(new LlmConnectionFactory { Provider = "deepseek", ModelId = "deepseek-v4-pro", ApiKey = "sk-test" }, new HttpClient(new FixedHandler(body, mediaType))); private static LlmRequest Request() => new() { Messages = [LlmMessage.User("hi")] }; private static string Answer(string usage) => $$""" {"id":"chatcmpl-1","choices":[{"index":0,"message":{"role":"assistant","content":"done"},"finish_reason":"stop"}],"usage":{{usage}}} """; [Fact] public async Task DeepSeek_CachedPrefix_ReachesUsage() { // The numbers of the report: a ~170k system field served from cache, 63 tokens of it new. DeepSeek fills its // own pair and leaves the OpenAI-shaped cached_tokens at zero, so the zero must not win. var provider = Provider(Answer(""" {"prompt_tokens":172095,"completion_tokens":11,"total_tokens":172106, "prompt_tokens_details":{"cached_tokens":0}, "prompt_cache_hit_tokens":172032,"prompt_cache_miss_tokens":63} """)); var usage = (await provider.CompleteAsync(Request())).Usage; usage.CacheReadInputTokens.Should().Be(172032, "this is the number that says caching works"); usage.InputTokens.Should().Be(63, "InputTokens is what was billed at full price, not the whole prompt"); usage.CacheCreationInputTokens.Should().Be(0, "DeepSeek does not bill cache creation separately"); usage.OutputTokens.Should().Be(11); } [Fact] public async Task OpenAi_CachedPrefix_ReachesUsage() { var provider = Provider(Answer(""" {"prompt_tokens":1000,"completion_tokens":20,"prompt_tokens_details":{"cached_tokens":896}} """)); var usage = (await provider.CompleteAsync(Request())).Usage; usage.CacheReadInputTokens.Should().Be(896); usage.InputTokens.Should().Be(104, "the prompt minus what came from cache"); } [Fact] public async Task WithoutCacheFields_TheWholePromptIsInput() { var provider = Provider(Answer("""{"prompt_tokens":38,"completion_tokens":5,"total_tokens":43}""")); var usage = (await provider.CompleteAsync(Request())).Usage; usage.InputTokens.Should().Be(38); usage.CacheReadInputTokens.Should().Be(0); } [Fact] public async Task StreamedCall_ReportsTheCachedPrefixToo() { var sse = string.Join("\n", [ """data: {"id":"chatcmpl-1","choices":[{"index":0,"delta":{"content":"done"}}]}""", "", """data: {"id":"chatcmpl-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}""", "", """data: {"id":"chatcmpl-1","choices":[],"usage":{"prompt_tokens":172095,"completion_tokens":11,"prompt_cache_hit_tokens":172032,"prompt_cache_miss_tokens":63}}""", "", "data: [DONE]"]) + "\n"; var provider = Provider(sse, "text/event-stream"); LlmResponse? answer = null; await foreach (var chunk in provider.StreamAsync(Request())) if (chunk.Response is not null) answer = chunk.Response; answer!.Usage.CacheReadInputTokens.Should().Be(172032, "the streamed answer carries the same usage"); answer.Usage.InputTokens.Should().Be(63); } } Path: redb-route/tests/redb.Route.Tests.Llm/ComponentSideTests.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/ComponentSideTests.cs ---- using redb.Route.Core; using redb.Route.Llm.Embeddings; using redb.Route.Llm.Knowledge; using redb.Route.Llm.Transcription; namespace redb.Route.Tests.Llm; /// The component declares the only side it has ([EndpointRole], Apache Camel's producerOnly / consumerOnly). public sealed class ComponentSideTests { [Fact] public void The_component_declares_its_only_side() { EndpointSides.Declaration(typeof(EmbedComponent))!.Role.Should().Be(EndpointRole.Producer); EndpointSides.Declaration(typeof(KnowledgeComponent))!.Role.Should().Be(EndpointRole.Producer); EndpointSides.Declaration(typeof(SttComponent))!.Role.Should().Be(EndpointRole.Producer); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/AnthropicCompatLiveTests.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/DslShowcase/AnthropicCompatLiveTests.cs ---- using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using redb.Route.Tests.Llm.TestHelpers; using Xunit.Abstractions; namespace redb.Route.Tests.Llm.DslShowcase; /// /// Phase 16.0b, on the interface that is actually reachable: DeepSeek serves the Anthropic Messages API /// at https://api.deepseek.com/anthropic (x-api-key supported, type="thinking" /// supported, redacted_thinking not), so can be exercised against /// a live endpoint without an Anthropic key — which is the whole question 16.0b asks: does a thinking /// block that came off the wire go back on it without a 400. /// /// The run is recorded, not assumed. Both request bodies are captured as sent, and the artifact says /// what came back (a block with a signature, a block without one, or none) — so a green run with no /// returnable block is read as "the path works", never as "the replay was proven". /// /// /// Nothing here prints the key or the thinking text: the artifact carries counts, lengths, field names /// and the first 16 hex digits of the block's SHA-256. /// /// [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] public sealed class AnthropicCompatLiveTests { private const string EnvVar = "REDB_LLM_DEEPSEEK"; private const string BaseUrl = "https://api.deepseek.com/anthropic/"; private const string Model = "deepseek-flash"; private const string Artifact = "16-0b-anthropic-compat.json"; private readonly ITestOutputHelper _output; /// Creates the probe with xUnit's output sink. public AnthropicCompatLiveTests(ITestOutputHelper output) => _output = output; /// Forwards a request untouched and keeps the body and address the provider sent. private sealed class RecordingHandler : HttpMessageHandler { private readonly HttpClient _forward = new() { Timeout = TimeSpan.FromSeconds(120) }; /// Serialised request bodies, in the order the provider sent them. public List SentBodies { get; } = new(); /// Request addresses, so the run proves which endpoint was spoken to. public List SentUris { get; } = new(); protected override async Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { var body = await request.Content!.ReadAsStringAsync(cancellationToken); SentBodies.Add(body); SentUris.Add(request.RequestUri!.ToString()); using var clone = new HttpRequestMessage(request.Method, request.RequestUri); foreach (var header in request.Headers) clone.Headers.TryAddWithoutValidation(header.Key, header.Value); clone.Content = new StringContent(body, Encoding.UTF8, "application/json"); return await _forward.SendAsync(clone, HttpCompletionOption.ResponseHeadersRead, cancellationToken); } protected override void Dispose(bool disposing) { if (disposing) _forward.Dispose(); base.Dispose(disposing); } } private static string Fingerprint(string text) { var hash = System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(text)); return Convert.ToHexString(hash[..8]).ToLowerInvariant(); } /// What came back on the thinking path — enough to compare two runs without reading thoughts. private sealed record ThinkingShape(bool Present, bool HasSignature, bool IsRedacted, int TextLength, string TextFingerprint) { public static ThinkingShape Of(LlmThinkingBlock? block) => block is null ? new ThinkingShape(false, false, false, 0, string.Empty) : new ThinkingShape(true, block.Signature is { Length: > 0 }, block.IsRedacted, block.Text.Length, Fingerprint(block.Text)); } private const string Question = "Where is order 4711 right now?"; private static readonly LlmToolCapability LookupTool = new() { Name = "order_lookup", Description = "Looks up one order by id and returns its shipping status.", InputSchema = """{"type":"object","properties":{"orderId":{"type":"string"}},"required":["orderId"]}""" }; private static JsonObject ParseBody(string body) => JsonNode.Parse(body)!.AsObject(); /// A block the Anthropic wire can carry back: signed thinking, or a redacted payload. private static bool HasAnthropicForm(LlmThinkingBlock? block) => block is not null && (block.IsRedacted || !string.IsNullOrEmpty(block.Signature)); private static IEnumerable BlocksOf(JsonObject body) { if (body["messages"] is not JsonArray messages) yield break; foreach (var message in messages) { if (message?["content"] is not JsonArray blocks) continue; foreach (var block in blocks) if (block is JsonObject obj) yield return obj; } } private static int ThinkingBlocksIn(JsonObject body) => BlocksOf(body) .Count(b => b["type"]?.GetValue() is "thinking" or "redacted_thinking"); /// The signature (or redacted payload) of the first thinking block carried in a request. private static string? SignaturePlayed(JsonObject body) => BlocksOf(body) .FirstOrDefault(b => b["type"]?.GetValue() is "thinking" or "redacted_thinking") is { } first ? first["signature"]?.GetValue() ?? first["data"]?.GetValue() : null; /// /// The 16.0b question on an endpoint that is reachable today: against /// DeepSeek's Anthropic-compatible interface, asked twice — once for an answer that may carry a thinking /// block, then with that block and the tool turn it belongs to handed back. /// [EnvFact(EnvVar)] public async Task DeepSeek_AnthropicPath_TakesTheThinkingBlockBack() { var started = DateTimeOffset.UtcNow; var factory = new LlmConnectionFactory { Name = "deepseek-anthropic-compat", Provider = "anthropic", ModelId = Model, ApiKey = Environment.GetEnvironmentVariable(EnvVar)!, BaseUrl = new Uri(BaseUrl), MaxTokens = 512 }; using var recorder = new RecordingHandler(); var provider = new AnthropicProvider(factory, new HttpClient(recorder)); var first = await provider.CompleteAsync(new LlmRequest { SystemPrompt = "Call the order_lookup tool before answering the question.", Messages = [LlmMessage.User(Question)], Tools = [LookupTool] }); var thinking = first.Content.OfType().FirstOrDefault(); var shape = ThinkingShape.Of(thinking); var toolUses = first.Content.OfType().ToList(); // The transcript is rebuilt the way a run would: the block first, what the assistant said next, // then the tool result the tool_use asked for — the shape that 400s if either half is lost. var assistant = new List(); if (HasAnthropicForm(thinking)) assistant.Add(thinking!); assistant.AddRange(first.Content.Where(b => b is not LlmThinkingBlock)); var transcript = new List { LlmMessage.User(Question) }; if (assistant.Count > 0) transcript.Add(new LlmMessage { Role = "assistant", Content = assistant }); if (toolUses.Count > 0) transcript.Add(new LlmMessage { Role = "user", Content = toolUses .Select(u => (LlmContentBlock)new LlmToolResultBlock(u.ToolUseId, """{"status":"in_transit"}""")) .ToList() }); var replay = await provider.CompleteAsync(new LlmRequest { Messages = transcript, Tools = [LookupTool] }); var sent = recorder.SentBodies.Select(ParseBody).ToList(); var carriedBack = ThinkingBlocksIn(sent[1]); var verdict = shape switch { { Present: false } => "no thinking block came back — the path holds, the replay is not proven", { IsRedacted: true } => "redacted block came back and was handed back verbatim", { HasSignature: true } => "signed block came back and was handed back verbatim", _ => "unsigned block came back — this connector does not replay it (it would be rejected)" }; recorder.SentUris.Should().HaveCount(2); recorder.SentUris[0].Should().Be(BaseUrl + "v1/messages"); first.Content.Should().NotBeEmpty(); replay.Content.Should().NotBeEmpty(); // Decision 15 of the plan: this connector never asks for thinking, so a block that comes back is // the model thinking on its own — asserted, because "we do not send it" is a promise a request // body can keep. sent[0].Should().NotContainKey("thinking", "the anthropic path must not send a top-level thinking field."); sent[1].Should().NotContainKey("thinking"); if (HasAnthropicForm(thinking)) { carriedBack.Should().Be(1); SignaturePlayed(sent[1]).Should().Be(thinking!.IsRedacted ? thinking.RedactedData : thinking.Signature); } else { // Nothing returnable came back, so nothing could be replayed — said out loud rather than // left for a reader to infer from a green run. carriedBack.Should().Be(0); } var artifact = new { Phase = "16.0b — the anthropic path against DeepSeek's Anthropic-compatible interface", Endpoint = recorder.SentUris[0], Model, StartedUtc = started, FinishedUtc = DateTimeOffset.UtcNow, FirstRequestHadThinkingField = sent[0].ContainsKey("thinking"), ThinkingOnTheWire = ThinkingBlocksIn(sent[0]), ThinkingParsed = shape, ToolCalls = toolUses.Count, BlocksHandedBack = carriedBack, ReplayedSignatureFingerprint = SignaturePlayed(sent[1]) is { Length: > 0 } sig ? Fingerprint(sig) : null, Verdict = verdict }; var path = Path.Combine(AppContext.BaseDirectory, Artifact); await File.WriteAllTextAsync(path, JsonSerializer.Serialize(artifact, new JsonSerializerOptions { WriteIndented = true })); _output.WriteLine($"artifact: {path}"); _output.WriteLine($"thinking on the wire={artifact.ThinkingOnTheWire} parsed={shape.Present} " + $"signed={shape.HasSignature} redacted={shape.IsRedacted} " + $"textLen={shape.TextLength} textSha256={shape.TextFingerprint}"); _output.WriteLine($"tool calls={toolUses.Count} blocks handed back={carriedBack}"); _output.WriteLine(verdict); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/BasicChatTests.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/DslShowcase/BasicChatTests.cs ---- using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.DslShowcase; /// /// The simplest live shape — an Apache Camel pattern reduced to one line: /// From("direct:chat") → To("llm://...") → To("mock:result"). /// One direct: producer, one LLM hop, one assertion sink. Any junior /// reader should grasp the shape on first sight. /// /// Each test gates on the env var of the corresponding free-tier provider. /// We don't pretend the cheapest free tiers are equally reliable — the suite /// shows the connector works in principle across providers, not that /// every provider is production-grade. /// /// [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] public sealed class BasicChatTests { /// /// Groq + Llama 3.3 70B is the most reliable free tier we have access to, /// so it gets the strict assertion (the model must produce the literal word). /// [EnvFact("REDB_LLM_GROQ_KEY")] public async Task Groq_From_To_Mock_DeliversAnswer() { await using var host = LiveLlmHost.Build() .AddFactory("groq", new LlmConnectionFactory { Provider = "groq", ModelId = "llama-3.3-70b-versatile", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"), Temperature = 0.0, MaxTokens = 16 }); await host.StartAsync(r => { r.From("direct:chat") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Reply with exactly one lowercase word: pong. No punctuation.") .To(LlmDsl.Factory("groq").Temperature(0.0).MaxTokens(16).AsUri()) .To("mock:result"); }); await host.SendAsync("direct:chat", "Say the word."); var sink = host.Mock("mock:result"); sink.ReceivedCount.Should().Be(1); var reply = ((string)sink.ReceivedExchanges[0].In.Body!).Trim().ToLowerInvariant(); reply.Should().Contain("pong"); // Headers stamped by LlmProducer must propagate down the route. sink.ReceivedExchanges[0].In.Headers[LlmHeaders.ProviderId].Should().Be("groq"); ((int)sink.ReceivedExchanges[0].In.Headers[LlmHeaders.TokensIn]!).Should().BeGreaterThan(0); } /// /// Gemini's free tier is rate-limited to 15 RPM; on a quiet repo it works, /// but we keep the assertion philosophical: some non-empty reply /// rather than a specific token. Demonstrates that switching provider is /// just a registry entry change — no other DSL surface moves. /// [EnvFact("REDB_LLM_GEMINI_KEY")] public async Task Gemini_From_To_Mock_DeliversNonEmptyReply() { await using var host = LiveLlmHost.Build() .AddFactory("gemini", new LlmConnectionFactory { Provider = "gemini", ModelId = "gemini-2.0-flash", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GEMINI_KEY"), Temperature = 0.0, MaxTokens = 32 }); await host.StartAsync(r => { r.From("direct:chat") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Reply with one short sentence in plain English.") .To(LlmDsl.Factory("gemini").AsUri()) .To("mock:result"); }); await host.SendAsync("direct:chat", "Greet me."); var sink = host.Mock("mock:result"); sink.ReceivedCount.Should().Be(1); ((string)sink.ReceivedExchanges[0].In.Body!).Should().NotBeNullOrWhiteSpace(); } /// /// Mistral's small-latest is the second-most reliable free tier for /// short-form replies. Same DSL — only the registry name changes. /// [EnvFact("REDB_LLM_MISTRAL_KEY")] public async Task Mistral_From_To_Mock_DeliversNonEmptyReply() { await using var host = LiveLlmHost.Build() .AddFactory("mistral", new LlmConnectionFactory { Provider = "mistral", ModelId = "mistral-small-latest", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_MISTRAL_KEY"), Temperature = 0.0, MaxTokens = 32 }); await host.StartAsync(r => { r.From("direct:chat") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Reply with one short sentence in plain English.") .To(LlmDsl.Factory("mistral").AsUri()) .To("mock:result"); }); await host.SendAsync("direct:chat", "Greet me."); var sink = host.Mock("mock:result"); sink.ReceivedCount.Should().Be(1); ((string)sink.ReceivedExchanges[0].In.Body!).Should().NotBeNullOrWhiteSpace(); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/ChainedLlmTests.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/DslShowcase/ChainedLlmTests.cs ---- using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.DslShowcase; /// /// Two LLM hops in a row. First hop summarizes, second hop translates the /// summary. The route engine carries the body forward; no extra plumbing is /// needed to chain models. Uses Groq twice with different system prompts — /// the same factory, parameterized per call site. /// [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] public sealed class ChainedLlmTests { [EnvFact("REDB_LLM_GROQ_KEY")] public async Task Groq_TwoHopChain_SummarizeThenTranslate() { await using var host = LiveLlmHost.Build() .AddFactory("groq", new LlmConnectionFactory { Provider = "groq", ModelId = "llama-3.3-70b-versatile", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"), Temperature = 0.0, MaxTokens = 96 }); await host.StartAsync(r => { r.From("direct:chain") // Hop 1 — summarize. .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Summarize the user's text in one short English sentence.") .To(LlmDsl.Factory("groq").Temperature(0.0).MaxTokens(64).AsUri()) // Hop 2 — translate the previous reply. .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Translate the user's text to French. Reply with the translation only, no preamble.") .To(LlmDsl.Factory("groq").Temperature(0.0).MaxTokens(64).AsUri()) .To("mock:done"); }); await host.SendAsync("direct:chain", "The quick brown fox jumps over the lazy dog every single morning before breakfast."); var sink = host.Mock("mock:done"); sink.ReceivedCount.Should().Be(1); var final = ((string)sink.ReceivedExchanges[0].In.Body!); final.Should().NotBeNullOrWhiteSpace(); // Philosophical: French replies usually contain at least one of these tokens. // We don't pin one specific word because models phrase things differently. var lower = final.ToLowerInvariant(); var frenchish = new[] { "le ", "la ", "les ", "un ", "une ", "renard", "chien" }; frenchish.Any(tok => lower.Contains(tok)).Should().BeTrue( "the second hop should yield French-shaped output, but got: {0}", final); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/ClaudeChatTests.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/DslShowcase/ClaudeChatTests.cs ---- using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.DslShowcase; /// /// Live tests against Anthropic's Claude family through the OpenAI-compatible /// endpoint at https://api.anthropic.com/v1/. Same DSL shapes as the rest /// of DslShowcase — a different vendor key, a different model, no other /// changes to the route definitions. The one extension we made to support this /// is wiring "anthropic" / "claude" into OpenAiProvider.ResolveDefaultBaseUrl. /// /// Claude tends to be the most reliable closed-source model we have access to, /// so this is the strict-assertion suite — the model must produce literal /// tokens we ask for. /// /// [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] public sealed class ClaudeChatTests { [EnvFact("REDB_LLM_ANT_API03_KEY")] public async Task Claude_Haiku_45_From_To_Mock_DeliversAnswer() { await using var host = LiveLlmHost.Build() .AddFactory("claude", new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-haiku-4-5", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_ANT_API03_KEY"), Temperature = 0.0, MaxTokens = 32 }); await host.StartAsync(r => { r.From("direct:chat") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Reply with the literal token 'pong' and nothing else. No punctuation.") .To(LlmDsl.Factory("claude").Temperature(0.0).MaxTokens(8).AsUri()) .To("mock:result"); }); await host.SendAsync("direct:chat", "ping"); var sink = host.Mock("mock:result"); sink.ReceivedCount.Should().Be(1); var reply = ((string)sink.ReceivedExchanges[0].In.Body!).Trim().ToLowerInvariant(); reply.Should().Contain("pong", "Haiku 4.5 reliably follows 'reply with the literal token X' instructions"); } [EnvFact("REDB_LLM_ANT_API03_KEY")] public async Task Claude_Haiku_45_Tools_LookupAgent_UsesTool() { var lookup = new EchoToolRoute( toolName: "lookup", description: "Look up the magic word for a key.", inputSchema: """{"type":"object","properties":{"key":{"type":"string"}},"required":["key"]}""", replyJson: """{"answer":"the magic word is rosebud"}"""); await using var host = LiveLlmHost.Build() .AddFactory("claude", new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-haiku-4-5", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_ANT_API03_KEY"), Temperature = 0.0, MaxTokens = 128 }); await host.StartAsync(lookup, r => { r.From("direct:agent") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Use the lookup tool to find the magic word, then reply with that exact phrase. " + "Do not invent a word — call the tool first.") .To(LlmDsl.Factory("claude").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done"); }); await host.SendAsync("direct:agent", "What is the magic word?"); lookup.CapturedInputs.Should().NotBeEmpty("Claude must call the lookup tool at least once"); var sink = host.Mock("mock:done"); sink.ReceivedCount.Should().Be(1); var final = ((string)sink.ReceivedExchanges[0].In.Body!).ToLowerInvariant(); final.Should().Contain("rosebud", "the final reply must echo the tool result"); } /// /// A larger model on a slightly fuzzier task — translate then summarize via two /// LLM hops in one route. Loose assertion (French-shaped output) — Sonnet has /// more degrees of freedom than Haiku and we don't want to pin specific tokens. /// [EnvFact("REDB_LLM_ANT_API03_KEY")] public async Task Claude_Sonnet_46_TwoHopChain_SummarizeThenTranslate() { await using var host = LiveLlmHost.Build() .AddFactory("claude", new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-sonnet-4-6", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_ANT_API03_KEY"), Temperature = 0.0, MaxTokens = 96 }); await host.StartAsync(r => { r.From("direct:chain") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Summarize the user's text in one short English sentence.") .To(LlmDsl.Factory("claude").Temperature(0.0).MaxTokens(64).AsUri()) .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Translate the user's text to French. Reply with the translation only, no preamble.") .To(LlmDsl.Factory("claude").Temperature(0.0).MaxTokens(64).AsUri()) .To("mock:done"); }); await host.SendAsync("direct:chain", "The quick brown fox jumps over the lazy dog every single morning before breakfast."); var sink = host.Mock("mock:done"); sink.ReceivedCount.Should().Be(1); var final = ((string)sink.ReceivedExchanges[0].In.Body!); final.Should().NotBeNullOrWhiteSpace(); var lower = final.ToLowerInvariant(); var frenchish = new[] { "le ", "la ", "les ", "un ", "une ", "renard", "chien" }; frenchish.Any(tok => lower.Contains(tok)).Should().BeTrue( "the second hop should yield French-shaped output, but got: {0}", final); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/DeepSeekGovernanceLiveTests.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/DslShowcase/DeepSeekGovernanceLiveTests.cs ---- using System.Security.Claims; using redb.Route.Abstractions; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.DslShowcase; /// /// Live governance: a real model, a real tool loop, a real claim check — the level every other live test /// skips, because they prove the transport and this proves the policy. The key is DeepSeek's (the one /// provider whose key is valid in this environment); the behaviour under test is provider-independent. /// /// The caller's scope is put on the exchange the way a transport would (a property, see /// ), and the tool declares what it needs — so the two runs below differ in /// exactly one thing: whether the principal holds that scope. /// /// [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] public sealed class DeepSeekGovernanceLiveTests { private const string Schema = """{"type":"object","properties":{"orderId":{"type":"string"}},"required":["orderId"]}"""; private const string ToolName = "order_lookup"; private const string Claim = "orders:read"; private static LlmConnectionFactory DeepSeek() => new() { Provider = "deepseek", ModelId = "deepseek-flash", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_DEEPSEEK"), Temperature = 0.0, MaxTokens = 256 }; private static ClaimsPrincipal Caller(string scope) => new(new ClaimsIdentity([new Claim("scope", scope)], authenticationType: "live-test")); private static async Task<(ToolInvocationSpy Spy, EchoToolRoute Tool, LiveLlmHost Host)> RunAsync(string grantedScope) { var spy = new ToolInvocationSpy(); var tool = new EchoToolRoute(ToolName, "Look up an order by id and return its status.", Schema, """{"status":"shipped"}""", requiredClaims: [Claim]); var host = await LiveLlmHost.Build(spy, claimsSource: new ExchangePrincipalClaimsSource()) .AddFactory("deepseek", DeepSeek()) .StartAsync(tool, r => r.From("direct:agent") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = $"Use the {ToolName} tool to look up the order, then reply with only the status word.") .To(LlmDsl.Factory("deepseek").Tools(ToolName).MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "What is the status of order 42?", configure: ex => ExchangePrincipal.Set(ex, Caller(grantedScope))); return (spy, tool, host); } [EnvFact("REDB_LLM_DEEPSEEK")] public async Task DeepSeek_ClaimRequiredTool_RunsForACallerHoldingTheScope() { var (spy, tool, host) = await RunAsync(Claim); await using var _ = host; spy.ForTool(ToolName).Should().NotBeEmpty( "the model must call the tool, and the caller's scope satisfies its requirement"); spy.ForTool(ToolName).Should().OnlyContain(o => !o.Skipped); tool.CapturedInputs.Should().HaveCount(1, "the tool route actually ran"); tool.CapturedInputs[0].Should().Contain("42").And.Contain("orderId"); var sink = host.Mock("mock:done"); sink.ReceivedCount.Should().Be(1); ((string)sink.ReceivedExchanges[0].In.Body!).Should().Contain("shipped", "the answer the model produced carries the tool's output"); } [EnvFact("REDB_LLM_DEEPSEEK")] public async Task DeepSeek_ClaimRequiredTool_IsDeniedForACallerWithoutTheScope() { // The caller is authenticated and holds a different scope. The model still asks for the tool — and // the engine refuses the call, so the tool route never runs; what the observer sees is a skip with a // machine-readable reason, not an invocation. var (spy, tool, host) = await RunAsync("billing:read"); await using var _ = host; spy.ForTool(ToolName).Should().NotBeEmpty("the model asked for the tool — a refusal is not a silent drop"); spy.ForTool(ToolName).Should().OnlyContain(o => o.Skipped); spy.ForTool(ToolName).Last().SkipReason.Should().StartWith(ToolSkipReasons.ClaimsMissing, "the refusal carries the reason an audit dashboard filters on"); tool.CapturedInputs.Should().BeEmpty("refused means the tool route never executed"); host.Mock("mock:done").ReceivedCount.Should().Be(1, "the run finishes and the model answers — a refusal is a tool_result, not a crash"); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/DeepSeekStreamLiveTests.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/DslShowcase/DeepSeekStreamLiveTests.cs ---- using System.Text; using redb.Route.Llm.Engine.Observability; using redb.Route.Tests.Llm.TestHelpers; using Xunit.Abstractions; namespace redb.Route.Tests.Llm.DslShowcase; /// /// The streamed parsers and the cache counters against a live provider. One DeepSeek key reaches both parsers: /// the OpenAI-compatible API at api.deepseek.com and the Anthropic Messages API at /// api.deepseek.com/anthropic. The offline tests prove the parsers on recorded shapes; these prove them on the /// wire, through the package's own transport (HTTP/2, keep-alive pings, call limits). /// /// Nothing here prints the key or the model's text: the output carries counts and lengths. /// /// [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] public sealed class DeepSeekStreamLiveTests { private const string EnvVar = "REDB_LLM_DEEPSEEK"; private const string Model = "deepseek-flash"; private static readonly Uri AnthropicBaseUrl = new("https://api.deepseek.com/anthropic/"); private readonly ITestOutputHelper _output; /// Creates the tests with xUnit's output sink. public DeepSeekStreamLiveTests(ITestOutputHelper output) => _output = output; private static string Key => Environment.GetEnvironmentVariable(EnvVar)!; private static LlmConnectionFactory OpenAiFactory() => new() { Name = "deepseek-live", Provider = "deepseek", ModelId = Model, ApiKey = Key, MaxTokens = 1024 }; private static LlmConnectionFactory AnthropicFactory() => new() { Name = "deepseek-anthropic-live", Provider = "anthropic", ModelId = Model, ApiKey = Key, BaseUrl = AnthropicBaseUrl, MaxTokens = 1024 }; private static LlmRequest Question(string? system = null) => new() { SystemPrompt = system, Messages = [LlmMessage.User("What is 2 + 2? Answer with the digit only.")], MaxTokens = 1024 }; /// Streams the question and checks the assembled answer against the pieces that made it. private async Task StreamedAnswerMatchesItsPiecesAsync(ILlmProvider provider) { var text = new StringBuilder(); var thinking = new StringBuilder(); var pieces = 0; LlmResponse? answer = null; await foreach (var chunk in provider.StreamAsync(Question())) { foreach (var piece in chunk.Content) { if (chunk.Response is not null) break; switch (piece) { case LlmTextBlock t: text.Append(t.Text); pieces++; break; case LlmThinkingBlock th: thinking.Append(th.Text); pieces++; break; } } if (chunk.Response is not null) answer = chunk.Response; } answer.Should().NotBeNull($"{provider.ProviderId}: the last chunk carries the assembled answer"); var assembledText = string.Concat(answer!.Content.OfType().Select(b => b.Text)); var assembledThinking = string.Concat(answer.Content.OfType().Select(b => b.Text)); _output.WriteLine( $"{provider.ProviderId}: pieces={pieces}, text={assembledText.Length} chars, thinking={assembledThinking.Length} chars, " + $"blocks=[{string.Join(",", answer.Content.Select(b => b.GetType().Name))}], stop={answer.RawStopReason}, " + $"usage in/out/cacheRead={answer.Usage.InputTokens}/{answer.Usage.OutputTokens}/{answer.Usage.CacheReadInputTokens}"); pieces.Should().BeGreaterThan(1, "the answer arrived in pieces"); answer.StopReason.Should().Be(LlmStopReason.EndTurn); text.ToString().Should().Be(assembledText, "the assembled text is exactly the text that streamed"); thinking.ToString().Should().Be(assembledThinking, "the assembled thinking is exactly the thinking that streamed"); assembledText.Should().Contain("4"); answer.Usage.OutputTokens.Should().BeGreaterThan(0, "the terminal usage reached the answer"); } [EnvFact(EnvVar)] public Task OpenAiPath_StreamedAnswer_MatchesItsPieces() => StreamedAnswerMatchesItsPiecesAsync(OpenAiProvider.Create(OpenAiFactory())); [EnvFact(EnvVar)] public Task AnthropicPath_StreamedAnswer_MatchesItsPieces() => StreamedAnswerMatchesItsPiecesAsync(new AnthropicProvider(AnthropicFactory())); /// A prefix of a few thousand tokens that no earlier run has sent: it starts with this run's id. private static string LongPrefix() { var sb = new StringBuilder($"Run {Guid.NewGuid():N}. You answer arithmetic questions with the digit only.\n"); for (var i = 1; i <= 300; i++) sb.Append("Rule ").Append(i).Append(": keep the answer short, exact and free of any explanation.\n"); return sb.ToString(); } [EnvFact(EnvVar)] public async Task OpenAiPath_RepeatedPrefix_IsReadFromCache() { var provider = OpenAiProvider.Create(OpenAiFactory()); var request = Question(LongPrefix()); var first = await provider.CompleteAsync(request); _output.WriteLine($"first: in={first.Usage.InputTokens}, cacheRead={first.Usage.CacheReadInputTokens}"); first.Usage.CacheReadInputTokens.Should().Be(0, "the prefix starts with this run's id, so nothing of it was cached"); // The provider stores the prefix after the first call; a later call reads it. Give it a few tries. LlmUsage? cached = null; for (var attempt = 1; attempt <= 4 && cached is null; attempt++) { await Task.Delay(TimeSpan.FromSeconds(2)); var again = await provider.CompleteAsync(request); _output.WriteLine($"plain #{attempt}: in={again.Usage.InputTokens}, cacheRead={again.Usage.CacheReadInputTokens}"); if (again.Usage.CacheReadInputTokens > 0) cached = again.Usage; } cached.Should().NotBeNull("DeepSeek serves a repeated prefix from cache and says so in usage (issue #11)"); cached!.InputTokens.Should().BeLessThan(cached.CacheReadInputTokens, "InputTokens is the remainder billed at full price, and most of this prompt came from cache"); LlmResponse? streamed = null; await foreach (var chunk in provider.StreamAsync(request)) if (chunk.Response is not null) streamed = chunk.Response; _output.WriteLine($"streamed: in={streamed!.Usage.InputTokens}, cacheRead={streamed.Usage.CacheReadInputTokens}"); streamed.Usage.CacheReadInputTokens.Should().BeGreaterThan(0, "the streamed call reports the cache the same way"); } /// Counts the pieces the engine hands on. private sealed class PieceCounter : IAgentObserver { private int _text; private int _thinking; public int Text => Volatile.Read(ref _text); public int Thinking => Volatile.Read(ref _thinking); public Task OnRunStartedAsync(AgentRunContext context, CancellationToken ct = default) => Task.CompletedTask; public Task OnIterationCompletedAsync(AgentIterationContext context, CancellationToken ct = default) => Task.CompletedTask; public Task OnToolInvokedAsync(AgentToolInvocationContext context, CancellationToken ct = default) => Task.CompletedTask; public Task OnRunCompletedAsync(AgentRunCompletedContext context, CancellationToken ct = default) => Task.CompletedTask; public Task OnDeltaAsync(AgentDeltaContext context, CancellationToken ct = default) { if (context.Kind == AgentDeltaKind.Text) Interlocked.Increment(ref _text); else Interlocked.Increment(ref _thinking); return Task.CompletedTask; } } [EnvFact(EnvVar)] public async Task StreamCalls_ToolLoop_EndToEnd() { const string schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}"""; var tool = new EchoToolRoute("lookup", "Looks up the stored answer for a key. Always call it before answering.", schema, """{"answer":"42"}"""); var counter = new PieceCounter(); await using var host = LiveLlmHost.Build(counter).AddFactory("ds", OpenAiFactory()); await host.StartAsync(tool, r => r.From("direct:agent") .To("llm://ds?stream=calls&tools=lookup&maxIterations=4") .To("mock:done")); await host.SendAsync("direct:agent", "Call the lookup tool with q = \"life\", then tell me the answer it returned, digits only."); var answer = host.Mock("mock:done").ReceivedExchanges.Single().In.Body as string; _output.WriteLine($"tool calls={tool.CapturedInputs.Count}, text pieces={counter.Text}, thinking pieces={counter.Thinking}, answer={answer?.Length} chars"); tool.CapturedInputs.Should().NotBeEmpty("the streamed tool loop dispatched the tool"); answer.Should().Contain("42", "the model answered with what the tool returned"); // A two-character answer may arrive as one text piece; the run as a whole still streams, thinking included. counter.Text.Should().BeGreaterThan(0, "the answer reached the observer as it was written"); (counter.Text + counter.Thinking).Should().BeGreaterThan(1, "the run reached the observer in pieces, not as one block"); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/EmbedSchemeTests.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/DslShowcase/EmbedSchemeTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm; using redb.Route.Llm.Embeddings; using redb.Route.Llm.Providers; namespace redb.Route.Tests.Llm.DslShowcase; /// /// embed://<factory> scheme — embeds the exchange body via the named /// connection factory. Driven with a stub /// (no live endpoint): a single text → float[], a collection → float[][]. /// public sealed class EmbedSchemeTests { // Deterministic stub: vector = [text length, input index]. private sealed class StubEmb : IEmbeddingProvider { public string ProviderId => "stub"; public string ModelId => "stub-model"; public Task> EmbedAsync(IReadOnlyList inputs, CancellationToken ct = default) => Task.FromResult>( inputs.Select((s, i) => new float[] { s.Length, i }).ToArray()); } private static (RouteContext Ctx, ProducerTemplate Producer) Host(EmbedComponent component) { var sp = new ServiceCollection().BuildServiceProvider(); var ctx = new RouteContext(sp, contextId: "embed-scheme-test"); ctx.AddToRegistry("emb", new LlmConnectionFactory { Provider = "openai", ModelId = "text-embedding-3-small", ApiKey = "sk-test" }); ctx.AddComponent(component); var producer = new ProducerTemplate(ctx); ctx.AddService(typeof(IProducerTemplate), producer); return (ctx, producer); } [Fact] public async Task SingleText_ProducesFloatVector() { var (ctx, producer) = Host(new EmbedComponent { ProviderFactory = _ => new StubEmb() }); ctx.AddRoutes(r => r.From("direct:e").To("embed://emb")); await ctx.Start(); producer.Start(); var result = await producer.RequestBody("direct:e", "hello"); // 5 chars result.Should().BeOfType(); ((float[])result!).Should().Equal(5f, 0f); await ctx.DisposeAsync(); } [Fact] public async Task ManyTexts_ProduceVectorArray_OrderPreserved() { var (ctx, producer) = Host(new EmbedComponent { ProviderFactory = _ => new StubEmb() }); ctx.AddRoutes(r => r.From("direct:e2").To("embed://emb")); await ctx.Start(); producer.Start(); var result = await producer.RequestBody("direct:e2", new List { "ab", "cde" }); result.Should().BeOfType(); var vecs = (float[][])result!; vecs.Should().HaveCount(2); vecs[0].Should().Equal(2f, 0f); // "ab" → len 2, index 0 vecs[1].Should().Equal(3f, 1f); // "cde" → len 3, index 1 await ctx.DisposeAsync(); } [Fact] public async Task PerRoute_ResolvesNamedFactory() { LlmConnectionFactory? seen = null; var (ctx, producer) = Host(new EmbedComponent { ProviderFactory = f => { seen = f; return new StubEmb(); } }); ctx.AddRoutes(r => r.From("direct:e3").To("embed://emb")); await ctx.Start(); producer.Start(); await producer.RequestBody("direct:e3", "x"); seen.Should().NotBeNull(); seen!.ModelId.Should().Be("text-embedding-3-small"); // the factory named by embed://emb await ctx.DisposeAsync(); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/ExecShellToolTests.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/DslShowcase/ExecShellToolTests.cs ---- using redb.Route.Configuration; using redb.Route.Exec; using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.DslShowcase; /// /// Live integration test: a Claude agent calls a shell tool that is wired through /// the brand-new . The whole shape mirrors the existing /// pattern — except that the tool's body is a real /// exec://run producer with an allowlist on the host commands. /// /// What this proves: /// /// The exec connector is reachable from direct: via .AsLlmTool. /// Claude correctly emits {"command":"...","args":[...]} and the producer /// deserializes it without manual glue. /// The allowlist enforces the security envelope — a model trying to call /// anything other than the listed commands would be rejected. /// The JSON response shape is what the agent loop expects, so the model can /// read back stdout and reply to the user. /// /// /// [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] public sealed class ExecShellToolTests { private static bool IsWindows => OperatingSystem.IsWindows(); [EnvFact("REDB_LLM_ANT_API03_KEY")] public async Task Claude_Haiku_45_ShellTool_RunsAllowedCommand_AndEchoesStdout() { var shell = new ShellToolRoute(); await using var host = LiveLlmHost.Build(); // Mount the exec component on the live host context — the LiveLlmHost // base build only registers the LLM component by default. host.Context.AddComponent(new ExecComponent()); host.AddFactory("claude", new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-haiku-4-5", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_ANT_API03_KEY"), Temperature = 0.0, MaxTokens = 256 }); await host.StartAsync(shell, r => { r.From("direct:agent") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Use the shell tool to print the literal token 'redb-shell-ok' to stdout. " + "After receiving the tool's stdout, reply with that exact token and nothing else.") .To(LlmDsl.Factory("claude").Tools("shell").MaxIterations(4).AsUri()) .To("mock:done"); }); await host.SendAsync("direct:agent", "Print 'redb-shell-ok'."); // The model must have invoked the shell tool at least once. shell.LastStdout.Should().NotBeNull("Claude must call the shell tool"); shell.LastStdout.Should().Contain("redb-shell-ok", "the shell tool must have echoed our literal token"); var sink = host.Mock("mock:done"); sink.ReceivedCount.Should().Be(1); var final = ((string)sink.ReceivedExchanges[0].In.Body!).ToLowerInvariant(); final.Should().Contain("redb-shell-ok", "the agent's final reply must echo what the shell tool produced"); } /// /// Tool route that dispatches to exec://run with a tight allowlist. The route /// captures the producer's stdout for assertions — production usage would skip the /// capture and just chain to whatever sink the route needs. /// private sealed class ShellToolRoute : RouteBuilder { public string? LastStdout { get; private set; } protected override void Configure() { // Same description-and-schema shape any LLM tool ABI expects. // Allowlist is the security envelope — anything outside this list is rejected // before the OS process ever starts. From("direct:tool-shell") .AsLlmTool("shell") .Description( "Run a small shell command. Input: {\"command\":\"\",\"args\":[\"...\"]}. " + "Output: {\"stdout\":\"...\",\"stderr\":\"...\",\"exitCode\":N}. " + $"Allowed commands: {(IsWindows ? "cmd" : "sh")}.") .Input(""" { "type": "object", "properties": { "command": { "type": "string" }, "args": { "type": "array", "items": { "type": "string" } } }, "required": ["command"] } """) .SideEffect(ToolSideEffect.ReadOnly) .Cost(ToolCostClass.Cheap) .Then() .To(ExecDsl.Run() .AllowedCommands(IsWindows ? "cmd" : "sh") .TimeoutMs(5_000) .MaxStdoutBytes(8_192) .MaxStderrBytes(8_192)) .Process(e => { // Capture for the test — never required in production tool routes. // PipelineProcessor merges Out → In between steps, so the producer's // headers land on e.In here, not e.Out. if (e.In.Headers.TryGetValue(ExecHeaders.Stdout, out var s) && s is string str) LastStdout = str; }); } } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/HttpFetchToolTests.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/DslShowcase/HttpFetchToolTests.cs ---- using redb.Route.Llm.Tools; using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.DslShowcase; /// /// Demonstrates the canonical pre-built tool from redb.Route.Llm.Tools: /// . The chat route is unchanged from the basic /// shape; the only addition is registering http_fetch in the tool /// filter. /// /// We deliberately script the provider with here: /// free-tier models call HTTP tools inconsistently (URLs get truncated, schemas /// drift), and this suite is about DSL + tool wiring + real HTTP fetch, /// not about whether a 7B free model copies a URL byte-for-byte. /// covers the live tool-loop end-to-end. /// /// [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] public sealed class HttpFetchToolTests { [Fact] public async Task HttpFetchTool_PluggedIntoRoute_FetchesAndReturnsBody() { // Local HTTP server stands in for an external API. using var server = new LocalHttpServer { ResponseBody = """{"secret":"unicorn"}""" }; var url = server.BaseUrl + "secrets"; // Scripted provider: turn 1 calls the tool, turn 2 returns the secret. var fake = new FakeProvider() .EnqueueToolUse("http_fetch", $"{{\"url\":\"{url}\"}}") .EnqueueText("the secret is unicorn"); await using var host = LiveLlmHost.Build() .AddFactory("scripted", new LlmConnectionFactory { Provider = "fake", ModelId = fake.ModelId, PrebuiltProvider = fake }); var fetch = new HttpFetchTool(new HttpFetchOptions { HostAllowlist = new[] { server.Host }, Timeout = TimeSpan.FromSeconds(5) }); await host.StartAsync(fetch, r => { r.From("direct:agent") .To(LlmDsl.Factory("scripted").Tools("http_fetch").MaxIterations(4).AsUri()) .To("mock:done"); }); await host.SendAsync("direct:agent", "Fetch the secret."); // 1. Tool was registered. host.ToolRegistry.Get("http_fetch").Should().NotBeNull(); // 2. The local HTTP server was hit by the tool. server.RequestPaths.Should().ContainSingle().Which.Should().Contain("/secrets"); // 3. The tool result flowed back into the next provider call. fake.CallCount.Should().Be(2); fake.CapturedRequests[^1].Messages .SelectMany(m => m.Content) .OfType() .Should().ContainSingle() .Which.OutputJson.Should().Contain("unicorn"); // 4. The final assistant text rotated through to the mock sink. var sink = host.Mock("mock:done"); sink.ReceivedCount.Should().Be(1); ((string)sink.ReceivedExchanges[0].In.Body!).Should().Contain("unicorn"); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/InlineLlmTests.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/DslShowcase/InlineLlmTests.cs ---- using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm.DslShowcase; /// /// Shows the second flavor of LLM step: an inline .Llm(name, b => ...) /// fluent call instead of a llm:// URI. Functionally equivalent to /// but reads more naturally when the route has a /// strong opinion about parameters (system prompt, max iterations, etc.). /// /// We keep one strict assertion (Groq must produce the literal token) and one /// philosophical assertion (Mistral must produce some reply), mirroring /// the spectrum of free-tier reliability we see in practice. /// /// [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] public sealed class InlineLlmTests { [EnvFact("REDB_LLM_GROQ_KEY")] public async Task Groq_InlineLlm_Step_DeliversAnswer() { await using var host = LiveLlmHost.Build() .AddFactory("groq", new LlmConnectionFactory { Provider = "groq", ModelId = "llama-3.3-70b-versatile", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"), Temperature = 0.0, MaxTokens = 16 }); await host.StartAsync(r => { r.From("direct:chat") .Llm("groq", b => b .WithSystemPrompt("Reply with exactly one lowercase word: pong. No punctuation.") .WithTemperature(0.0) .WithMaxTokens(16)) .To("mock:result"); }); await host.SendAsync("direct:chat", "Say the word."); var sink = host.Mock("mock:result"); sink.ReceivedCount.Should().Be(1); var reply = ((string)sink.ReceivedExchanges[0].In.Body!).Trim().ToLowerInvariant(); reply.Should().Contain("pong"); } [EnvFact("REDB_LLM_MISTRAL_KEY")] public async Task Mistral_InlineLlm_Step_DeliversNonEmptyReply() { await using var host = LiveLlmHost.Build() .AddFactory("mistral", new LlmConnectionFactory { Provider = "mistral", ModelId = "mistral-small-latest", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_MISTRAL_KEY"), Temperature = 0.0, MaxTokens = 32 }); await host.StartAsync(r => { r.From("direct:chat") .Llm("mistral", b => b .WithSystemPrompt("Reply with one short sentence in plain English.") .WithMaxTokens(32)) .To("mock:result"); }); await host.SendAsync("direct:chat", "Greet me."); var sink = host.Mock("mock:result"); sink.ReceivedCount.Should().Be(1); ((string)sink.ReceivedExchanges[0].In.Body!).Should().NotBeNullOrWhiteSpace(); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/KnowledgeIngestTests.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/DslShowcase/KnowledgeIngestTests.cs ---- using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Knowledge; namespace redb.Route.Tests.Llm.DslShowcase; /// /// knowledge:// ingest producer — To("knowledge://coll") chunks the /// document body and upserts into the resolved . /// Driven through a bare + , /// no LLM provider. /// public sealed class KnowledgeIngestTests { private static (RouteContext Ctx, ProducerTemplate Producer, IKnowledgeStore Store) BuildHost() { var sp = new ServiceCollection().BuildServiceProvider(); var ctx = new RouteContext(sp, contextId: "knowledge-ingest-test"); IKnowledgeStore store = new InMemoryKnowledgeStore(); ctx.AddService(typeof(IKnowledgeStore), store); ctx.AddComponent(new KnowledgeComponent()); var producer = new ProducerTemplate(ctx); ctx.AddService(typeof(IProducerTemplate), producer); return (ctx, producer, store); } [Fact] public async Task Ingest_ChunksDocument_UpsertsAndIsSearchable() { var (ctx, producer, store) = BuildHost(); ctx.AddRoutes(r => r.From("direct:ingest").To("knowledge://kb?chunkChars=40&overlap=0")); await ctx.Start(); producer.Start(); const string text = "The mask breaks the name and speech. The idol breeds the fear of death. The rift loses meaning."; var reply = (string)(await producer.RequestBody("direct:ingest", text))!; var summary = JsonDocument.Parse(reply).RootElement; summary.GetProperty("collection").GetString().Should().Be("kb"); summary.GetProperty("chunks").GetInt32().Should().BeGreaterThan(1); // ~95 chars / 40 → 3 chunks var hits = await store.SearchTextAsync("idol", 10, "kb"); hits.Should().NotBeEmpty(); hits[0].Chunk.Collection.Should().Be("kb"); await ctx.DisposeAsync(); } [Fact] public async Task Reingest_SameDocId_ReplacesChunksInPlace() { var (ctx, producer, store) = BuildHost(); // one chunk per doc (large chunkChars), stable docId → id "d1#0" ctx.AddRoutes(r => r.From("direct:ingest2").To("knowledge://kb?chunkChars=1000&docId=d1")); await ctx.Start(); producer.Start(); await producer.RequestBody("direct:ingest2", "first version about apples"); (await store.SearchTextAsync("apples", 10, "kb")).Should().ContainSingle(); await producer.RequestBody("direct:ingest2", "second version about bananas"); (await store.SearchTextAsync("apples", 10, "kb")).Should().BeEmpty(); // replaced (await store.SearchTextAsync("bananas", 10, "kb")).Should().ContainSingle(); await ctx.DisposeAsync(); } [Fact] public void Chunker_WindowsWithOverlap() { KnowledgeChunker.Split("abcdefghij", chunkChars: 4, overlap: 0) .Should().Equal("abcd", "efgh", "ij"); KnowledgeChunker.Split("abcdefghij", chunkChars: 4, overlap: 2) .Should().Equal("abcd", "cdef", "efgh", "ghij"); KnowledgeChunker.Split("short", chunkChars: 100, overlap: 0) .Should().Equal("short"); KnowledgeChunker.Split(" ", chunkChars: 10, overlap: 0) .Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/KnowledgeRetrievalTests.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/DslShowcase/KnowledgeRetrievalTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Knowledge; using redb.Route.Llm.Providers; namespace redb.Route.Tests.Llm.DslShowcase; /// /// .Knowledge(collection, k) — retrieves top-K chunks for the current message /// and injects them into the system prompt before a downstream .To("llm://"). /// public sealed class KnowledgeRetrievalTests { private sealed class StubEmb(Dictionary map) : IEmbeddingProvider { public string ProviderId => "stub"; public string ModelId => "stub"; public Task> EmbedAsync(IReadOnlyList inputs, CancellationToken ct = default) => Task.FromResult>( inputs.Select(i => map.TryGetValue(i, out var v) ? v : new float[] { 0f, 0f }).ToArray()); } private static (RouteContext Ctx, ProducerTemplate Producer) Host() { var sp = new ServiceCollection().BuildServiceProvider(); var ctx = new RouteContext(sp, contextId: "knowledge-retrieval-test"); var producer = new ProducerTemplate(ctx); ctx.AddService(typeof(IProducerTemplate), producer); return (ctx, producer); } private static async Task Seed(params (string Id, string Text, float[]? Emb)[] chunks) { IKnowledgeStore store = new InMemoryKnowledgeStore(); await store.UpsertManyAsync(chunks.Select(c => new KnowledgeChunk { Id = c.Id, Text = c.Text, Collection = "kb", Embedding = c.Emb ?? Array.Empty() })); return store; } [Fact] public async Task Keyword_InjectsRetrievedChunks_IntoSystemPrompt() { var store = await Seed(("1", "apples grow on trees", null), ("2", "bananas are yellow", null)); var (ctx, producer) = Host(); ctx.AddRoutes(r => r.From("direct:q") .Knowledge(new KnowledgeRetrievalOptions { Collection = "kb", TopK = 3, Store = store }) .Process(e => e.In.Body = e.In.Headers.TryGetValue(LlmHeaders.SystemPrompt, out var sp) ? sp : "(none)")); await ctx.Start(); producer.Start(); var result = (string)(await producer.RequestBody("direct:q", "apples"))!; result.Should().Contain("apples grow on trees"); result.Should().NotContain("bananas"); await ctx.DisposeAsync(); } [Fact] public async Task Semantic_UsesEmbeddings_NotSubstring() { var store = await Seed(("cats", "about cats", new[] { 1f, 0f }), ("dogs", "about dogs", new[] { 0f, 1f })); var emb = new StubEmb(new() { ["feline pets"] = new[] { 0.9f, 0.1f } }); var (ctx, producer) = Host(); ctx.AddRoutes(r => r.From("direct:q2") .Knowledge(new KnowledgeRetrievalOptions { Collection = "kb", TopK = 1, Store = store, EmbeddingProvider = emb }) .Process(e => e.In.Body = e.In.Headers.TryGetValue(LlmHeaders.SystemPrompt, out var sp) ? sp : "(none)")); await ctx.Start(); producer.Start(); var result = (string)(await producer.RequestBody("direct:q2", "feline pets"))!; result.Should().Contain("about cats"); // semantic match, query shares no keyword await ctx.DisposeAsync(); } [Fact] public async Task AugmentsExistingSystemPrompt() { var store = await Seed(("1", "apples grow on trees", null)); var (ctx, producer) = Host(); ctx.AddRoutes(r => r.From("direct:q3") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "You are helpful.") .Knowledge(new KnowledgeRetrievalOptions { Collection = "kb", Store = store }) .Process(e => e.In.Body = e.In.Headers[LlmHeaders.SystemPrompt])); await ctx.Start(); producer.Start(); var result = (string)(await producer.RequestBody("direct:q3", "apples"))!; result.Should().StartWith("You are helpful."); result.Should().Contain("apples grow on trees"); await ctx.DisposeAsync(); } [Fact] public async Task NoStore_IsNoOp() { var (ctx, producer) = Host(); ctx.AddRoutes(r => r.From("direct:q4") .Knowledge(new KnowledgeRetrievalOptions { Collection = "kb" }) // no store, no DI .Process(e => e.In.Body = e.In.Headers.ContainsKey(LlmHeaders.SystemPrompt) ? "injected" : "clean")); await ctx.Start(); producer.Start(); ((string)(await producer.RequestBody("direct:q4", "apples"))!).Should().Be("clean"); await ctx.DisposeAsync(); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/KnowledgeSearchToolTests.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/DslShowcase/KnowledgeSearchToolTests.cs ---- using System.Text.Json; using AwesomeAssertions; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Providers; using redb.Route.Llm.Tools; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm.DslShowcase; /// /// Drives the knowledge_search tool () straight /// through the route pipeline — a direct: route mounted via .AsLlmTool(...) /// over . No LLM provider involved. /// public sealed class KnowledgeSearchToolTests { private static async Task SeededStore(params (string Id, string Text, string? Collection)[] chunks) { IKnowledgeStore store = new InMemoryKnowledgeStore(); await store.UpsertManyAsync(chunks.Select(c => new KnowledgeChunk { Id = c.Id, Text = c.Text, Collection = c.Collection, Embedding = new float[] { 0f } })); return store; } [Fact] public async Task RegistersDescriptor_AndReturnsRankedHits() { var store = await SeededStore( ("1", "Apples grow on trees.", "fruit"), ("2", "apple, apple, apple pie.", "fruit"), ("3", "The office is downtown.", "misc")); await using var host = LiveLlmHost.Build(); await host.StartAsync(new KnowledgeSearchTool(new KnowledgeSearchOptions { Store = store })); var descriptor = host.ToolRegistry.Get("knowledge_search"); descriptor.Should().NotBeNull(); descriptor!.Capability.Safety.SideEffect.Should().Be(ToolSideEffect.ReadOnly); var ex = await host.SendAsync("direct:llm.knowledge_search", """{"query":"apple"}"""); var results = JsonDocument.Parse((string)ex.Out!.Body!).RootElement.GetProperty("results"); results.GetArrayLength().Should().Be(2); // #1 and #2 contain "apple" results[0].GetProperty("id").GetString().Should().Be("2"); // 3 occurrences rank first ex.Out.Headers["llm.knowledge_search.hits"].Should().Be(2); } [Fact] public async Task PinnedCollection_IgnoresModelSuppliedCollection() { var store = await SeededStore( ("a", "a shared term", "alpha"), ("b", "a shared term", "beta")); await using var host = LiveLlmHost.Build(); await host.StartAsync(new KnowledgeSearchTool( new KnowledgeSearchOptions { Store = store, Collection = "beta" })); // The model asks for alpha, but the tool is pinned to beta — pin wins. var ex = await host.SendAsync("direct:llm.knowledge_search", """{"query":"shared","collection":"alpha"}"""); var results = JsonDocument.Parse((string)ex.Out!.Body!).RootElement.GetProperty("results"); results.GetArrayLength().Should().Be(1); results[0].GetProperty("id").GetString().Should().Be("b"); } private sealed class StubEmbeddingProvider(Dictionary map) : IEmbeddingProvider { public string ProviderId => "stub"; public string ModelId => "stub"; public Task> EmbedAsync(IReadOnlyList inputs, CancellationToken ct = default) => Task.FromResult>( inputs.Select(i => map.TryGetValue(i, out var v) ? v : new float[] { 0f, 0f }).ToArray()); } [Fact] public async Task SemanticMode_RanksByCosine_NotKeyword() { IKnowledgeStore store = new InMemoryKnowledgeStore(); await store.UpsertManyAsync(new[] { new KnowledgeChunk { Id = "cats", Text = "about cats", Collection = "kb", Embedding = new float[] { 1f, 0f } }, new KnowledgeChunk { Id = "dogs", Text = "about dogs", Collection = "kb", Embedding = new float[] { 0f, 1f } }, }); // The query shares NO keyword with the chunk texts, but embeds near "cats". var emb = new StubEmbeddingProvider(new() { ["feline pets"] = new[] { 0.9f, 0.1f } }); await using var host = LiveLlmHost.Build(); await host.StartAsync(new KnowledgeSearchTool(new KnowledgeSearchOptions { Store = store, Collection = "kb", EmbeddingProvider = emb })); var ex = await host.SendAsync("direct:llm.knowledge_search", """{"query":"feline pets","top_k":1}"""); var results = JsonDocument.Parse((string)ex.Out!.Body!).RootElement.GetProperty("results"); results.GetArrayLength().Should().Be(1); results[0].GetProperty("id").GetString().Should().Be("cats"); // semantic, not substring } [Fact] public async Task NoMatch_ReturnsEmptyResults() { var store = await SeededStore(("1", "apple and banana", null)); await using var host = LiveLlmHost.Build(); await host.StartAsync(new KnowledgeSearchTool(new KnowledgeSearchOptions { Store = store })); var ex = await host.SendAsync("direct:llm.knowledge_search", """{"query":"zebra"}"""); JsonDocument.Parse((string)ex.Out!.Body!).RootElement.GetProperty("results") .GetArrayLength().Should().Be(0); ex.Out.Headers["llm.knowledge_search.hits"].Should().Be(0); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/LiveToolInvocationTests.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/DslShowcase/LiveToolInvocationTests.cs ---- using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.DslShowcase; /// /// Live integration suite that drives every redb.Route.Llm.Tools utility tool /// through a real provider's tool-use loop. Each test: /// /// Mounts the production tool route via new XxxTool(...). /// Hooks a so we can prove the model called the tool. /// Configures an agent that exposes only that one tool. /// Sends a question whose answer the model cannot reliably guess without the tool — /// the prompt embeds a fact the model would otherwise have to fabricate or compute. /// Asserts both the invocation happened and the final reply carries the tool's output. /// /// /// We use Groq llama-3.3-70b-versatile for the deterministic tools because its /// free-tier tool-use is the most reliable mix we have. Tavily uses Claude — Anthropic /// is the most consistent provider for chained tool-use that summarises external content. /// /// [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] public sealed class LiveToolInvocationTests { [EnvFact("REDB_LLM_GROQ_KEY")] public async Task Groq_JsonPathTool_ExtractsValueFromEmbeddedJson() { var spy = new ToolInvocationSpy(); await using var host = LiveLlmHost.Build(spy) .AddFactory("groq", new LlmConnectionFactory { Provider = "groq", ModelId = "llama-3.3-70b-versatile", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"), Temperature = 0.0, MaxTokens = 256 }); await host.StartAsync(new JsonPathTool(), r => { r.From("direct:agent") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Use the json_path tool when you need to read a specific value from a JSON document. " + "Reply with only the extracted value, no quotes, no extra words.") .To(LlmDsl.Factory("groq").Tools("json_path").MaxIterations(4).AsUri()) .To("mock:done"); }); var question = "Given this JSON: {\"order\":{\"items\":[{\"sku\":\"X-1\",\"qty\":3},{\"sku\":\"Z-9\",\"qty\":11}]}}. " + "What is the SKU of the second item? Use the json_path tool with path $.order.items[1].sku."; await host.SendAsync("direct:agent", question); spy.ForTool("json_path").Should().NotBeEmpty("the model must call json_path"); var lastOutput = spy.ForTool("json_path").Last().OutputJson ?? ""; lastOutput.Should().Contain("Z-9"); var sink = host.Mock("mock:done"); sink.ReceivedCount.Should().Be(1); ((string)sink.ReceivedExchanges[0].In.Body!).Should().Contain("Z-9"); } [EnvFact("REDB_LLM_GROQ_KEY")] public async Task Groq_XPathTool_ExtractsValueFromEmbeddedXml() { var spy = new ToolInvocationSpy(); await using var host = LiveLlmHost.Build(spy) .AddFactory("groq", new LlmConnectionFactory { Provider = "groq", ModelId = "llama-3.3-70b-versatile", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"), Temperature = 0.0, MaxTokens = 512 }); await host.StartAsync(new XPathTool(), r => { r.From("direct:agent") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "You must use the xpath tool to read values from XML. " + "After the tool returns its result, you MUST send a final assistant text message " + "containing only the extracted value. Never end the conversation without that final message.") .To(LlmDsl.Factory("groq").Tools("xpath").MaxIterations(6).AsUri()) .To("mock:done"); }); var question = "Given this XML: Dune" + "Foundation. " + "Use the xpath tool with the expression string(//book[@id='2']/title) to read the title of book #2, " + "then reply with just the title."; await host.SendAsync("direct:agent", question); spy.ForTool("xpath").Should().NotBeEmpty("the model must call xpath"); spy.ForTool("xpath").Last().OutputJson.Should().Contain("Foundation"); var sink = host.Mock("mock:done"); ((string)sink.ReceivedExchanges[0].In.Body!).Should().Contain("Foundation"); } [EnvFact("REDB_LLM_GROQ_KEY")] public async Task Groq_MathEvalTool_ComputesNonTrivialExpression() { var spy = new ToolInvocationSpy(); await using var host = LiveLlmHost.Build(spy) .AddFactory("groq", new LlmConnectionFactory { Provider = "groq", ModelId = "llama-3.3-70b-versatile", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"), Temperature = 0.0, MaxTokens = 256 }); await host.StartAsync(new MathEvalTool(), r => { r.From("direct:agent") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Always use the math_eval tool for arithmetic — never compute it yourself. " + "Reply with only the numeric result.") .To(LlmDsl.Factory("groq").Tools("math_eval").MaxIterations(4).AsUri()) .To("mock:done"); }); // 31337 * 271 = 8 492 327 — a value the model is unlikely to memorize, but // ExpressionResolver computes deterministically. await host.SendAsync("direct:agent", "What is 31337 multiplied by 271? Use the math_eval tool."); spy.ForTool("math_eval").Should().NotBeEmpty("the model must call math_eval"); spy.ForTool("math_eval").Last().OutputJson.Should().Contain("8492327"); var sink = host.Mock("mock:done"); ((string)sink.ReceivedExchanges[0].In.Body!).Should().Contain("8492327"); } [EnvFact("REDB_LLM_GROQ_KEY")] public async Task Groq_RegexExtractTool_ExtractsPatternFromText() { var spy = new ToolInvocationSpy(); await using var host = LiveLlmHost.Build(spy) .AddFactory("groq", new LlmConnectionFactory { Provider = "groq", ModelId = "llama-3.3-70b-versatile", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"), Temperature = 0.0, MaxTokens = 256 }); await host.StartAsync(new RegexExtractTool(), r => { r.From("direct:agent") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Use the regex_extract tool to pull a value out of a string. " + "Reply with only the extracted value.") .To(LlmDsl.Factory("groq").Tools("regex_extract").MaxIterations(4).AsUri()) .To("mock:done"); }); var question = "Given the text 'order id ORD-7421 was placed at 14:55', extract the order id " + "(matches the pattern ORD-\\d+) using the regex_extract tool."; await host.SendAsync("direct:agent", question); spy.ForTool("regex_extract").Should().NotBeEmpty("the model must call regex_extract"); spy.ForTool("regex_extract").Last().OutputJson.Should().Contain("ORD-7421"); var sink = host.Mock("mock:done"); ((string)sink.ReceivedExchanges[0].In.Body!).Should().Contain("ORD-7421"); } [EnvFact("REDB_LLM_ANT_API03_KEY", "REDB_LLM_TAVILY_KEY")] public async Task Claude_TavilyWebSearchTool_AnswersFromLiveSearch() { var spy = new ToolInvocationSpy(); await using var host = LiveLlmHost.Build(spy) .AddFactory("claude", new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-haiku-4-5", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_ANT_API03_KEY"), Temperature = 0.0, MaxTokens = 384 }); await host.StartAsync(new TavilyWebSearchTool(new TavilyWebSearchOptions { ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_TAVILY_KEY")!, MaxResults = 3, Timeout = TimeSpan.FromSeconds(15) }), r => { r.From("direct:agent") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "When the user asks for current real-world facts, call the web_search tool with a focused " + "query, then summarise the findings in one short sentence.") .To(LlmDsl.Factory("claude").Tools("web_search").MaxIterations(4).AsUri()) .To("mock:done"); }); // A factual query whose answer is stable enough to assert on — Tavily's // 'answer' field for capital-of-France queries reliably mentions Paris. await host.SendAsync("direct:agent", "What is the capital city of France?"); spy.ForTool("web_search").Should().NotBeEmpty("the model must call web_search"); var sink = host.Mock("mock:done"); sink.ReceivedCount.Should().Be(1); var reply = ((string)sink.ReceivedExchanges[0].In.Body!).ToLowerInvariant(); reply.Should().Contain("paris"); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/RegistryDrivenPromptTests.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/DslShowcase/RegistryDrivenPromptTests.cs ---- using redb.Route.Llm.Engine.Storage; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm.DslShowcase; /// /// The #name registry-ref is a framework-wide convention in redb.Route: /// connection factories, processors, and now prompts use the same shape. /// /// A leading # on ?systemPromptRef= or ?initialBodyRef= turns /// the URI parameter into a registry lookup. Resolution order: /// /// (latest version of the named template) /// 's named-object registry (a plain string) /// /// Plain values are still treated as literal prompts. /// /// /// The point: any other route — running on its own schedule — can rewrite the /// referenced key, and the next agent invocation picks up the fresh prompt /// without a route redeploy. Decoupling source-of-truth from caller is the /// same trick we already use for Kafka/S3 connection factories. /// /// We use the scripted here so the assertions can /// focus on which system prompt arrived at the provider — that is the /// behavior under test, not the model's reply quality. /// [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] public sealed class RegistryDrivenPromptTests { [Fact] public async Task SystemPromptRef_HashName_ResolvesFromRouteContextRegistry() { var fake = new FakeProvider().EnqueueText("ok").EnqueueText("ok"); await using var host = LiveLlmHost.Build() .AddFactory("scripted", new LlmConnectionFactory { Provider = "fake", ModelId = fake.ModelId, PrebuiltProvider = fake }); // Step 1 — populate the prompt by name. Any route, processor, or // bootstrap step in the application could do this. host.Context.AddToRegistry("style.terse", "Reply in fewer than 5 words."); await host.StartAsync(r => { r.From("direct:chat") .To("llm://scripted?systemPromptRef=#style.terse") .To("mock:done"); }); await host.SendAsync("direct:chat", "Hi."); fake.CapturedRequests[0].SystemPrompt.Should().Be("Reply in fewer than 5 words."); // Step 2 — a different actor mutates the same key; the next call sees // the new value with no changes to the LLM route. host.Context.AddToRegistry("style.terse", "Reply in French only."); await host.SendAsync("direct:chat", "Hi again."); fake.CapturedRequests[1].SystemPrompt.Should().Be("Reply in French only."); } [Fact] public async Task SystemPromptRef_HashName_PrefersPromptTemplateRegistry() { var fake = new FakeProvider().EnqueueText("ok"); var templates = new InMemoryPromptTemplateRegistry(); await templates.SetAsync(new PromptTemplate { Name = "watchdog", Version = "v1", Body = "You are a watchdog. Respond with PASS or FAIL only." }); await using var host = LiveLlmHost.Build() .AddFactory("scripted", new LlmConnectionFactory { Provider = "fake", ModelId = fake.ModelId, PrebuiltProvider = fake }); host.Context.AddService(typeof(IPromptTemplateRegistry), templates); // Decoy in the generic registry — must be *ignored* in favour of the // versioned IPromptTemplateRegistry hit. This is what makes the prompt // ref versionable and replayable in eval runs. host.Context.AddToRegistry("watchdog", "WRONG — should not be used."); await host.StartAsync(r => { r.From("direct:chat") .To("llm://scripted?systemPromptRef=#watchdog") .To("mock:done"); }); await host.SendAsync("direct:chat", "ping"); fake.CapturedRequests[0].SystemPrompt.Should().Be( "You are a watchdog. Respond with PASS or FAIL only."); } [Fact] public async Task SystemPromptRef_PlainValue_StaysLiteral() { var fake = new FakeProvider().EnqueueText("ok"); await using var host = LiveLlmHost.Build() .AddFactory("scripted", new LlmConnectionFactory { Provider = "fake", ModelId = fake.ModelId, PrebuiltProvider = fake }); // Even though "literal" exists in the registry, the URI ref has no // leading '#' — so it must arrive unchanged at the provider. host.Context.AddToRegistry("literal", "WRONG."); await host.StartAsync(r => { r.From("direct:chat") .To("llm://scripted?systemPromptRef=literal") .To("mock:done"); }); await host.SendAsync("direct:chat", "ping"); fake.CapturedRequests[0].SystemPrompt.Should().Be("literal"); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/SttSchemeTests.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/DslShowcase/SttSchemeTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm; using redb.Route.Llm.Providers; using redb.Route.Llm.Transcription; namespace redb.Route.Tests.Llm.DslShowcase; /// /// stt://<factory> scheme — transcribes the exchange body via the named /// connection factory. Driven with a stub /// (no live endpoint): recorded audio in, text out. /// public sealed class SttSchemeTests { /// Deterministic stub: reports back what it was handed. private sealed class StubStt(string text = "распознанный текст") : ITranscriptionProvider { public TranscriptionRequest? Last { get; private set; } public string ProviderId => "stub"; public string ModelId => "stub-speech"; public Task TranscribeAsync(TranscriptionRequest request, CancellationToken ct = default) { Last = request; return Task.FromResult(new TranscriptionResult(text, Language: "ru")); } } private static (RouteContext Ctx, ProducerTemplate Producer) Host(SttComponent component) { var sp = new ServiceCollection().BuildServiceProvider(); var ctx = new RouteContext(sp, contextId: "stt-scheme-test"); ctx.AddToRegistry("speech", new LlmConnectionFactory { Provider = "local", ModelId = "large-v3", BaseUrl = new Uri("http://127.0.0.1:8083/v1/") }); ctx.AddComponent(component); var producer = new ProducerTemplate(ctx); ctx.AddService(typeof(IProducerTemplate), producer); return (ctx, producer); } /// Drives one exchange through and hands back what came out. private static async Task RunAsync( ProducerTemplate producer, string uri, Action prepare) { var exchange = new Exchange(new Message(null)); prepare(exchange); return await producer.RequestAsync(uri, exchange); } private static IMessage Result(IExchange exchange) => exchange.Out ?? exchange.In; [Fact] public async Task RecordedBytes_BecomeText() { var (ctx, producer) = Host(new SttComponent { ProviderFactory = _ => new StubStt() }); ctx.AddRoutes(r => r.From("direct:v1").To("stt://speech")); await ctx.Start(); producer.Start(); var result = await producer.RequestBody("direct:v1", new byte[] { 1, 2, 3 }); result.Should().Be("распознанный текст"); await ctx.DisposeAsync(); } [Fact] public async Task AStreamBodyIsBufferedForTheUpload() { // Multipart needs a length; a chunked body is not something a speech endpoint takes. var stub = new StubStt(); var (ctx, producer) = Host(new SttComponent { ProviderFactory = _ => stub }); ctx.AddRoutes(r => r.From("direct:v2").To("stt://speech")); await ctx.Start(); producer.Start(); await producer.RequestBody("direct:v2", new MemoryStream([9, 8, 7])); stub.Last!.Value.Audio.ToArray().Should().Equal(9, 8, 7); await ctx.DisposeAsync(); } [Fact] public async Task TheFileNameFollowsTheContentType() { // The transport that delivered the recording already knows the format. Deriving the // upload name from it is what lets a voice route work with no configuration at all — // and getting it wrong is a decode error, not a worse transcription. var stub = new StubStt(); var (ctx, producer) = Host(new SttComponent { ProviderFactory = _ => stub }); ctx.AddRoutes(r => r.From("direct:v3").To("stt://speech")); await ctx.Start(); producer.Start(); await RunAsync(producer, "direct:v3", exchange => { exchange.In.Body = new byte[] { 1 }; exchange.In.ContentType = "audio/ogg"; }); stub.Last!.Value.FileName.Should().Be("audio.oga"); await ctx.DisposeAsync(); } [Fact] public async Task HeadersOverrideTheEndpointOptions() { var stub = new StubStt(); var (ctx, producer) = Host(new SttComponent { ProviderFactory = _ => stub }); ctx.AddRoutes(r => r.From("direct:v4").To("stt://speech?language=en&fileName=fixed.wav")); await ctx.Start(); producer.Start(); await RunAsync(producer, "direct:v4", exchange => { exchange.In.Body = new byte[] { 1 }; exchange.In.Headers[LlmHeaders.TranscriptionLanguage] = "ru"; exchange.In.Headers[LlmHeaders.TranscriptionFileName] = "voice.oga"; }); stub.Last!.Value.Language.Should().Be("ru"); stub.Last!.Value.FileName.Should().Be("voice.oga"); await ctx.DisposeAsync(); } [Fact] public async Task TheAnswerIsDescribedByLength_NeverByContent() { const string recognised = "шесть слов, а может и меньше"; var stub = new StubStt(recognised); var (ctx, producer) = Host(new SttComponent { ProviderFactory = _ => stub }); ctx.AddRoutes(r => r.From("direct:v5").To("stt://speech")); await ctx.Start(); producer.Start(); var result = Result(await RunAsync(producer, "direct:v5", e => e.In.Body = new byte[] { 1 })); result.Headers[LlmHeaders.TranscriptionChars].Should().Be(recognised.Length); result.Headers[LlmHeaders.TranscriptionModel].Should().Be("stub-speech"); result.Headers[LlmHeaders.TranscriptionProvider].Should().Be("stub"); result.Headers[LlmHeaders.TranscriptionLanguage].Should().Be("ru"); // A header travels into logs, audits and dead letters; a transcription is the // speaker's own words. Nothing here repeats them. result.Headers.Values .Select(v => v?.ToString() ?? string.Empty) .Should().NotContain(s => s.Contains("слов")); await ctx.DisposeAsync(); } [Fact] public async Task ANonAudioBodySaysWhatToPutThere() { var (ctx, producer) = Host(new SttComponent { ProviderFactory = _ => new StubStt() }); ctx.AddRoutes(r => r.From("direct:v6").To("stt://speech")); await ctx.Start(); producer.Start(); var act = async () => await producer.RequestBody("direct:v6", "это текст, а не запись"); (await act.Should().ThrowAsync()).And.ToString().Should().Contain("telegram://download"); await ctx.DisposeAsync(); } [Fact] public void TheSchemeIsProducerOnly() { var component = new SttComponent(); var endpoint = component.CreateEndpoint(EndpointUriParser.Parse("stt://speech")); var act = () => endpoint.CreateConsumer(Substitute.For()); act.Should().Throw(); } [Fact] public void AnEndpointWithoutAFactoryRefusesToStart() { var component = new SttComponent(); var act = () => component.CreateEndpoint(EndpointUriParser.Parse("stt://")); act.Should().Throw().WithMessage("*connection factory*"); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/TavilyWebSearchToolTests.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/DslShowcase/TavilyWebSearchToolTests.cs ---- using AwesomeAssertions; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm.DslShowcase; /// /// Drives against a local HTTP server that mimics the Tavily /// search API. Verifies the request shape (POST + api_key + query) and that the tool reshapes /// the response to {answer, results} for the model. /// public sealed class TavilyWebSearchToolTests { [Fact] public async Task TavilyWebSearchTool_PostsQueryAndShapesResponse() { using var server = new LocalHttpServer { ResponseBody = """ { "answer": "Paris is the capital of France.", "results": [ { "title": "France", "url": "https://en.wikipedia.org/wiki/France", "content": "Paris is the capital city.", "score": 0.9 }, { "title": "Paris", "url": "https://en.wikipedia.org/wiki/Paris", "content": "Capital of France.", "score": 0.8 } ] } """ }; await using var host = LiveLlmHost.Build(); await host.StartAsync(new TavilyWebSearchTool(new TavilyWebSearchOptions { ApiKey = "test-key", Endpoint = server.BaseUrl + "search", MaxResults = 2, Timeout = TimeSpan.FromSeconds(5) })); host.ToolRegistry.Get("web_search").Should().NotBeNull(); var ex = await host.SendAsync("direct:llm.web_search", """{"query":"capital of France"}"""); var body = (string)ex.Out!.Body!; body.Should().Contain("\"answer\":\"Paris is the capital of France.\""); body.Should().Contain("https://en.wikipedia.org/wiki/France"); body.Should().Contain("https://en.wikipedia.org/wiki/Paris"); body.Should().NotContain("score"); ex.Out.Headers["llm.web_search.results"].Should().Be(2); server.RequestPaths.Should().ContainSingle().Which.Should().Contain("/search"); } [Fact] public void TavilyWebSearchTool_RequiresApiKey() { var act = () => new TavilyWebSearchTool(new TavilyWebSearchOptions()); act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/ThinkingProbeLiveTests.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/DslShowcase/ThinkingProbeLiveTests.cs ---- using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; using redb.Route.Llm.Providers; using redb.Route.Tests.Llm.TestHelpers; using Xunit.Abstractions; namespace redb.Route.Tests.Llm.DslShowcase; /// /// Phase 16.0a — the live half of the provider matrix: what the wire actually carries for the model's /// thinking block, and what happens when that block is missing from a tool turn. /// /// The probes speak raw HTTP instead of going through on purpose: /// until 16.1 the connector neither returns a thinking block nor can be asked to send one back, so a /// connector test could not report the defect — it would only report the connector. The provider is the /// evidence here, and the probes are the smallest shape that asks it the questions 16.0 exists for: /// what comes back, what must be sent back, what happens when the block is dropped, and whether a /// conversation whose tool turns never carried one can still be continued. /// /// /// Nothing here prints a secret or the thinking text. The artifact records field names, lengths, the /// first 16 hex digits of the block's SHA-256 (two runs can be compared without reading thoughts) and /// the provider's error text. Findings land in 16-0a-probe.json next to the test binary. /// /// /// A probe whose history already carries the tool result expects an answer; only the opening turns /// expect a call. The verdicts are read that way, and the artifact records both the shapes sent and /// what came back, so a reader can disagree with the reading. /// /// /// tool_choice is deliberately absent from the tool probes: the first live run of this wave /// (2026-09-14) showed thinking mode answering 400 invalid_request_error: Thinking mode does not /// support this tool_choice for "required", which would have masked every other finding. The /// system prompt asks for the tool instead, and one probe keeps the pinned form on purpose so the /// constraint stays proven rather than remembered. /// /// [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] public sealed class ThinkingProbeLiveTests { private const string EnvVar = "REDB_LLM_DEEPSEEK"; private const string Provider = "deepseek"; private const string ToolName = "order_lookup"; private const int MaxTokens = 512; /// /// Aliases DeepSeek documents but no longer lists. Probed on their own, because "documented" and /// "still routed" stopped being the same thing: on 2026-09-14 GET /models offers /// deepseek-flash and deepseek-v4-pro and nothing else. /// private static readonly string[] LegacyAliases = ["deepseek-reasoner", "deepseek-chat"]; private readonly ITestOutputHelper _output; /// Creates the probe with xUnit's output sink. public ThinkingProbeLiveTests(ITestOutputHelper output) => _output = output; [EnvFact(EnvVar)] public async Task DeepSeek_Probes_RecordWhatTheThinkingPathDoes() { var key = Environment.GetEnvironmentVariable(EnvVar)!; var baseUrl = OpenAiProvider.ResolveDefaultBaseUrl(Provider); var report = new ProbeReport { Provider = Provider, Endpoint = new Uri(baseUrl, "chat/completions").ToString(), StartedUtc = DateTimeOffset.UtcNow }; using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(120) }; http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key); try { var available = await ListModelsAsync(http, baseUrl, report); // Whatever the endpoint lists is what gets probed: "ask /models first" is step zero of 16.0, // and the reason this wave discovered that the models its plan named no longer exist. foreach (var model in available.Where(IsChatModel)) { var withBlock = await ProbeWithBlockAsync(http, baseUrl, model, report); await ProbeWithBlockReplayAsync(http, baseUrl, model, withBlock, report); await ProbeWithoutBlockAsync(http, baseUrl, model, withBlock, report, withTools: true); await ProbeWithoutBlockWithContentAsync(http, baseUrl, model, withBlock, report); await ProbeWithoutBlockAsync(http, baseUrl, model, withBlock, report, withTools: false); await ProbeOldHistoryAsync(http, baseUrl, model, report); await ProbeToolChoiceAsync(http, baseUrl, model, report); } // Aliases the endpoint no longer lists get one question: does the name still route at all? foreach (var alias in LegacyAliases.Where(a => !available.Any(id => id.Equals(a, StringComparison.OrdinalIgnoreCase)))) await SendAsync(http, baseUrl, ProbeId.AliasWithBlock, ChatBody(alias, new JsonArray(SystemPrompt(), UserQuestion()), withTools: true), expectToolCall: true, report); } finally { report.FinishedUtc = DateTimeOffset.UtcNow; WriteArtifact(report); } _output.WriteLine($"16.0a artifact: {ArtifactPath}"); report.ModelListStatus.Should().Be(200, "GET /models is the cheapest proof that the key is live"); report.ModelsAvailable.Should().NotBeEmpty("the endpoint must list at least one model to probe"); report.Probes.Should().NotBeEmpty(); report.Probes.Where(p => p.Verdict != ProbeVerdict.NotApplicable) .Should().OnlyContain(p => p.Status > 0 && p.Status < 500, "a 5xx is infrastructure, not a provider verdict"); report.Probes.Should().OnlyContain(p => p.Verdict != ProbeVerdict.Unknown, "every probe must end in a recorded verdict — that record is the deliverable of 16.0a"); report.Probes.Count(p => p.Probe == ProbeId.WithBlock && p.Status == 200).Should().BePositive( "at least one candidate model must answer a tool turn, or nothing was learned"); File.Exists(ArtifactPath).Should().BeTrue("the artifact is what the matrix is filled from"); } /// Asks the endpoint which models exist, so the probes run on names that are real. private static async Task> ListModelsAsync(HttpClient http, Uri baseUrl, ProbeReport report) { var ids = new List(); using var response = await http.GetAsync(new Uri(baseUrl, "models")); var body = await response.Content.ReadAsStringAsync(); report.ModelListStatus = (int)response.StatusCode; if (response.IsSuccessStatusCode && TryParse(body) is JsonObject root && root["data"] is JsonArray data) foreach (var entry in data) if (entry?["id"]?.GetValue() is { Length: > 0 } id && !ids.Contains(id, StringComparer.OrdinalIgnoreCase)) ids.Add(id); report.ModelsAvailable = ids.ToArray(); return ids; } /// Embedding and other non-chat entries are listed too; probing them would only add noise. private static bool IsChatModel(string id) => !id.Contains("embed", StringComparison.OrdinalIgnoreCase); /// First question: a tool turn with nothing replayed — what does the answer carry? private static async Task ProbeWithBlockAsync( HttpClient http, Uri baseUrl, string model, ProbeReport report) { var body = ChatBody(model, new JsonArray(SystemPrompt(), UserQuestion()), withTools: true); return await SendAsync(http, baseUrl, ProbeId.WithBlock, body, expectToolCall: true, report); } /// /// Second question: replay the block we just received — the shape 16.2 must be able to reproduce. /// Skipped, with a reason, when the model returned nothing to replay. /// private static async Task ProbeWithBlockReplayAsync( HttpClient http, Uri baseUrl, string model, ProbeOutcome? withBlock, ProbeReport report) { if (withBlock?.ThinkingText is not { Length: > 0 } thinking || withBlock.ToolCalls.Count == 0) { report.Probes.Add(new ProbeOutcome { Probe = ProbeId.WithBlockReplay, Model = model, Verdict = ProbeVerdict.NotApplicable, VerdictDetail = string.IsNullOrEmpty(withBlock?.ThinkingText) ? "the model returned no thinking block, so there is nothing to replay" : "the model returned no tool call to attach the block to" }); return; } var call = withBlock.ToolCalls[0]; var messages = new JsonArray( SystemPrompt(), UserQuestion(), AssistantTurn(call, thinking, withBlock.ContentText), ToolResult(call, "shipped")); await SendAsync(http, baseUrl, ProbeId.WithBlockReplay, ChatBody(model, messages, withTools: true), expectToolCall: false, report); } /// /// Third question, the K4 test: the same tool turn with the block dropped — exactly what the connector /// sends today. Three shapes, because the answer turned out to depend on the turn rather than on /// tools: as the model returned it minus the block, with a non-empty content, and with no /// tool surface declared at all (the control for the documented "the 400 needs tools" rule). /// private static async Task ProbeWithoutBlockAsync( HttpClient http, Uri baseUrl, string model, ProbeOutcome? withBlock, ProbeReport report, bool withTools) { var call = withBlock?.ToolCalls.FirstOrDefault() ?? SyntheticCall(); var messages = new JsonArray( SystemPrompt(), UserQuestion(), AssistantTurn(call, thinking: null, withBlock?.ContentText), ToolResult(call, "shipped")); await SendAsync(http, baseUrl, withTools ? ProbeId.WithoutBlockTools : ProbeId.WithoutBlockNoTools, ChatBody(model, messages, withTools), expectToolCall: false, report); } /// /// The same dropped-block turn, but with the visible content the model produced kept in place: /// if the provider validates the block only when the assistant turn has text, this is where it says so. /// private static async Task ProbeWithoutBlockWithContentAsync( HttpClient http, Uri baseUrl, string model, ProbeOutcome? withBlock, ProbeReport report) { var call = withBlock?.ToolCalls.FirstOrDefault() ?? SyntheticCall(); var messages = new JsonArray( SystemPrompt(), UserQuestion(), AssistantTurn(call, thinking: null, withBlock?.ContentText ?? "Let me look that up."), ToolResult(call, "shipped")); await SendAsync(http, baseUrl, ProbeId.WithoutBlockContent, ChatBody(model, messages, withTools: true), expectToolCall: false, report); } /// /// Fourth question: a conversation created before the phase — its tool turns never carried a block. /// Continuing it is the class of the 2026-09-07 incident. /// private static async Task ProbeOldHistoryAsync(HttpClient http, Uri baseUrl, string model, ProbeReport report) { var call = SyntheticCall(); var messages = new JsonArray( SystemPrompt(), UserQuestion(), AssistantTurn(call, thinking: null), ToolResult(call, "shipped"), AssistantText("shipped"), new JsonObject { ["role"] = "user", ["content"] = "And what about order 43?" }); await SendAsync(http, baseUrl, ProbeId.OldHistory, ChatBody(model, messages, withTools: true), expectToolCall: true, report); } /// /// Fifth question, learned the hard way on the first run: thinking mode refuses a pinned tool_choice. /// Kept as a probe so the constraint stays proven — the connector must never send /// tool_choice: "required" to a thinking model. /// private static async Task ProbeToolChoiceAsync(HttpClient http, Uri baseUrl, string model, ProbeReport report) { var body = ChatBody(model, new JsonArray(SystemPrompt(), UserQuestion()), withTools: true); body["tool_choice"] = "required"; await SendAsync(http, baseUrl, ProbeId.ToolChoiceRequired, body, expectToolCall: true, report); } /// Sends one probe and records everything the matrix needs — and nothing it must not carry. private static async Task SendAsync( HttpClient http, Uri baseUrl, string probeId, JsonObject body, bool expectToolCall, ProbeReport report) { var outcome = new ProbeOutcome { Probe = probeId, Model = body["model"]!.GetValue(), Request = Describe(body) }; using var content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json"); using var response = await http.PostAsync(new Uri(baseUrl, "chat/completions"), content); var text = await response.Content.ReadAsStringAsync(); outcome.Status = (int)response.StatusCode; if (response.IsSuccessStatusCode) Capture(outcome, TryParse(text), expectToolCall); else Reject(outcome, text); report.Probes.Add(outcome); return outcome; } /// Builds the request body in the shape the connector sends, minus everything it does not send. private static JsonObject ChatBody(string model, JsonArray messages, bool withTools) { var body = new JsonObject { ["model"] = model, ["messages"] = messages, ["max_tokens"] = MaxTokens, ["stream"] = false }; if (!withTools) return body; // No tool_choice: thinking mode refuses the pinned form (see the class remarks), and the prompt // already asks for the tool by name. body["tools"] = ToolDefinitions(); return body; } /// Roles of the request plus whether the tool surface was declared — the "what we sent" column. private static string Describe(JsonObject body) { var messages = (JsonArray)body["messages"]!; var roles = messages.Select(m => { var role = m?["role"]?.GetValue() ?? "?"; if (m?["tool_calls"] is not null) role += m?["reasoning_content"] is not null ? "(tool_calls+thinking)" : "(tool_calls)"; return role; }); return $"{string.Join(",", roles)} | tools={(body["tools"] is null ? "no" : "yes")}"; } private static void Capture(ProbeOutcome outcome, JsonNode? json, bool expectToolCall) { if (json?["choices"] is not JsonArray { Count: > 0 } choices || choices[0]?["message"]?.AsObject() is not { } message) { outcome.Verdict = ProbeVerdict.Unknown; outcome.VerdictDetail = "200 without a message to read"; return; } var first = choices[0]!.AsObject(); outcome.ResponseModel = json["model"]?.GetValue(); outcome.SystemFingerprint = json["system_fingerprint"]?.GetValue(); outcome.FinishReason = first["finish_reason"]?.GetValue(); outcome.MessageKeys = message.Select(p => p.Key).OrderBy(k => k, StringComparer.Ordinal).ToArray(); var thinking = message["reasoning_content"]?.GetValue(); if (thinking is not null) outcome.ThinkingField = "reasoning_content"; else if (message["reasoning"] is JsonValue other) { outcome.ThinkingField = "reasoning"; thinking = other.GetValue(); } outcome.ThinkingPresent = !string.IsNullOrEmpty(thinking); outcome.ThinkingLength = thinking?.Length ?? 0; outcome.ThinkingSha256 = thinking is { Length: > 0 } ? Sha256(thinking) : null; outcome.ThinkingText = thinking; outcome.ContentLength = message["content"]?.GetValue()?.Length ?? 0; outcome.ContentText = message["content"]?.GetValue(); if (message["tool_calls"] is JsonArray calls) { outcome.ToolCallCount = calls.Count; foreach (var call in calls) { if (call?["function"] is not JsonObject fn) continue; outcome.ToolCalls.Add(new ToolCallShape { Id = call["id"]?.GetValue() ?? string.Empty, Name = fn["name"]?.GetValue() ?? string.Empty, Arguments = fn["arguments"]?.GetValue() ?? string.Empty }); } } if (json["usage"] is JsonObject usage) { outcome.PromptTokens = usage["prompt_tokens"]?.GetValue(); outcome.CompletionTokens = usage["completion_tokens"]?.GetValue(); outcome.ReasoningTokens = usage["completion_tokens_details"]?["reasoning_tokens"]?.GetValue(); } var degraded = expectToolCall && outcome.ToolCallCount == 0; outcome.Verdict = degraded ? ProbeVerdict.AcceptedDegraded : ProbeVerdict.Accepted; outcome.VerdictDetail = degraded ? "answered without calling the tool the prompt asked for" : "answered"; } private static void Reject(ProbeOutcome outcome, string body) { var error = TryParse(body)?["error"] as JsonObject; outcome.ErrorType = Truncate(error?["type"]?.GetValue(), 120); outcome.ErrorMessage = Truncate(error?["message"]?.GetValue() ?? body, 400); outcome.Verdict = ProbeVerdict.Rejected; outcome.VerdictDetail = $"HTTP {outcome.Status}: {outcome.ErrorType ?? outcome.ErrorMessage}"; } private static JsonObject SystemPrompt() => new() { ["role"] = "system", ["content"] = $"Use the {ToolName} tool to look up the order, then reply with only the status word." }; private static JsonObject UserQuestion() => new() { ["role"] = "user", ["content"] = "What is the status of order 42?" }; /// An assistant tool turn — with the thinking block only when the probe means to send one. private static JsonObject AssistantTurn(ToolCallShape call, string? thinking, string? content = null) { var message = new JsonObject { ["role"] = "assistant", ["content"] = content, ["tool_calls"] = new JsonArray(new JsonObject { ["id"] = call.Id, ["type"] = "function", ["function"] = new JsonObject { ["name"] = call.Name, ["arguments"] = call.Arguments } }) }; if (thinking is { Length: > 0 }) message["reasoning_content"] = thinking; return message; } private static JsonObject ToolResult(ToolCallShape call, string status) => new() { ["role"] = "tool", ["tool_call_id"] = call.Id, ["content"] = $"{{\"status\":\"{status}\"}}" }; private static JsonObject AssistantText(string text) => new() { ["role"] = "assistant", ["content"] = text }; /// A tool call the answer did not supply, so every probe still runs when the first one fails. private static ToolCallShape SyntheticCall() => new() { Id = "call_probe_1", Name = ToolName, Arguments = "{\"orderId\":\"42\"}" }; private static JsonArray ToolDefinitions() => new( new JsonObject { ["type"] = "function", ["function"] = new JsonObject { ["name"] = ToolName, ["description"] = "Look up an order by id and return its status.", ["parameters"] = JsonNode.Parse( """{"type":"object","properties":{"orderId":{"type":"string"}},"required":["orderId"]}""") } }); private static JsonNode? TryParse(string text) { try { return JsonNode.Parse(text); } catch (JsonException) { return null; } } /// First 16 hex digits of SHA-256 — enough to compare two runs without carrying the thought. private static string Sha256(string text) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant()[..16]; private static string? Truncate(string? text, int max) => text is null ? null : text.Length <= max ? text : text[..max] + "..."; /// Where the findings land: next to the test binary, so bin keeps them out of the repo. private static string ArtifactPath => Path.Combine(AppContext.BaseDirectory, "16-0a-probe.json"); private static void WriteArtifact(ProbeReport report) { var json = JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); File.WriteAllText(ArtifactPath, json); } } /// Ids of the probes; the matrix cites these, so they are stable strings, not enum numbers. internal static class ProbeId { /// A tool turn with nothing replayed. public const string WithBlock = "with-block"; /// The block we received, sent back on the next tool turn. public const string WithBlockReplay = "with-block-replay"; /// The K4 probe: tool turn without its block, tool surface declared. public const string WithoutBlockTools = "without-block-tools"; /// Control for K4: same turn, no tool surface declared. public const string WithoutBlockNoTools = "without-block-no-tools"; /// Same turn with its visible content kept, block still dropped. public const string WithoutBlockContent = "without-block-content"; /// A conversation created before the phase, continued. public const string OldHistory = "old-history"; /// An alias the endpoint no longer lists, asked the first question only. public const string AliasWithBlock = "alias-with-block"; /// A tool turn with tool_choice: "required" — the form thinking mode refuses. public const string ToolChoiceRequired = "tool-choice-required"; } /// Verdict vocabulary shared by the artifact and the matrix. internal static class ProbeVerdict { /// Nothing was learned — the probe must not end here. public const string Unknown = "unknown"; /// 2xx and the expected shape came back. public const string Accepted = "accepted"; /// 2xx but thinner than the request pinned — the "degraded answer" outcome. public const string AcceptedDegraded = "accepted-degraded"; /// Provider refused the request; the error text is in the outcome. public const string Rejected = "rejected"; /// The probe could not be asked (nothing to replay) — a recorded answer, not a gap. public const string NotApplicable = "not-applicable"; } /// The tool call of an assistant turn, in the shape it travels on the wire. internal sealed class ToolCallShape { /// Provider-assigned call id. public string Id { get; set; } = string.Empty; /// Function name. public string Name { get; set; } = string.Empty; /// Function arguments as a JSON string. public string Arguments { get; set; } = string.Empty; } /// One probe: what was sent, what came back, what it means. internal sealed class ProbeOutcome { /// Probe id — see . public string Probe { get; set; } = string.Empty; /// Model the probe ran on. public string Model { get; set; } = string.Empty; /// Model id the provider says it served — how an alias resolves. public string? ResponseModel { get; set; } /// Backend fingerprint, when the provider exposes one. public string? SystemFingerprint { get; set; } /// HTTP status of the response. public int Status { get; set; } /// Verdict — see . public string Verdict { get; set; } = ProbeVerdict.Unknown; /// One line explaining the verdict. public string? VerdictDetail { get; set; } /// Roles and tool surface of the request we sent. public string Request { get; set; } = string.Empty; /// Provider's finish_reason. public string? FinishReason { get; set; } /// Keys present on the assistant message — how the provider names its fields. public string[] MessageKeys { get; set; } = []; /// Name of the field carrying the thinking block, when one came. public string? ThinkingField { get; set; } /// Whether a non-empty thinking block came back. public bool ThinkingPresent { get; set; } /// Length of the thinking block in characters. public int ThinkingLength { get; set; } /// Short hash of the thinking block, for run-to-run comparison. public string? ThinkingSha256 { get; set; } /// Length of the visible answer. public int ContentLength { get; set; } /// Number of tool calls in the answer. public int ToolCallCount { get; set; } /// The tool calls themselves, reused when a later probe replays this turn. public List ToolCalls { get; set; } = []; /// Prompt tokens reported by the provider. public int? PromptTokens { get; set; } /// Completion tokens reported by the provider. public int? CompletionTokens { get; set; } /// Reasoning tokens, when the provider splits them out. public int? ReasoningTokens { get; set; } /// Provider error type, when the request was refused. public string? ErrorType { get; set; } /// Provider error text, truncated. public string? ErrorMessage { get; set; } /// /// The block itself, kept in memory so the replay probe can send it back. Never written to the /// artifact: thoughts are the model's, and this file is meant to be committed as evidence. /// [JsonIgnore] public string? ThinkingText { get; set; } /// The visible answer of the turn, kept in memory so the dropped-block probe can keep it. [JsonIgnore] public string? ContentText { get; set; } } /// The whole 16.0a run: which models answered, and every probe's outcome. internal sealed class ProbeReport { /// Provider alias probed. public string Provider { get; set; } = string.Empty; /// Chat Completions endpoint the probes used. public string Endpoint { get; set; } = string.Empty; /// When the run started. public DateTimeOffset StartedUtc { get; set; } /// When the run finished. public DateTimeOffset FinishedUtc { get; set; } /// HTTP status of GET /models. public int ModelListStatus { get; set; } /// Model ids the endpoint offers. public string[] ModelsAvailable { get; set; } = []; /// Every probe the run performed, in order. public List Probes { get; set; } = []; } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/ToolRouteTests.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/DslShowcase/ToolRouteTests.cs ---- using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.DslShowcase; /// /// The point of redb.Route.Llm is that a tool is just a route. This /// suite proves it end-to-end against a live provider: an /// is mounted with .AsLlmTool, then a chat route asks the model to call /// it and return the payload. The agent loop runs entirely inside the route /// engine — no manual JSON shuffling. /// /// We only run this against Groq because Groq's tool-use on Llama 3.3 70B is /// the most reliable free tier we have. Other providers either rate-limit /// aggressively (Gemini), tool-use is gated behind a paid plan (OpenAI), /// or the free model refuses tool calls some fraction of the time /// (Mistral small). Adding more providers here is just an extra /// — the DSL doesn't change. /// /// [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] public sealed class ToolRouteTests { [EnvFact("REDB_LLM_GROQ_KEY")] public async Task Groq_ToolLoop_RoutedTool_DeliversPayload() { await using var host = LiveLlmHost.Build() .AddFactory("groq", new LlmConnectionFactory { Provider = "groq", ModelId = "llama-3.3-70b-versatile", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_GROQ_KEY"), Temperature = 0.0, MaxTokens = 256 }); // Tool: takes {"q": string}, returns {"answer": ""}. var echo = new EchoToolRoute( toolName: "lookup", description: "Look up a fact for the given query and return JSON {\"answer\": ...}.", inputSchema: """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}""", replyJson: """{"answer":"the magic word is rosebud"}"""); await host.StartAsync(echo, r => { r.From("direct:agent") .Process(e => e.In.Headers[LlmHeaders.SystemPrompt] = "Use the lookup tool to find the magic word, then reply with that word verbatim and nothing else.") .To(LlmDsl.Factory("groq").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done"); }); await host.SendAsync("direct:agent", "What is the magic word?"); // The agent must have called the tool at least once. echo.CapturedInputs.Should().NotBeEmpty(); var sink = host.Mock("mock:done"); sink.ReceivedCount.Should().Be(1); var reply = ((string)sink.ReceivedExchanges[0].In.Body!).ToLowerInvariant(); reply.Should().Contain("rosebud"); } } Path: redb-route/tests/redb.Route.Tests.Llm/DslShowcase/UtilityToolTests.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/DslShowcase/UtilityToolTests.cs ---- using AwesomeAssertions; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm.DslShowcase; /// /// Exercises the framework-backed utility tools shipped in redb.Route.Llm.Tools. /// Each tool is a thin wrapper over a redb.Route primitive — /// over JsonPathExpression, over XPathExpression, /// over ExpressionResolver, /// over System.Text.RegularExpressions.Regex with a ReDoS guard. /// /// The tools mount direct: routes via .AsLlmTool(...), so we can drive them /// straight through the route pipeline without involving an LLM provider. /// /// public sealed class UtilityToolTests { [Fact] public async Task JsonPathTool_RegistersDescriptor_AndExtractsValue() { await using var host = LiveLlmHost.Build(); await host.StartAsync(new JsonPathTool(new JsonPathOptions())); var descriptor = host.ToolRegistry.Get("json_path"); descriptor.Should().NotBeNull(); descriptor!.Capability.Safety.SideEffect.Should().Be(ToolSideEffect.ReadOnly); descriptor.Capability.Safety.Cost.Should().Be(ToolCostClass.Cheap); var input = """{"json":"{\"items\":[{\"name\":\"alpha\"},{\"name\":\"beta\"}]}","path":"$.items[1].name"}"""; var ex = await host.SendAsync("direct:llm.json_path", input); ((string)ex.Out!.Body!).Should().Be("\"beta\""); ex.Out.Headers["llm.json_path.matched"].Should().Be(true); var miss = """{"json":"{\"x\":1}","path":"$.y"}"""; var exMiss = await host.SendAsync("direct:llm.json_path", miss); ((string)exMiss.Out!.Body!).Should().Be("null"); exMiss.Out.Headers["llm.json_path.matched"].Should().Be(false); } [Fact] public async Task JsonPathTool_SupportsRecursiveDescentAndFilters() { await using var host = LiveLlmHost.Build(); await host.StartAsync(new JsonPathTool()); // Recursive descent — pick all 'name' properties anywhere in the tree. var rec = """{"json":"{\"a\":{\"name\":\"x\"},\"b\":[{\"name\":\"y\"}]}","path":"$..name"}"""; var exRec = await host.SendAsync("direct:llm.json_path", rec); ((string)exRec.Out!.Body!).Should().Be("[\"x\",\"y\"]"); // Filter — items priced over 10. var filt = """{"json":"{\"items\":[{\"p\":5},{\"p\":12},{\"p\":20}]}","path":"$.items[?(@.p > 10)].p"}"""; var exFilt = await host.SendAsync("direct:llm.json_path", filt); ((string)exFilt.Out!.Body!).Should().Be("[12,20]"); } [Fact] public async Task XPathTool_ExtractsValueFromXmlDocument() { await using var host = LiveLlmHost.Build(); await host.StartAsync(new XPathTool()); host.ToolRegistry.Get("xpath").Should().NotBeNull(); var input = """{"xml":"DuneFoundation","xpath":"string(//book[1]/title)"}"""; var ex = await host.SendAsync("direct:llm.xpath", input); ((string)ex.Out!.Body!).Should().Be("Dune"); ex.Out.Headers["llm.xpath.matched"].Should().Be(true); var miss = """{"xml":"","xpath":"string(//missing)"}"""; var exMiss = await host.SendAsync("direct:llm.xpath", miss); // XPath string() on no-match returns empty string, not null — but our tool // surfaces it as an empty string body (matched=true, value=""). ((string)exMiss.Out!.Body!).Should().Be(""); } [Fact] public async Task RegexExtractTool_ReturnsFirstAndAllMatches() { await using var host = LiveLlmHost.Build(); await host.StartAsync(new RegexExtractTool(new RegexExtractOptions())); host.ToolRegistry.Get("regex_extract").Should().NotBeNull(); var first = """{"text":"order 42 and 7","pattern":"\\d+"}"""; var ex1 = await host.SendAsync("direct:llm.regex_extract", first); ((string)ex1.Out!.Body!).Should().Be("\"42\""); var all = """{"text":"order 42 and 7","pattern":"\\d+","all":true}"""; var exAll = await host.SendAsync("direct:llm.regex_extract", all); ((string)exAll.Out!.Body!).Should().Be("[\"42\",\"7\"]"); var named = """{"text":"name=alice","pattern":"name=(?\\w+)","group":"who"}"""; var exNamed = await host.SendAsync("direct:llm.regex_extract", named); ((string)exNamed.Out!.Body!).Should().Be("\"alice\""); var miss = """{"text":"abc","pattern":"\\d+"}"""; var exMiss = await host.SendAsync("direct:llm.regex_extract", miss); ((string)exMiss.Out!.Body!).Should().Be("null"); } [Fact] public async Task MathEvalTool_DelegatesToExpressionResolver() { await using var host = LiveLlmHost.Build(); await host.StartAsync(new MathEvalTool(new MathEvalOptions())); host.ToolRegistry.Get("math_eval").Should().NotBeNull(); async Task EvalAsync(string expr) { var body = $"{{\"expression\":\"{expr}\"}}"; var ex = await host.SendAsync("direct:llm.math_eval", body); return (string)ex.Out!.Body!; } (await EvalAsync("2 * (3 + 4)")).Should().Be("14"); (await EvalAsync("100 / 4")).Should().Be("25"); (await EvalAsync("42")).Should().Be("42"); (await EvalAsync("'hello'")).Should().Be("\"hello\""); } } Path: redb-route/tests/redb.Route.Tests.Llm/EmbeddingProviderTests.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/EmbeddingProviderTests.cs ---- using System.Net; using System.Text; using System.Text.Json; using AwesomeAssertions; using redb.Route.Llm; using redb.Route.Llm.Providers; namespace redb.Route.Tests.Llm; /// /// request/response mapping, driven through a /// stub — no live key, deterministic. /// public sealed class EmbeddingProviderTests { private sealed class StubHandler(string responseJson, HttpStatusCode status = HttpStatusCode.OK) : HttpMessageHandler { public HttpRequestMessage? LastRequest { get; private set; } public string? LastBody { get; private set; } protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) { LastRequest = request; LastBody = request.Content is null ? null : await request.Content.ReadAsStringAsync(ct); return new HttpResponseMessage(status) { Content = new StringContent(responseJson, Encoding.UTF8, "application/json") }; } } private static LlmConnectionFactory Factory(string provider = "openai", string model = "text-embedding-3-small") => new() { Provider = provider, ModelId = model, ApiKey = "sk-test" }; [Fact] public async Task EmbedAsync_ParsesVectors_HonoursIndexOrder_AndShapesRequest() { // data arrives out of order (index 1 before index 0) — must be reordered to match inputs. var handler = new StubHandler( """{"data":[{"index":1,"embedding":[0.3,0.4]},{"index":0,"embedding":[0.1,0.2]}]}"""); var provider = new OpenAiEmbeddingProvider(Factory(), new HttpClient(handler)); var vectors = await provider.EmbedAsync(new[] { "alpha", "beta" }); vectors.Should().HaveCount(2); vectors[0].Should().Equal(0.1f, 0.2f); // index 0 → first input vectors[1].Should().Equal(0.3f, 0.4f); // index 1 → second input handler.LastRequest!.RequestUri!.ToString().Should().Be("https://api.openai.com/v1/embeddings"); handler.LastRequest.Headers.Authorization!.ToString().Should().Be("Bearer sk-test"); var body = JsonDocument.Parse(handler.LastBody!).RootElement; body.GetProperty("model").GetString().Should().Be("text-embedding-3-small"); body.GetProperty("input").GetArrayLength().Should().Be(2); } [Fact] public async Task EmbedOneAsync_ReturnsFirstVector() { var handler = new StubHandler("""{"data":[{"index":0,"embedding":[1,2,3]}]}"""); IEmbeddingProvider provider = new OpenAiEmbeddingProvider(Factory(), new HttpClient(handler)); (await provider.EmbedOneAsync("hi")).Should().Equal(1f, 2f, 3f); } [Fact] public async Task EmbedAsync_EmptyInputs_ReturnsEmpty_WithoutHttpCall() { var handler = new StubHandler("{}"); var provider = new OpenAiEmbeddingProvider(Factory(), new HttpClient(handler)); (await provider.EmbedAsync(Array.Empty())).Should().BeEmpty(); handler.LastRequest.Should().BeNull(); } [Fact] public void Endpoint_ResolvesPerProvider() { new OpenAiEmbeddingProvider(Factory("mistral"), new HttpClient(new StubHandler("{}"))) .ProviderId.Should().Be("mistral"); // base-url resolution is shared with OpenAiProvider; a smoke check that the // provider id is lower-cased and carried through. } [Fact] public async Task EmbedAsync_HttpError_Throws() { var handler = new StubHandler("""{"error":"bad model"}""", HttpStatusCode.BadRequest); var provider = new OpenAiEmbeddingProvider(Factory(), new HttpClient(handler)); var act = async () => await provider.EmbedAsync(new[] { "x" }); await act.Should().ThrowAsync(); } /// Stub that also sets Retry-After, which only the 429 path reads. private sealed class RetryAfterHandler(HttpStatusCode status, int? retryAfterSeconds) : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) { var response = new HttpResponseMessage(status) { Content = new StringContent("""{"error":"slow down"}""", Encoding.UTF8, "application/json") }; if (retryAfterSeconds is { } seconds) response.Headers.Add("Retry-After", seconds.ToString(System.Globalization.CultureInfo.InvariantCulture)); return Task.FromResult(response); } } [Fact] public async Task EmbedAsync_RateLimited_ThrowsTypedRateLimit_WithRetryAfter() { // Retrieval degrades to keyword on ANY embedder failure, so an expired key and a busy // server used to look identical to the caller. 429 has to be its own kind, with the // provider's own wait time, or "retry" is guesswork. var provider = new OpenAiEmbeddingProvider( Factory(), new HttpClient(new RetryAfterHandler(HttpStatusCode.TooManyRequests, 7))); var error = await Assert.ThrowsAsync( () => provider.EmbedAsync(new[] { "x" })); error.ProviderId.Should().Be("openai"); error.RetryAfter.Should().Be(TimeSpan.FromSeconds(7)); } [Fact] public async Task EmbedAsync_ServerError_ThrowsTypedTransient_ButClientErrorDoesNot() { var transient = new OpenAiEmbeddingProvider( Factory(), new HttpClient(new RetryAfterHandler(HttpStatusCode.ServiceUnavailable, null))); var error = await Assert.ThrowsAsync( () => transient.EmbedAsync(new[] { "x" })); error.StatusCode.Should().Be(503); // 401 stays a plain HttpRequestException on purpose: a wrong key is not worth retrying, // and lumping it in with "transient" would spin forever on a dead credential. var unauthorized = new OpenAiEmbeddingProvider( Factory(), new HttpClient(new RetryAfterHandler(HttpStatusCode.Unauthorized, null))); var act = async () => await unauthorized.EmbedAsync(new[] { "x" }); (await act.Should().ThrowAsync()) .And.Should().NotBeOfType(); } } Path: redb-route/tests/redb.Route.Tests.Llm/GlobalUsings.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/GlobalUsings.cs ---- global using redb.Route.Abstractions; global using redb.Route.Core; global using redb.Route.Extensions; global using redb.Route.Llm; global using redb.Route.Llm.Abstractions.Tools; global using redb.Route.Llm.Engine; global using redb.Route.Llm.Extensions; global using redb.Route.Llm.Providers; global using redb.Route.Llm.Tools; Path: redb-route/tests/redb.Route.Tests.Llm/Governance/ApprovalDefaultsTests.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/Governance/ApprovalDefaultsTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Llm.Engine.Governance; namespace redb.Route.Tests.Llm.Governance; /// /// Lock, not red. Records the shipped default that the governance docs talk about: a container /// built by AddRedbRouteLlm() resolves , i.e. the approval flag /// alone does not stop a tool call. /// /// This stays true after wave 6 by decision: discovered MCP tools now declare /// RequiresApproval = true, which with this gate produces an audit row /// (ApprovalId = "auto"), not a blocked call. A host that wants approval to be a control point /// registers its own gate — and AddRedbLlmStorage() leaves that registration alone. /// /// [Trait("Category", "Governance")] public sealed class ApprovalDefaultsTests { [Fact] public void AddRedbRouteLlm_ResolvesAutoApproveGateByDefault() { var services = new ServiceCollection(); services.AddRedbRouteLlm(); using var provider = services.BuildServiceProvider(); var gate = provider.GetRequiredService(); gate.Should().BeOfType( "the shipped default gate auto-approves; a real control point requires replacing it"); } } Path: redb-route/tests/redb.Route.Tests.Llm/Governance/BudgetTests.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/Governance/BudgetTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Extensions; using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.Governance; /// /// Budgets (wave 4). Before this wave AgentRequest.Budget was filled nowhere, so every route /// ran unbounded, and the cost dimension was a structural zero. These tests pin the three things that /// make the feature real: the ceiling reaches the engine, a run that crosses it stops with a reason, /// and a cost ceiling nobody can price fails fast instead of being silently ignored. /// [Trait("Category", "Governance")] public sealed class BudgetTests { private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}"""; private const string Input = """{"q":"x"}"""; private const string Reply = """{"answer":"42"}"""; [Fact] public async Task RouteWithTokenBudget_StopsWithBudgetReason() { var provider = new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_1", tokensIn: 10, tokensOut: 1) .EnqueueText("first answer", tokensIn: 500, tokensOut: 1) .EnqueueText("never asked for", tokensIn: 500, tokensOut: 1); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply); var budgetSpy = new SpyBudgetEnforcer(); await using var host = LiveLlmHost.Build(budget: budgetSpy) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).Budget(inputTokens: 100).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool."); tool.CapturedInputs.Should().HaveCount(1, "the first iteration stayed inside the ceiling"); provider.CallCount.Should().Be(2, "the run stopped after the iteration that crossed the ceiling"); host.Mock("mock:done").ReceivedExchanges[0].In.Headers[LlmHeaders.ToolIterations] .Should().Be(2, "two iterations completed; the third provider call never happened"); budgetSpy.StopReasons.Should().Contain(r => r != null && r.Contains("input-token budget exceeded")); } [Fact] public async Task RouteWithCostBudget_WithoutCostCalculator_FailsFast() { var provider = new FakeProvider().EnqueueText("never reached"); await using var host = LiveLlmHost.Build() .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Budget(costUsd: 0.5m).AsUri()) .To("mock:done")); var thrown = await Record.ExceptionAsync(() => host.SendAsync("direct:agent", "hello")); thrown.Should().BeOfType() .Which.Message.Should().Contain("ICostCalculator", "the message must name what is missing, not just that something is wrong"); provider.CallCount.Should().Be(0, "an unpriceable cost ceiling must be refused before any spend"); } [Fact] public async Task RouteWithCostBudget_WithCalculator_StopsWithBudgetReason() { var provider = new FakeProvider() .EnqueueText("first answer", tokensIn: 1000, tokensOut: 1000) .EnqueueText("never asked for", tokensIn: 1000, tokensOut: 1000); var budgetSpy = new SpyBudgetEnforcer(); await using var host = LiveLlmHost.Build(budget: budgetSpy, costCalculator: new FlatCostCalculator(0.01m)) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Budget(costUsd: 0.005m).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "hello"); provider.CallCount.Should().Be(1, "the priced iteration crossed the ceiling, so the loop stopped"); budgetSpy.StopReasons.Should().Contain(r => r != null && r.Contains("cost budget exceeded")); } [Fact] public void BudgetBuilder_EmitsOnlyTheDimensionsItWasGiven() { var outputOnly = LlmDsl.Factory("demo").Budget(outputTokens: 50).AsUri(); outputOnly.Should().Contain("budgetOutputTokens=50"); outputOnly.Should().NotContain("budgetInputTokens", "an unset dimension must stay absent — zero and \"not set\" must not become one state in the URI"); outputOnly.Should().NotContain("budgetCostUsd"); LlmDsl.Factory("demo").AsUri().Should().NotContain("budget", "a route that asked for no budget carries none"); } [Fact] public void CustomBudgetEnforcer_SurvivesAddRedbLlmStorage() { var services = new ServiceCollection(); services.AddSingleton(new RouteContext()); services.AddRedbRouteLlm(); var mine = new SpyBudgetEnforcer(); services.AddSingleton(mine); services.AddRedbLlmStorage(); using var sp = services.BuildServiceProvider(); sp.GetRequiredService().Should().BeSameAs(mine, "AddRedbLlmStorage must never take away a governance implementation the host registered"); } [Fact] public void ShippedBudgetEnforcer_IsReplacedByStoreEnforcer() { var services = new ServiceCollection(); services.AddSingleton(new RouteContext()); services.AddRedbRouteLlm(); services.AddRedbLlmStorage(); using var sp = services.BuildServiceProvider(); sp.GetRequiredService().Should().BeOfType( "with a store present the shipped per-run default is replaced — otherwise usage is never accumulated"); } /// /// A zero ceiling means "no ceiling": the enforcer only enforces positive limits, and the option docs /// now say so. Pinned here so the documentation cannot drift back into promising a stop sign that the /// code does not implement. /// [Fact] public async Task ZeroBudget_MeansNoCeiling() { var provider = new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_1", tokensIn: 500, tokensOut: 1) .EnqueueText("done", tokensIn: 500, tokensOut: 1); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply); await using var host = LiveLlmHost.Build() .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).Budget(inputTokens: 0).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool."); provider.CallCount.Should().Be(2, "a zero ceiling does not stop the run — 500 tokens per iteration and the loop still reaches the model's own stop reason"); } } Path: redb-route/tests/redb.Route.Tests.Llm/Governance/EngineCompositionTests.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/Governance/EngineCompositionTests.cs ---- using System.Security.Claims; using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.Governance; /// /// The composition path, which is not the tests' path: every other test here hand-wires the engine /// (new AgentEngine(...)), while a real host lets AddRedbRouteLlm() build it. If that path /// loses a governance seam, every promise of this phase holds only inside the test suite — so the /// container's engine is exercised end-to-end here. /// [Trait("Category", "Governance")] public sealed class EngineCompositionTests { private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}"""; private const string Input = """{"q":"x"}"""; private const string Claim = "orders:read"; /// /// A claims-required tool through the container's engine: the tool fires only if the engine the /// container built carries the registered claims source and a producer template. /// [Fact] public async Task EngineFromDi_DispatchesAClaimRequiredTool() { var provider = new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_1") .EnqueueText("done"); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""", requiredClaims: [Claim]); await using var host = LiveLlmHost.Build(engineFromDi: true) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); var principal = new ClaimsPrincipal( new ClaimsIdentity([new Claim("scope", Claim)], authenticationType: "test")); await host.SendAsync("direct:agent", "Call the tool.", configure: ex => ExchangePrincipal.Set(ex, principal)); var sinkBody = host.Mock("mock:done").ReceivedExchanges[0].In.Body?.ToString() ?? "(no body)"; tool.CapturedInputs.Should().HaveCount(1, $"AddRedbRouteLlm() registers the default claims source — the engine it builds must be the one using it. Sink said: {sinkBody}"); } /// /// A read-only, Persist-cached tool through the container's engine: the second identical call inside /// one run is answered from the cache, which only happens if the container wired the cache layer into /// the engine it built. /// [Fact] public async Task EngineFromDi_AnswersARepeatedCallFromTheCache() { var provider = new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_1") .EnqueueToolUse("lookup", Input, "tu_2") .EnqueueText("done"); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""", caching: ToolCachingPolicy.Memoize); await using var host = LiveLlmHost.Build(engineFromDi: true) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool twice."); tool.CapturedInputs.Should().HaveCount(1, "the container's engine must consult the cache it registered, not only the hand-wired one"); } } Path: redb-route/tests/redb.Route.Tests.Llm/Governance/IdempotencyGateTests.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/Governance/IdempotencyGateTests.cs ---- using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.Governance; /// /// Idempotency gate (wave 5). The spec gates the idempotency store on the declared side-effect class: /// a mutating tool is reserved before it runs and a replay of the same tool_use id returns the /// stored result, while a read-only tool is never reserved — it has no side effect to de-duplicate and /// a reservation would cost store round-trips on every call. /// /// Both tests set a conversation id (via ?conversation=header); without one the engine's /// idempotency branch has nowhere to store anything. /// /// [Trait("Category", "Governance")] public sealed class IdempotencyGateTests { private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}"""; private const string ConversationId = "c-1"; private const string Input = """{"q":"x"}"""; private const string Reply = """{"answer":"42"}"""; [Fact] public async Task ReadOnlyTool_DoesNotConsultIdempotencyStore() { var provider = new FakeProvider() .EnqueueToolUse("lookup", """{"q":"x"}""", "tu_1") .EnqueueText("done"); var idempotency = new SpyIdempotencyStore(); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""", sideEffect: ToolSideEffect.ReadOnly); await using var host = LiveLlmHost.Build(idempotency: idempotency) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").ConversationFromHeader().Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool.", new Dictionary { [LlmHeaders.ConversationId] = ConversationId }); tool.CapturedInputs.Should().HaveCount(1, "the tool itself still runs"); idempotency.Reservations.Should().BeEmpty( "a read-only tool has no side effect to deduplicate — reserving it costs a store round-trip for nothing"); } [Fact] public async Task MutatingTool_ReservesAndCompletesOnce() { var provider = new FakeProvider() .EnqueueToolUse("write", """{"q":"x"}""", "tu_1") .EnqueueText("done"); var idempotency = new SpyIdempotencyStore(); var tool = new EchoToolRoute("write", "Mutate something.", Schema, """{"answer":"ok"}""", sideEffect: ToolSideEffect.Mutating); await using var host = LiveLlmHost.Build(idempotency: idempotency) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").ConversationFromHeader().Tools("write").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Mutate.", new Dictionary { [LlmHeaders.ConversationId] = ConversationId }); tool.CapturedInputs.Should().HaveCount(1); idempotency.Reservations.Should().HaveCount(1, "a mutating tool is reserved before it runs"); idempotency.Completions.Should().HaveCount(1, "and completed after it succeeded"); } [Fact] public async Task MutatingTool_Replay_IsServedFromStoreAndReportedAsIdempotencyHit() { var provider = new FakeProvider() .EnqueueToolUse("write", Input, "tu_1") .EnqueueText("done") .EnqueueToolUse("write", Input, "tu_1") .EnqueueText("done"); var idempotency = new SpyIdempotencyStore(); var spy = new ToolInvocationSpy(); var tool = new EchoToolRoute("write", "Mutate something.", Schema, Reply, sideEffect: ToolSideEffect.Mutating); await using var host = LiveLlmHost.Build(spy, idempotency: idempotency) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").ConversationFromHeader().Tools("write").MaxIterations(4).AsUri()) .To("mock:done")); var headers = new Dictionary { [LlmHeaders.ConversationId] = ConversationId }; await host.SendAsync("direct:agent", "Mutate.", headers); await host.SendAsync("direct:agent", "Mutate.", headers); tool.CapturedInputs.Should().HaveCount(1, "the replayed tool_use id is answered from the store instead of mutating a second time"); idempotency.Reservations.Should().HaveCount(2, "the engine still asks the store on the replay — that question is the protection"); spy.ForTool("write").Should().Contain(i => i.Skipped && i.SkipReason == ToolSkipReasons.IdempotencyHit, "the replay is reported to observers under its own reason, not as a cache hit"); } } Path: redb-route/tests/redb.Route.Tests.Llm/Governance/InMemoryStoresInTransactionWarningTests.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/Governance/InMemoryStoresInTransactionWarningTests.cs ---- using System.Transactions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Llm.Engine.Storage; using redb.Route.Processors; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm.Governance; /// /// The in-memory conversation and tool idempotency stores do not take part in an ambient transaction, so a run /// inside one warns, once per route and connection factory: after a rollback the transcript keeps the rolled-back /// run's tool calls. The run itself goes on. No warning outside a transaction, with the redb stores, or with a /// host's own store. /// [Trait("Category", "Governance")] public sealed class InMemoryStoresInTransactionWarningTests { private sealed class ListLogger : ILogger { private readonly List<(LogLevel Level, string Message)> _entries = new(); public IReadOnlyList Warnings { get { lock (_entries) return _entries.Where(e => e.Level == LogLevel.Warning).Select(e => e.Message).ToArray(); } } public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => true; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { lock (_entries) _entries.Add((logLevel, formatter(state, exception))); } } /// A host's own conversation store; it happens to keep its rows in memory, which is its own business. private sealed class HostConversationStore : IConversationStore { private readonly InMemoryConversationStore _inner = new(); public Task AppendAsync(string conversationId, string? parentId, LlmMessage message, ConversationMessageMeta meta, IExchange? exchange = null, CancellationToken ct = default) => _inner.AppendAsync(conversationId, parentId, message, meta, exchange, ct); public Task> LoadPathAsync(string conversationId, string? leafId = null, IExchange? exchange = null, CancellationToken ct = default) => _inner.LoadPathAsync(conversationId, leafId, exchange, ct); public Task> LoadTreeAsync(string conversationId, IExchange? exchange = null, CancellationToken ct = default) => _inner.LoadTreeAsync(conversationId, exchange, ct); } private static AgentEngine Engine(ILogger logger, IConversationStore? conversation, IToolIdempotencyStore? idempotency) => new( logger: logger, producerTemplate: null, observer: null, budget: null, approval: null, redaction: null, shadow: null, conversation: conversation, idempotency: idempotency, approvalStore: null); private static AgentRequest Request(string route, bool withTools = false) { var provider = new FakeProvider().EnqueueText("done"); return new AgentRequest { Factory = new LlmConnectionFactory { Name = "support", Provider = "fake", ModelId = provider.ModelId, PrebuiltProvider = provider }, Exchange = new Exchange(new Message("hello")) { RouteId = route }, UserContent = [new LlmTextBlock("hello")], ConversationId = "conv-1", Tools = withTools ? [new TenantScopedToolDescriptor()] : [] }; } private static async Task RunInTransactionAsync(AgentEngine engine, AgentRequest request) { using var tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled); var response = await engine.RunAsync(request); response.Content.OfType().Single().Text.Should().Be("done", "the run goes on as before"); tx.Complete(); } [Fact] public async Task InMemoryStores_InsideATransaction_WarnOncePerRouteAndFactory() { var logger = new ListLogger(); var engine = Engine(logger, new InMemoryConversationStore(), new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository())); await RunInTransactionAsync(engine, Request("orders", withTools: true)); await RunInTransactionAsync(engine, Request("orders", withTools: true)); logger.Warnings.Should().ContainSingle(); var warning = logger.Warnings[0]; warning.Should().Contain("llm:support").And.Contain("'orders'") .And.Contain("InMemoryConversationStore and InMemoryToolIdempotencyStore") .And.Contain("do not take part in the transaction") .And.Contain("may not call the tool again") .And.Contain("AddRedbLlmStorage()").And.Contain(".Transacted()"); await RunInTransactionAsync(engine, Request("billing")); logger.Warnings.Should().HaveCount(2, "another route is another step, warned once on its own"); logger.Warnings[1].Should().Contain("'billing'").And.Contain("InMemoryConversationStore keep state") .And.NotContain("InMemoryToolIdempotencyStore", "a run without tools never touches the idempotency store"); } [Fact] public async Task InMemoryStores_OutsideATransaction_DoNotWarn() { var logger = new ListLogger(); var engine = Engine(logger, new InMemoryConversationStore(), new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository())); await engine.RunAsync(Request("orders", withTools: true)); logger.Warnings.Should().BeEmpty(); } [Fact] public async Task AHostsOwnStore_InsideATransaction_IsNotWarnedAbout() { var logger = new ListLogger(); var engine = Engine(logger, new HostConversationStore(), idempotency: null); await RunInTransactionAsync(engine, Request("orders", withTools: true)); logger.Warnings.Should().BeEmpty(); } [Fact] public void AddRedbLlmStorage_ReplacesBothInMemoryStores() { // The warning looks at the store instances the engine holds; with AddRedbLlmStorage() neither of them is an // in-memory one, so a transacted run is not warned about. A run against the redb stores is covered by the // storage suites, which need a database. var services = new ServiceCollection(); services.AddSingleton(new RouteContext()); services.AddRedbRouteLlm(); services.AddRedbLlmStorage(); using var sp = services.BuildServiceProvider(); sp.GetRequiredService().Should().NotBeOfType(); sp.GetRequiredService().Should().NotBeOfType(); } } Path: redb-route/tests/redb.Route.Tests.Llm/Governance/RequiredClaimsTests.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/Governance/RequiredClaimsTests.cs ---- using System.Security.Claims; using Microsoft.Extensions.DependencyInjection; using redb.Route.Llm.Extensions; using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.Governance; /// /// Claims enforcement (wave 2). A tool that declares .RequireClaim(...) may only fire when the /// run's principal provably holds the claim; without a verifiable principal it is denied, and the /// model is told the error code only. /// /// The realistic runtime shape is exercised with the shipped default source, which reads the caller /// from the exchange properties (never a header). A tool that declares claims with no source /// registered does not even build — see . /// /// [Trait("Category", "Governance")] public sealed class RequiredClaimsTests { private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}"""; private const string Claim = "orders:read"; /// An authenticated caller carrying each of as its own scope claim. private static ClaimsPrincipal Principal(params string[] scopeValues) => PrincipalWithClaimType("scope", scopeValues); /// An authenticated caller whose values arrive under . private static ClaimsPrincipal PrincipalWithClaimType(string claimType, params string[] values) => new(new ClaimsIdentity(values.Select(v => new Claim(claimType, v)), authenticationType: "test")); /// /// Runs a claim-required tool through the shipped default source, with /// placed on the exchange the way a transport would (a property, before the route runs). /// private static async Task<(EchoToolRoute Tool, ToolInvocationSpy Spy, IExchange Exchange)> RunWithPrincipalAsync( ClaimsPrincipal? principal) { var provider = new FakeProvider() .EnqueueToolUse("lookup", """{"q":"x"}""", "tu_1") .EnqueueText("done"); var spy = new ToolInvocationSpy(); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""", requiredClaims: [Claim]); await using var host = LiveLlmHost.Build(spy, claimsSource: new ExchangePrincipalClaimsSource()) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); var exchange = await host.SendAsync("direct:agent", "Call the tool.", configure: ex => { if (principal is not null) ExchangePrincipal.Set(ex, principal); }); return (tool, spy, exchange); } [Fact] public async Task RequiredClaimsTool_WithoutPrincipal_IsDenied() { var provider = new FakeProvider() .EnqueueToolUse("lookup", """{"q":"x"}""", "tu_1") .EnqueueText("done"); var spy = new ToolInvocationSpy(); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""", requiredClaims: [Claim]); await using var host = LiveLlmHost.Build(spy, claimsSource: new DelegateToolClaimsSource(_ => null)) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool."); tool.CapturedInputs.Should().BeEmpty( "a tool whose claims cannot be verified must never be invoked (fail closed)"); spy.ForTool("lookup").Should().NotBeEmpty("the denial is reported to observers") .And.OnlyContain(i => i.Skipped && i.SkipReason != null && i.SkipReason.StartsWith("claims_missing")); } [Fact] public async Task RequiredClaimsTool_WithUserHeaderButNoPrincipal_IsDenied() { // The header is the *audit identity* fallback, not an authorization source: a client-supplied // string must not be enough to satisfy a declared claim. var provider = new FakeProvider() .EnqueueToolUse("lookup", """{"q":"x"}""", "tu_1") .EnqueueText("done"); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""", requiredClaims: [Claim]); await using var host = LiveLlmHost.Build(claimsSource: new DelegateToolClaimsSource(_ => null)) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool.", new Dictionary { [LlmHeaders.UserId] = "user-1" }); tool.CapturedInputs.Should().BeEmpty( "an unverified client-supplied identity must not satisfy RequiredClaims"); } [Fact] public async Task RequiredClaimsTool_WithAllClaims_IsInvoked() { var provider = new FakeProvider() .EnqueueToolUse("lookup", """{"q":"x"}""", "tu_1") .EnqueueText("done"); var spy = new ToolInvocationSpy(); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""", requiredClaims: [Claim]); await using var host = LiveLlmHost.Build(spy, claimsSource: new DelegateToolClaimsSource(_ => [Claim, "orders:write"])) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool."); tool.CapturedInputs.Should().HaveCount(1, "a principal holding the claim runs the tool"); spy.ForTool("lookup").Should().Contain(i => !i.Skipped, "and the invocation is not a skip"); } [Fact] public async Task RequireClaim_WithoutClaimsSource_FailsRouteBuild() { var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""", requiredClaims: [Claim]); // No claims source on purpose: the tool could never fire, so the route must not build. await using var host = LiveLlmHost.Build() .AddFactory("demo", new LlmConnectionFactory { Provider = "stub" }); var thrown = await Record.ExceptionAsync(() => host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done"))); thrown.Should().BeOfType() .Which.Message.Should().Contain("IToolClaimsSource", "the message must name the missing registration so the fix is obvious"); } /// /// The positive path through the shipped default source: the caller proved itself to a transport, /// the principal sits on the exchange, and the required scope is there. /// [Fact] public async Task RequiredClaimsTool_WithVerifiedPrincipalScope_IsInvoked() { var (tool, spy, _) = await RunWithPrincipalAsync(Principal(Claim)); tool.CapturedInputs.Should().HaveCount(1, "the caller holds the required scope"); spy.ForTool("lookup").Should().Contain(i => !i.Skipped); } /// Microsoft Entra ID spells the same vocabulary under scp; the default source reads both. [Fact] public async Task RequiredClaimsTool_ScpClaimType_IsHonoured() { var (tool, _, _) = await RunWithPrincipalAsync(PrincipalWithClaimType("scp", Claim)); tool.CapturedInputs.Should().HaveCount(1); } /// /// Real issuers split one logical set into several claims and pad the values; neither may turn a /// satisfied requirement into a denial. /// [Fact] public async Task RequiredClaimsTool_PaddedAndRepeatedScopes_AreNormalized() { var (tool, _, _) = await RunWithPrincipalAsync( PrincipalWithClaimType("scope", $"{Claim} orders:write ", Claim, " orders:write ")); tool.CapturedInputs.Should().HaveCount(1, "padding and repetition are formatting, not a different claim"); } /// A verified caller who simply does not hold the scope is denied — with the audit reason. [Fact] public async Task RequiredClaimsTool_PrincipalWithoutTheScope_IsDenied() { var (tool, spy, _) = await RunWithPrincipalAsync(Principal("orders:write")); tool.CapturedInputs.Should().BeEmpty("holding another scope is not holding this one"); spy.ForTool("lookup").Should().OnlyContain(i => i.Skipped && i.SkipReason != null && i.SkipReason.StartsWith(ToolSkipReasons.ClaimsMissing)); } /// /// An identity that is not authenticated is not a principal: a transport that passes through an /// anonymous placeholder must not be able to satisfy a requirement. /// [Fact] public async Task RequiredClaimsTool_UnauthenticatedPrincipal_IsDenied() { var anonymous = new ClaimsPrincipal(new ClaimsIdentity([new Claim("scope", Claim)])); var (tool, _, _) = await RunWithPrincipalAsync(anonymous); tool.CapturedInputs.Should().BeEmpty( "claims on an unauthenticated identity are a claim about nothing"); } /// /// The caller reaches the exchange the tool itself runs on — the identity survives the linked child /// the agent dispatches into, which is what makes a claims check meaningful inside a tool route. /// [Fact] public async Task Principal_ReachesTheToolExchange() { var principal = Principal(Claim); var (tool, _, _) = await RunWithPrincipalAsync(principal); tool.CapturedProperties.Should().Contain( p => p.ContainsKey(ExchangePrincipal.PropertyKey) && ReferenceEquals(p[ExchangePrincipal.PropertyKey], principal), "a tool route reads the caller from its own exchange, not from a translation of the request"); } /// /// Scope values are space-delimited (RFC 6749 §3.3); a comma is a legal character inside a /// scope token. Treating it as a separator would turn one granted scope — orders:read,orders:write /// — into two grants, which is the one direction a security check must never fail in. /// [Fact] public async Task RequiredClaimsTool_CommaIsNotAScopeSeparator() { var (tool, spy, _) = await RunWithPrincipalAsync(Principal($"{Claim},orders:write")); tool.CapturedInputs.Should().BeEmpty( "the value is a single scope token containing a comma, not two scopes"); spy.ForTool("lookup").Should().OnlyContain(i => i.Skipped); } /// /// The default source on its own: which claim types it reads, and the two states it must keep apart /// — "no principal" and "a principal that holds nothing". /// [Fact] public void ExchangePrincipalClaimsSource_ReadsScopeClaimTypes_AndRefusesAnonymous() { var source = new ExchangePrincipalClaimsSource(); var exchange = Exchange.Create(new Message("x"), scopeFactory: null); source.GetClaims(exchange).Should().BeNull("an exchange with no principal proves nothing"); ExchangePrincipal.Set(exchange, PrincipalWithClaimType( "http://schemas.microsoft.com/identity/claims/scope", $"{Claim} orders:write")); source.GetClaims(exchange).Should().BeEquivalentTo([Claim, "orders:write"], "the Entra ID v1 scope claim type carries the same vocabulary"); ExchangePrincipal.Set(exchange, new ClaimsPrincipal(new ClaimsIdentity([new Claim("scope", Claim)]))); source.GetClaims(exchange).Should().BeNull( "an identity that is not authenticated is not a principal, so an anonymous placeholder cannot satisfy a requirement"); ExchangePrincipal.Set(exchange, Principal()); source.GetClaims(exchange).Should().BeEmpty( "a principal holding nothing differs from no principal — both deny, but only one is diagnosable"); } /// /// Claims work out of the box: the shipped container resolves the caller-based source, so a tool /// route can declare a requirement without the host wiring anything. /// [Fact] public void AddRedbRouteLlm_RegistersPrincipalClaimsSourceByDefault() { var services = new ServiceCollection(); services.AddRedbRouteLlm(); using var provider = services.BuildServiceProvider(); provider.GetRequiredService().Should().BeOfType( "the caller's principal is the default answer to \"what may this run do\""); } /// A host with its own vocabulary keeps it: the default registration must not win over it. [Fact] public void HostRegisteredClaimsSource_WinsOverTheDefault() { var services = new ServiceCollection(); var mine = new DelegateToolClaimsSource(_ => ["host:everything"]); services.AddSingleton(mine); services.AddRedbRouteLlm(); using var provider = services.BuildServiceProvider(); provider.GetRequiredService().Should().BeSameAs(mine); } } Path: redb-route/tests/redb.Route.Tests.Llm/Governance/RouteTransactionTests.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/Governance/RouteTransactionTests.cs ---- using System.Transactions; using redb.Route.Llm.Engine.Governance; using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.Governance; /// /// The agent inside a route transaction (a route's .Transacted()). Its database work and deferred /// sends, its tools' included, belong to that transaction and roll back with it. Three things do not: an /// external tool, whose action no rollback can take back, is not run there; the budget, whose tokens are /// paid whatever happens to the transaction, is recorded outside it; and the shadow run stays out of it. /// [Trait("Category", "Governance")] public sealed class RouteTransactionTests { private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}"""; private const string Input = """{"q":"x"}"""; private static LlmConnectionFactory Factory(FakeProvider provider) => new() { Provider = "fake", ModelId = provider.ModelId, PrebuiltProvider = provider }; private static AgentEngine Engine(IBudgetEnforcer? budget = null, IShadowRunner? shadow = null) => new( logger: null, producerTemplate: null, observer: null, budget: budget, approval: null, redaction: null, shadow: shadow, conversation: null, idempotency: null, approvalStore: null); private static AgentRequest Request(FakeProvider provider) => new() { Factory = Factory(provider), Exchange = new Exchange(new Message("status?")), UserContent = [new LlmTextBlock("status?")] }; [Fact] public async Task ExternalTool_InsideTransactedRoute_IsNotRun() { var provider = new FakeProvider() .EnqueueToolUse("send_mail", Input, "tu_1") .EnqueueText("done"); var spy = new ToolInvocationSpy(); var tool = new EchoToolRoute("send_mail", "Send an e-mail.", Schema, """{"sent":true}""", sideEffect: ToolSideEffect.External); var routeWasTransacted = false; await using var host = LiveLlmHost.Build(spy) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .Transacted() .Process(_ => routeWasTransacted = Transaction.Current is not null) .To(LlmDsl.Factory("demo").Tools("send_mail").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Mail the report."); routeWasTransacted.Should().BeTrue("the agent step must run inside the route's transaction, or this test proves nothing"); tool.CapturedInputs.Should().BeEmpty( "an irreversible action does not run inside a transaction that can still roll back"); spy.ForTool("send_mail").Should().ContainSingle( i => i.Skipped && i.SkipReason == ToolSkipReasons.ExternalInTransaction, "the audit channel records why the tool did not run"); var result = provider.SentMessages.Should().HaveCount(2).And.Subject.ElementAt(1) .SelectMany(m => m.Content).OfType().Should().ContainSingle().Subject; result.IsError.Should().BeTrue(); result.OutputJson.Should().Contain(ToolResultErrors.ExternalInTransaction, "the model is told the tool could not run, so it can answer without it"); } [Fact] public async Task ExternalTool_WithoutTransaction_Runs() { var provider = new FakeProvider() .EnqueueToolUse("send_mail", Input, "tu_1") .EnqueueText("done"); var tool = new EchoToolRoute("send_mail", "Send an e-mail.", Schema, """{"sent":true}""", sideEffect: ToolSideEffect.External); await using var host = LiveLlmHost.Build() .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("send_mail").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Mail the report."); tool.CapturedInputs.Should().HaveCount(1, "outside a transaction nothing can roll back under the action"); } [Fact] public async Task MutatingTool_InsideTransactedRoute_Runs() { var provider = new FakeProvider() .EnqueueToolUse("write", Input, "tu_1") .EnqueueText("done"); var tool = new EchoToolRoute("write", "Mutate something.", Schema, """{"answer":"ok"}""", sideEffect: ToolSideEffect.Mutating); await using var host = LiveLlmHost.Build() .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .Transacted() .To(LlmDsl.Factory("demo").Tools("write").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Mutate."); tool.CapturedInputs.Should().HaveCount(1, "a mutating tool's writes roll back with the transaction, so it belongs inside it"); } [Fact] public async Task Budget_InsideTransaction_IsRecordedOutsideIt() { var sawTransactionAtProvider = false; var provider = new FakeProvider { OnCall = (_, _) => { sawTransactionAtProvider = Transaction.Current is not null; return Task.CompletedTask; } }.EnqueueText("done"); var budget = new SpyBudgetEnforcer(); using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await Engine(budget: budget).RunAsync(Request(provider)); scope.Complete(); } sawTransactionAtProvider.Should().BeTrue("the run itself is inside the transaction, or this test proves nothing"); budget.PreChecks.Should().Be(1); budget.PostChecks.Should().Be(1); budget.SawAmbientTransaction.Should().HaveCount(2).And.OnlyContain(seen => !seen, "tokens are paid when the provider answers; a rollback must not un-count them"); } /// Reports whether the shadow run saw an ambient transaction. private sealed class ShadowSpy : IShadowRunner { public TaskCompletionSource SawTransaction { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public bool Enabled => true; public Task RunAsync(ILlmProvider primary, LlmRequest request, LlmResponse primaryResponse, CancellationToken ct = default) { SawTransaction.TrySetResult(Transaction.Current is not null); return Task.CompletedTask; } } [Fact] public async Task ShadowRun_DoesNotInheritTheTransaction() { var provider = new FakeProvider().EnqueueText("done"); var shadow = new ShadowSpy(); using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await Engine(shadow: shadow).RunAsync(Request(provider)); scope.Complete(); } (await shadow.SawTransaction.Task.WaitAsync(TimeSpan.FromSeconds(10))).Should().BeFalse( "the shadow runs beside the primary run: it must not write into its transaction"); } } Path: redb-route/tests/redb.Route.Tests.Llm/Governance/StreamingToolPolicyTests.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/Governance/StreamingToolPolicyTests.cs ---- using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.Governance; /// /// Streaming × tools. Both modes run the agent engine with its tools: stream=calls inside the route /// (StreamCallsTests), stream=body when the body is read (LazyStreamTests). So the combination is allowed when /// the endpoint is created; the one placement rule left is stream=body inside .Transacted(), refused at /// run time because the block would commit before the answer exists. /// [Trait("Category", "Governance")] public sealed class StreamingToolPolicyTests { [Theory] [InlineData(LlmStreamMode.Calls)] [InlineData(LlmStreamMode.Body)] public async Task StreamingWithTools_IsAllowed(LlmStreamMode mode) { await using var host = LiveLlmHost.Build() .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = new FakeProvider().EnqueueText("done") }); await host.StartAsync(r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Stream(mode).Tools("*").AsUri())); IExchange? exchange = null; var thrown = await Record.ExceptionAsync(async () => exchange = await host.SendAsync("direct:agent", "hello")); if (exchange is not null) await exchange.DisposeAsync(); thrown.Should().BeNull("a tool-using agent streams in either mode"); exchange!.Exception.Should().BeNull(); } [Fact] public async Task StreamingWithoutTools_IsStillAllowed() { await using var host = LiveLlmHost.Build() .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = new FakeProvider() }); var started = await Record.ExceptionAsync(() => host.StartAsync(r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Stream(LlmStreamMode.Body).AsUri()) .To("mock:done"))); started.Should().BeNull("streaming plain completions is untouched"); } } Path: redb-route/tests/redb.Route.Tests.Llm/Governance/ThinkingProviderSwitchTests.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/Governance/ThinkingProviderSwitchTests.cs ---- using redb.Route.Llm.Engine.Storage; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm.Governance; /// /// A stored conversation can be continued on another provider: switching the factory is the caller's /// decision, and the history goes to the new provider as it was written, thinking blocks included. /// Each provider's request path sends what its wire can express (the provider request tests pin /// that); the engine does not sort blocks by who produced them. /// public sealed class ThinkingProviderSwitchTests { private const string Prompt = "status of order 42?"; private static AgentEngine Engine(IConversationStore store) => new( logger: null, producerTemplate: null, observer: null, budget: null, approval: null, redaction: null, shadow: null, conversation: store, idempotency: null, approvalStore: null); private static ConversationMessageMeta Meta(string providerId, int iteration) => new() { CreatedAtUtc = DateTime.UtcNow, Iteration = iteration, ProviderId = providerId, Usage = new LlmUsage(1, 1) }; [Fact] public async Task ProviderSwitch_StoredThinkingTravelsWithTheHistory() { var store = new InMemoryConversationStore(); const string ConvId = "conv-switch"; var promptId = await store.AppendAsync(ConvId, null, LlmMessage.User(Prompt), Meta("anthropic", 0)); await store.AppendAsync(ConvId, promptId, new LlmMessage { Role = "assistant", Content = [new LlmThinkingBlock("anthropic reasoning", "sig-1"), new LlmTextBlock("shipped")] }, Meta("anthropic", 1)); // The conversation was written by Anthropic; this run asks DeepSeek. var provider = new FakeProvider(); await Engine(store).RunAsync(new AgentRequest { Factory = new LlmConnectionFactory { Provider = "deepseek", ModelId = provider.ModelId, PrebuiltProvider = provider }, Exchange = new Exchange(new Message(Prompt)), UserContent = [new LlmTextBlock(Prompt)], ConversationId = ConvId }); var sent = provider.SentMessages.Should().ContainSingle().Subject; sent.Should().HaveCount(3, "the stored prompt, the stored turn and this run's prompt"); var turn = sent[1].Content; turn.Should().HaveCount(2, "the stored turn goes to the new provider as it was written"); turn[0].Should().BeOfType().Which.Signature.Should().Be("sig-1"); turn[1].Should().BeOfType().Which.Text.Should().Be("shipped"); } } Path: redb-route/tests/redb.Route.Tests.Llm/Governance/ToolCacheTests.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/Governance/ToolCacheTests.cs ---- using System.Security.Claims; using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.Governance; /// /// Tool-result cache (wave 3). Two layers, one question — "do I already have an output for this exact /// input?": Memoize is answered by a run-scoped in-process memo, Persist by the /// configured store. A hit is a skipped invocation reported to observers, never a silent optimisation. /// /// The last two tests are locks on the boundaries: a memo must not survive its run, and a mutating /// tool must not be cacheable at all (a hit would suppress the side effect it stands for). /// /// [Trait("Category", "Governance")] public sealed class ToolCacheTests { private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}"""; private const string Input = """{"q":"x"}"""; private const string Reply = """{"answer":"42"}"""; [Fact] public async Task CachingMemoize_TwoIdenticalCalls_SecondIsServedFromCache() { var provider = new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_1") .EnqueueToolUse("lookup", Input, "tu_2") .EnqueueText("done"); var spy = new ToolInvocationSpy(); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply, caching: ToolCachingPolicy.Memoize); await using var host = LiveLlmHost.Build(spy) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool twice."); tool.CapturedInputs.Should().HaveCount(1, "Memoize answers the second identical call from the run-scoped cache instead of dispatching it"); spy.ForTool("lookup").Should().Contain(i => i.Skipped && i.SkipReason == ToolSkipReasons.CacheHit, "a hit is reported as a skipped invocation, not as an invisible optimisation"); } [Fact] public async Task CachingNone_TwoIdenticalCalls_BothDispatch() { var provider = new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_1") .EnqueueToolUse("lookup", Input, "tu_2") .EnqueueText("done"); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}"""); await using var host = LiveLlmHost.Build() .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool twice."); tool.CapturedInputs.Should().HaveCount(2, "with caching off every call must reach the tool — the cache must not invent memoisation"); } [Fact] public async Task CachingPersist_SurvivesNewEngineInstance() { var store = new SpyToolCacheStore(); var toolInFirstHost = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply, caching: ToolCachingPolicy.Persist); var firstRun = new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_1") .EnqueueText("done"); await using (var host = LiveLlmHost.Build(toolCache: store) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = firstRun })) { await host.StartAsync(toolInFirstHost, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool."); } toolInFirstHost.CapturedInputs.Should().HaveCount(1); store.Sets.Should().HaveCount(1, "Persist writes the output to the store"); // A second host means a second engine instance: only the store carries state across. var toolInSecondHost = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply, caching: ToolCachingPolicy.Persist); var secondRun = new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_2") .EnqueueText("done"); await using (var host = LiveLlmHost.Build(toolCache: store) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = secondRun })) { await host.StartAsync(toolInSecondHost, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool."); } toolInSecondHost.CapturedInputs.Should().BeEmpty( "the persisted entry answers the identical call from a new engine instance"); } [Fact] public async Task Cache_TwoTenantsSameInput_TwoEntries() { var store = new SpyToolCacheStore(); var provider = new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_1") .EnqueueText("done") .EnqueueToolUse("lookup", Input, "tu_2") .EnqueueText("done") .EnqueueToolUse("lookup", Input, "tu_3") .EnqueueText("done"); var routes = new TenantScopedToolRoutes(); await using var host = LiveLlmHost.Build(toolCache: store) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); host.ToolRegistry.Register(new TenantScopedToolDescriptor()); await host.StartAsync(routes, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools(TenantScopedToolDescriptor.ToolName).MaxIterations(4).AsUri()) .To("mock:done")); await SendAsTenant(host, "a"); await SendAsTenant(host, "b"); await SendAsTenant(host, "a"); routes.CountFor("a").Should().Be(1, "the identical call from the same tenant is answered from its own entry"); routes.CountFor("b").Should().Be(1, "tenant b sends the same input, but its resolved address differs — the cache must never serve one tenant's output to another"); store.Sets.Should().HaveCount(2, "one entry per resolved address"); store.Sets.Should().OnlyHaveUniqueItems("the two entries carry different keys"); } [Fact] public async Task Memoize_EntriesDoNotOutliveTheRun() { var store = new SpyToolCacheStore(); var provider = new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_1") .EnqueueText("done") .EnqueueToolUse("lookup", Input, "tu_2") .EnqueueText("done"); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply, caching: ToolCachingPolicy.Memoize); await using var host = LiveLlmHost.Build(toolCache: store) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool."); await host.SendAsync("direct:agent", "Call the tool."); tool.CapturedInputs.Should().HaveCount(2, "the memo belongs to one run — a later run must dispatch the identical call again"); store.Sets.Should().BeEmpty("Memoize is served in process: it never reaches the store"); store.Gets.Should().BeEmpty("and the store is never read for it either"); } [Fact] public async Task MutatingTool_WithCaching_IsRejectedAtBuild() { var tool = new EchoToolRoute("lookup", "Send an invoice.", Schema, Reply, sideEffect: ToolSideEffect.Mutating, caching: ToolCachingPolicy.Persist); await using var host = LiveLlmHost.Build() .AddFactory("demo", new LlmConnectionFactory { Provider = "stub" }); var thrown = await Record.ExceptionAsync(() => host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done"))); thrown.Should().BeOfType() .Which.Message.Should().Contain("Caching", "a cache hit would suppress the side effect, so the route must not build at all"); } private static Task SendAsTenant(LiveLlmHost host, string tenant) => host.SendAsync("direct:agent", "Call the tool.", new Dictionary { [TenantScopedToolDescriptor.TenantHeader] = tenant }); /// /// A cached entry belongs to the policy the tool had when the entry was written. Tightening the /// policy (here: adding a required claim) must not be answered by that entry — otherwise data /// fetched while the tool was open to everyone keeps flowing after it was closed down. /// [Fact] public async Task CachingPolicyChange_DoesNotServeAnEntryWrittenUnderTheOldPolicy() { var store = new SpyToolCacheStore(); var lax = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply, caching: ToolCachingPolicy.Persist); var firstRun = new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_1") .EnqueueText("done"); await using (var host = LiveLlmHost.Build(toolCache: store) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = firstRun })) { await host.StartAsync(lax, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool."); } lax.CapturedInputs.Should().HaveCount(1); store.Sets.Should().HaveCount(1, "the entry was written while the tool had no requirement"); var stricter = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply, caching: ToolCachingPolicy.Persist, requiredClaims: ["orders:read"]); var secondRun = new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_2") .EnqueueText("done"); var spy = new ToolInvocationSpy(); var principal = new ClaimsPrincipal( new ClaimsIdentity([new Claim("scope", "orders:read")], authenticationType: "test")); await using (var host = LiveLlmHost.Build(spy, claimsSource: new ExchangePrincipalClaimsSource(), toolCache: store) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = secondRun })) { await host.StartAsync(stricter, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool.", configure: ex => ExchangePrincipal.Set(ex, principal)); } stricter.CapturedInputs.Should().HaveCount(1, "a stricter policy is a different cache entry, not a hit on the laxer one"); spy.ForTool("lookup").Should().Contain(i => !i.Skipped); store.Sets.Should().HaveCount(2, "the new policy writes its own entry"); } /// /// The tool route sees the caller's principal, so "same input" is not "same answer": an entry /// fetched for one caller must not be served to another, even when both hold the same rights. /// [Fact] public async Task Cache_PersistedEntry_IsNotServedAcrossCallers() { var store = new SpyToolCacheStore(); async Task RunAsAsync(string subject) { var provider = new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_1") .EnqueueText("done"); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply, caching: ToolCachingPolicy.Persist); await using var host = LiveLlmHost.Build(toolCache: store) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); var principal = new ClaimsPrincipal( new ClaimsIdentity([new Claim(ClaimTypes.Name, subject)], authenticationType: "test")); await host.SendAsync("direct:agent", "Call the tool.", configure: ex => ExchangePrincipal.Set(ex, principal)); return tool.CapturedInputs.Count; } (await RunAsAsync("alice")).Should().Be(1); (await RunAsAsync("bob")).Should().Be(1, "another caller asking the same question is a different question — the entry belongs to alice"); store.Sets.Should().HaveCount(2, "one entry per caller"); } /// /// Headers the route opted into propagating (.PropagateToolHeaders(...)) reach the tool, so /// they are part of what it answers. /// [Fact] public async Task Cache_PersistedEntry_IsNotServedAcrossPropagatedHeaderValues() { var store = new SpyToolCacheStore(); async Task RunWithTenantAsync(string tenant) { var provider = new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_1") .EnqueueText("done"); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply, caching: ToolCachingPolicy.Persist); await using var host = LiveLlmHost.Build(toolCache: store) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").PropagateToolHeaders("x-tenant-id") .Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool.", new Dictionary { ["x-tenant-id"] = tenant }); return tool.CapturedInputs.Count; } (await RunWithTenantAsync("acme")).Should().Be(1); (await RunWithTenantAsync("globex")).Should().Be(1, "the header the route chose to pass on is part of the tool's input"); store.Sets.Should().HaveCount(2, "one entry per propagated header value"); } /// /// An unavailable cache costs a hit, never the run: the tool still executes, the model still gets a /// normal result, and the failure is logged rather than thrown at the model. /// [Fact] public async Task CacheStoreFailure_DoesNotFailTheRun() { var provider = new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_1") .EnqueueText("done"); var spy = new ToolInvocationSpy(); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, Reply, caching: ToolCachingPolicy.Persist); await using var host = LiveLlmHost.Build(spy, toolCache: new ThrowingToolCacheStore()) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool."); tool.CapturedInputs.Should().HaveCount(1, "a broken cache must not stop the tool from running"); spy.ForTool("lookup").Should().OnlyContain(i => !i.Skipped && i.Exception == null, "the model receives a normal tool result, not a cache error"); } /// /// The read-only rule is enforced where every descriptor path converges — the registry — so /// LlmTool.Define(...).Build(), the [ExposeAsLlmTool] attribute and MCP discovery are /// covered as well, not just the route DSL. /// [Fact] public void MutatingTool_WithCaching_IsRejectedByRegistration() { var descriptor = LlmTool.Define("send_invoice") .EndpointUri("direct:send-invoice") .Description("Send an invoice.") .Input(Schema) .SideEffect(ToolSideEffect.Mutating) .Caching(ToolCachingPolicy.Persist) .Build(); var act = () => new ToolDescriptorRegistry().Register(descriptor); act.Should().Throw() .Which.Message.Should().Contain("Caching", "a cache hit would suppress the side effect — enforced for every registration path"); } } Path: redb-route/tests/redb.Route.Tests.Llm/Governance/ToolSetHashTests.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/Governance/ToolSetHashTests.cs ---- using redb.Route.Llm.Engine.Storage; using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.Governance; /// /// Wave 0 — red before the fix. MessageProps.ToolSetHash exists so an auditor can answer /// "did the same prompt see a different tool surface?"; today the hash is computed from /// name + description + input schema only, so a changed LlmToolSafety (a weaker gate) /// leaves the hash untouched and the drift is invisible. /// /// The test runs the same tool twice with different side-effect declarations and compares the /// persisted hash — the observable auditors work with. /// /// [Trait("Category", "Governance")] public sealed class ToolSetHashTests { private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}"""; private const string ConversationId = "c-hash"; [Fact] public async Task ToolSetHash_DiffersWhenSafetyDiffers() { var readOnlyHash = await RunAndReadHashAsync(ToolSideEffect.ReadOnly); var mutatingHash = await RunAndReadHashAsync(ToolSideEffect.Mutating); readOnlyHash.Should().NotBeNull("the assistant message persists the tool surface hash"); mutatingHash.Should().NotBeNull(); mutatingHash.Should().NotBe(readOnlyHash, "a policy change is part of the tool surface an auditor compares between runs"); } [Fact] public async Task ToolSetHash_DistinguishesClaimSplitting() { var singleClaim = await RunAndReadHashAsync(ToolSideEffect.ReadOnly, "a,b"); var twoClaims = await RunAndReadHashAsync(ToolSideEffect.ReadOnly, "a", "b"); singleClaim.Should().NotBeNull(); twoClaims.Should().NotBe(singleClaim, "one claim named \"a,b\" and two claims \"a\",\"b\" are different requirements — a comma-joined hash would confuse them"); } private static async Task RunAndReadHashAsync(ToolSideEffect sideEffect, params string[] claims) { var provider = new FakeProvider() .EnqueueToolUse("lookup", """{"q":"x"}""", "tu_1") .EnqueueText("done"); var store = new InMemoryConversationStore(); var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, """{"answer":"42"}""", sideEffect: sideEffect, requiredClaims: claims); // A claims source is required for a claim-declaring tool to build at all; the hash is computed // from the declaration, so the run may still be denied the call. await using var host = LiveLlmHost.Build( conversation: store, claimsSource: new DelegateToolClaimsSource(_ => null)) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").ConversationFromHeader().Tools("lookup").MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool.", new Dictionary { [LlmHeaders.ConversationId] = ConversationId }); var path = await store.LoadPathAsync(ConversationId); return path.Select(m => m.Meta.ToolSetHash).FirstOrDefault(hash => hash is not null); } } Path: redb-route/tests/redb.Route.Tests.Llm/InMemoryToolIdempotencyStoreTests.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/InMemoryToolIdempotencyStoreTests.cs ---- using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Extensions; using redb.Route.Processors; namespace redb.Route.Tests.Llm; /// /// The expiry of : a completed call is forgotten ttl after it completed, on a /// later reservation; a reservation in flight is never aged out. The clock is a test clock, so no test waits. /// public sealed class InMemoryToolIdempotencyStoreTests { private sealed class ManualTime : TimeProvider { public DateTimeOffset Now { get; set; } = new(2026, 11, 25, 12, 0, 0, TimeSpan.Zero); public override DateTimeOffset GetUtcNow() => Now; } private static readonly TimeSpan Ttl = TimeSpan.FromHours(24); [Fact] public async Task ACompletedCall_IsAHit_UntilTheTtlHasPassed() { var time = new ManualTime(); var store = new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository(), Ttl, time); (await store.TryReserveAsync("c", "tu-1")).IsNew.Should().BeTrue(); await store.CompleteAsync("c", "tu-1", """{"sent":true}"""); time.Now += Ttl - TimeSpan.FromMinutes(1); var hit = await store.TryReserveAsync("c", "tu-1"); hit.IsNew.Should().BeFalse(); hit.CachedOutputJson.Should().Be("""{"sent":true}"""); } [Fact] public async Task ACompletedCall_IsForgotten_OnceTheTtlHasPassed() { var time = new ManualTime(); var store = new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository(), Ttl, time); (await store.TryReserveAsync("c", "tu-1")).IsNew.Should().BeTrue(); await store.CompleteAsync("c", "tu-1", """{"sent":true}"""); time.Now += Ttl + TimeSpan.FromMinutes(1); var again = await store.TryReserveAsync("c", "tu-1"); again.IsNew.Should().BeTrue("the call completed more than the ttl ago, so it is forgotten"); } [Fact] public async Task AnotherCall_ForgetsTheExpiredOnes_SoTheStoreDoesNotGrowWithoutBound() { var time = new ManualTime(); var repository = new InMemoryIdempotentRepository(); var store = new InMemoryToolIdempotencyStore(repository, Ttl, time); for (var i = 0; i < 5; i++) { (await store.TryReserveAsync("c", $"tu-{i}")).IsNew.Should().BeTrue(); await store.CompleteAsync("c", $"tu-{i}", "{}"); } time.Now += Ttl + TimeSpan.FromMinutes(1); (await store.TryReserveAsync("c", "tu-new")).IsNew.Should().BeTrue(); repository.Count.Should().Be(1, "only the new reservation is left"); } [Fact] public async Task AReservationInFlight_IsNotAgedOut_SoASecondRunCannotStart() { var time = new ManualTime(); var store = new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository(), Ttl, time); (await store.TryReserveAsync("c", "tu-long")).IsNew.Should().BeTrue(); // the tool is running, not completed time.Now += Ttl * 3; var second = await store.TryReserveAsync("c", "tu-long"); second.IsNew.Should().BeFalse("the first run has neither completed nor released, however long it takes"); second.CachedOutputJson.Should().Be("{}"); } [Fact] public async Task AReservationInFlight_ThatCompletesLate_IsKeptForTheTtlFromItsCompletion() { var time = new ManualTime(); var store = new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository(), Ttl, time); (await store.TryReserveAsync("c", "tu-long")).IsNew.Should().BeTrue(); time.Now += Ttl * 2; await store.CompleteAsync("c", "tu-long", """{"late":true}"""); time.Now += Ttl - TimeSpan.FromMinutes(1); var hit = await store.TryReserveAsync("c", "tu-long"); hit.IsNew.Should().BeFalse(); hit.CachedOutputJson.Should().Be("""{"late":true}"""); } [Fact] public async Task WithoutATtl_NothingExpires() { var time = new ManualTime(); var store = new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository(), ttl: null, time); (await store.TryReserveAsync("c", "tu-1")).IsNew.Should().BeTrue(); await store.CompleteAsync("c", "tu-1", "{}"); time.Now += TimeSpan.FromDays(365); (await store.TryReserveAsync("c", "tu-1")).IsNew.Should().BeFalse(); } [Theory] [InlineData(0)] [InlineData(-1)] public void ANonPositiveTtl_IsRefused(int seconds) { var act = () => new InMemoryToolIdempotencyStore(new InMemoryIdempotentRepository(), TimeSpan.FromSeconds(seconds)); act.Should().Throw(); } [Fact] public void TheDefaultRegistration_RemembersACompletedCallFor24Hours() { LlmServiceCollectionExtensions.DefaultToolIdempotencyTtl.Should().Be(TimeSpan.FromHours(24)); } } Path: redb-route/tests/redb.Route.Tests.Llm/LazyStreamTests.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/LazyStreamTests.cs ---- using System.Net; using System.Net.Sockets; using redb.Route.Http; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm; /// /// stream=body: the agent run, tools and all, happens when the body is read — after the route, as a streamed SQL /// result is read — and the text of every model call streams into Out.Body as the model writes it. The body /// belongs to its exchange: it reads the exchange's resources, so it is read once, released with the exchange, refused /// by RequestBody (which ends the exchange before it returns), and refused inside .Transacted(), whose block /// would commit before the answer exists. /// public sealed class LazyStreamTests { private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}"""; private const string Input = """{"q":"x"}"""; private const string Reply = """{"answer":"42"}"""; private static FakeProvider ToolThenAnswer() => new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_1") .EnqueueText("The answer is 42."); /// A one-call answer: for the tests about the body itself, where a tool would only add noise. private static FakeProvider PlainAnswer() => new FakeProvider().EnqueueText("The answer is 42."); private static LlmConnectionFactory Factory(ILlmProvider provider) => new() { Provider = "stub", PrebuiltProvider = provider }; private static async Task HostAsync( ILlmProvider provider, EchoToolRoute tool, bool transacted = false, string options = "&tools=lookup") { var host = LiveLlmHost.Build().AddFactory("demo", Factory(provider)); var uri = $"llm://demo?stream=body&maxIterations=4{options}"; await host.StartAsync(tool, r => { var from = r.From("direct:agent"); if (transacted) from.Transacted().To(uri); else from.To(uri); }); return host; } private static EchoToolRoute Lookup() => new("lookup", "Look up a fact.", Schema, Reply); private static IAsyncEnumerable BodyOf(IExchange exchange) => (IAsyncEnumerable)(exchange.Out?.Body ?? exchange.In.Body)!; private static async Task> ReadAsync(IAsyncEnumerable body) { var pieces = new List(); await foreach (var piece in body) pieces.Add(piece); return pieces; } [Fact] public async Task Body_WithTools_StreamsTheAnswerWhenRead() { var provider = new StreamingFakeProvider(ToolThenAnswer()); var tool = Lookup(); await using var host = await HostAsync(provider, tool); var exchange = await host.SendAsync("direct:agent", "What is the answer?"); try { provider.StreamCalls.Should().Be(0, "nothing runs until the body is read"); var pieces = await ReadAsync(BodyOf(exchange)); string.Concat(pieces).Should().Be("The answer is 42."); pieces.Should().HaveCountGreaterThan(1, "the text streams as the model writes it"); tool.CapturedInputs.Should().ContainSingle("the tool runs in the loop"); provider.StreamCalls.Should().Be(2, "both model calls are streamed"); exchange.Out!.Headers[LlmHeaders.ToolIterations].Should().Be(2, "the summary arrives after the run"); exchange.Out.Headers[LlmHeaders.StopReason].Should().Be(nameof(LlmStopReason.EndTurn)); } finally { await exchange.DisposeAsync(); } } [Fact] public async Task Body_ThinkingStaysOutOfTheBody() { var script = new FakeProvider().Enqueue(new LlmResponse { Content = [new LlmThinkingBlock("Let me look it up."), new LlmTextBlock("The answer is 42.")], StopReason = LlmStopReason.EndTurn }); await using var host = await HostAsync(new StreamingFakeProvider(script), Lookup(), options: ""); var exchange = await host.SendAsync("direct:agent", "What is the answer?"); try { string.Concat(await ReadAsync(BodyOf(exchange))).Should().Be("The answer is 42.", "thinking is not a reply and never reaches the body"); } finally { await exchange.DisposeAsync(); } } [Fact] public async Task Body_InsideTransacted_IsRefused() { var provider = new StreamingFakeProvider(PlainAnswer()); await using var host = await HostAsync(provider, Lookup(), transacted: true, options: ""); IExchange? exchange = null; var thrown = await Record.ExceptionAsync(async () => exchange = await host.SendAsync("direct:agent", "What is the answer?")); var failure = thrown ?? exchange?.Exception; if (exchange is not null) await exchange.DisposeAsync(); failure.Should().NotBeNull( "the run would happen after the block committed, its tools outside the transaction the route declared"); failure!.ToString().Should().Contain(".Transacted()", "the message says what the placement is wrong about") .And.Contain("stream=calls", "and names the mode that stays inside the transaction"); provider.StreamCalls.Should().Be(0); } [Fact] public async Task Body_ReadAfterTheExchangeEnded_Fails() { var provider = new StreamingFakeProvider(PlainAnswer()); await using var host = await HostAsync(provider, Lookup(), options: ""); var exchange = await host.SendAsync("direct:agent", "What is the answer?"); var body = BodyOf(exchange); await exchange.DisposeAsync(); var thrown = await Record.ExceptionAsync(() => ReadAsync(body)); thrown.Should().BeOfType("the run reads the exchange's resources, which are gone"); provider.StreamCalls.Should().Be(0, "nothing ran for a body nobody can read"); } [Fact] public async Task Body_ReadTwice_Fails() { await using var host = await HostAsync(new StreamingFakeProvider(PlainAnswer()), Lookup(), options: ""); var exchange = await host.SendAsync("direct:agent", "What is the answer?"); try { var body = BodyOf(exchange); await ReadAsync(body); var thrown = await Record.ExceptionAsync(() => ReadAsync(body)); thrown.Should().BeOfType("one read is one agent run; a second read would run it again"); } finally { await exchange.DisposeAsync(); } } [Fact] public async Task Body_ThroughRequestBody_IsRefused() { await using var host = await HostAsync(new StreamingFakeProvider(PlainAnswer()), Lookup(), options: ""); var thrown = await Record.ExceptionAsync(() => host.ProducerTemplate.RequestBody("direct:agent", "What is the answer?")); thrown.Should().BeOfType( "RequestBody ends the exchange before it returns, and this body reads the exchange's resources"); thrown!.Message.Should().Contain("RequestAsync"); } private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); [Fact] public async Task Body_OverHttp_IsServerSentEvents_WithTheSummaryLast() { var port = FreePort(); var provider = new StreamingFakeProvider(ToolThenAnswer()); var tool = Lookup(); await using var host = LiveLlmHost.Build(httpHosting: new HttpHostingOptions(), httpPort: port) .AddFactory("demo", Factory(provider)); await host.StartAsync(tool, r => r.From($"http:127.0.0.1:{port}/agent?inOut=true") .To("llm://demo?stream=body&tools=lookup&maxIterations=4")); using var http = new HttpClient(); using var response = await http.PostAsync($"http://127.0.0.1:{port}/agent", new StringContent("What is the answer?")); var text = await response.Content.ReadAsStringAsync(); response.Content.Headers.ContentType!.MediaType.Should().Be("text/event-stream", "the reply is a stream of events, whatever type the request carried"); var data = text.Split('\n') .Where(l => l.StartsWith("data: ", StringComparison.Ordinal) && !l.Contains("llm.tool.iterations")) .Select(l => l["data: ".Length..]); string.Concat(data).Should().Be("The answer is 42."); text.Should().Contain("event: done", "the summary of the run comes last, after the text"); text.Should().Contain("\"llm.tool.iterations\":2", "two model calls, the tool call and the answer, and the summary carries numbers as JSON numbers"); tool.CapturedInputs.Should().ContainSingle(); } } Path: redb-route/tests/redb.Route.Tests.Llm/LiveProviderTests.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/LiveProviderTests.cs ---- using System.Net; using System.Net.Http; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm; /// /// Live integration tests against real free-tier OpenAI-compatible providers. /// /// Each test is gated by an environment variable. If the key is missing the test /// is skipped (no failure) so CI runs stay green without secrets. On 429 /// (rate-limit) responses each call retries up to 3 times with exponential /// backoff that respects Retry-After. /// /// /// Local setup (any subset works — others auto-skip): /// /// $env:REDB_LLM_GITHUB_KEY = "ghp_..." # GitHub PAT — GitHub Models, free /// $env:REDB_LLM_GROQ_KEY = "gsk_..." # console.groq.com /// $env:REDB_LLM_GROK_KEY = "xai-..." # console.x.ai (xAI Grok) /// $env:REDB_LLM_CEREBRAS_KEY = "csk-..." # cloud.cerebras.ai /// $env:REDB_LLM_OPENROUTER_KEY = "sk-or-..." # openrouter.ai (:free models) /// $env:REDB_LLM_GEMINI_KEY = "AIza..." # aistudio.google.com /// $env:REDB_LLM_MISTRAL_KEY = "..." # console.mistral.ai /// /// Run only the live suite: /// dotnet test --filter "Category=LiveLlm" /// /// [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] // disables intra-class parallelism — important for 429-prone free tiers public sealed class LiveProviderTests { private static readonly HttpClient SharedHttp = new() { Timeout = TimeSpan.FromSeconds(60) }; private static LlmConnectionFactory MakeFactory(string name, string provider, string modelId, string envVar) => new() { Name = name, Provider = provider, ModelId = modelId, ApiKey = Environment.GetEnvironmentVariable(envVar), Temperature = 0.0, MaxTokens = 64 }; private static async Task CompleteWithRetryAsync(OpenAiProvider provider, LlmRequest request) { const int maxAttempts = 4; for (var attempt = 1; ; attempt++) { try { return await provider.CompleteAsync(request).ConfigureAwait(false); } catch (HttpRequestException ex) when (attempt < maxAttempts && Is429(ex.Message)) { // Free tiers (Gemini 15 RPM, OpenRouter shared upstream) need long backoff. var delay = TimeSpan.FromSeconds(5 * attempt); await Task.Delay(delay).ConfigureAwait(false); } } } private static bool Is429(string message) => message.Contains("429") || message.Contains("Too Many Requests", StringComparison.OrdinalIgnoreCase); // =================================================================== // Reusable scenarios — each takes a factory and runs a real call. // =================================================================== private static async Task SmokeAsync(LlmConnectionFactory factory) { var provider = new OpenAiProvider(factory, SharedHttp); var request = new LlmRequest { SystemPrompt = "You are a calculator. Answer with the number only, no words.", Messages = [LlmMessage.User("What is 2+2?")], Temperature = 0.0, // Reasoning models (Cerebras gpt-oss-120b, zai-glm-4.7) emit a long // chain-of-thought before the visible answer; small caps truncate it. MaxTokens = 512 }; var response = await CompleteWithRetryAsync(provider, request).ConfigureAwait(false); response.Content.Should().NotBeEmpty(); var text = response.Content.OfType().FirstOrDefault()?.Text ?? ""; text.Should().NotBeNullOrWhiteSpace($"{factory.Provider} returned empty content"); text.Should().Contain("4"); } // Note for maintainers: this suite is English-only so it is portable across // contributors and CI runners regardless of locale. If you want to verify // a particular non-English language (e.g. Russian, Chinese, Arabic) for // your own deployment, run a private fork of this test with a localized // prompt and a script-specific assertion. private static async Task NonAsciiAsync(LlmConnectionFactory factory) { var provider = new OpenAiProvider(factory, SharedHttp); var request = new LlmRequest { SystemPrompt = "Reply with EXACTLY one short sentence in plain English. " + "Then on a new line write the same sentence using only é, è, à, ü, ö, ß accents " + "(use any reasonable European spelling).", Messages = [LlmMessage.User("Say hello.")], Temperature = 0.0, MaxTokens = 64 }; var response = await CompleteWithRetryAsync(provider, request).ConfigureAwait(false); var text = response.Content.OfType().FirstOrDefault()?.Text ?? ""; text.Should().NotBeNullOrWhiteSpace(); // Sanity check: non-empty multi-line UTF-8 round-trip. text.Length.Should().BeGreaterThan(2, $"{factory.Provider} returned suspiciously short text: '{text}'"); } private static async Task ToolUseAsync(LlmConnectionFactory factory) { var provider = new OpenAiProvider(factory, SharedHttp); var request = new LlmRequest { SystemPrompt = "You MUST call the get_weather tool with city='Berlin'. Do not answer from memory.", Messages = [LlmMessage.User("What is the weather in Berlin?")], Temperature = 0.0, MaxTokens = 256, Tools = [ new LlmToolCapability { Name = "get_weather", Description = "Returns the current weather for a given city.", InputSchema = """ { "type": "object", "properties": { "city": { "type": "string" } }, "required": ["city"] } """ } ] }; var response = await CompleteWithRetryAsync(provider, request).ConfigureAwait(false); var toolUses = response.Content.OfType().ToList(); var texts = response.Content.OfType().ToList(); (toolUses.Count > 0 || texts.Count > 0).Should().BeTrue( $"{factory.Provider} returned no content blocks at all"); if (toolUses.Count > 0) { toolUses[0].Name.Should().Be("get_weather"); toolUses[0].InputJson.Should().Contain("Berlin"); } } private static async Task UsageReportedAsync(LlmConnectionFactory factory) { var provider = new OpenAiProvider(factory, SharedHttp); var request = new LlmRequest { Messages = [LlmMessage.User("Say 'ok' and nothing else.")], Temperature = 0.0, MaxTokens = 8 }; var response = await CompleteWithRetryAsync(provider, request).ConfigureAwait(false); response.Usage.InputTokens.Should().BeGreaterThan(0, $"{factory.Provider} should report input tokens"); response.Usage.OutputTokens.Should().BeGreaterThan(0, $"{factory.Provider} should report output tokens"); } private static async Task StopReasonAsync(LlmConnectionFactory factory) { var provider = new OpenAiProvider(factory, SharedHttp); var request = new LlmRequest { Messages = [LlmMessage.User("Reply with the single word: ok")], Temperature = 0.0, MaxTokens = 8 }; var response = await CompleteWithRetryAsync(provider, request).ConfigureAwait(false); response.RawStopReason.Should().NotBeNullOrEmpty(); } // =================================================================== // Per-provider tests. One row per (provider, scenario) — when the env // var is missing the row is skipped. // =================================================================== // ---------- GitHub Models ---------- [EnvFact("REDB_LLM_GITHUB_KEY")] public Task GitHub_Smoke() => SmokeAsync(GH()); [EnvFact("REDB_LLM_GITHUB_KEY")] public Task GitHub_NonAscii() => NonAsciiAsync(GH()); [EnvFact("REDB_LLM_GITHUB_KEY")] public Task GitHub_ToolUse() => ToolUseAsync(GH()); [EnvFact("REDB_LLM_GITHUB_KEY")] public Task GitHub_Usage() => UsageReportedAsync(GH()); [EnvFact("REDB_LLM_GITHUB_KEY")] public Task GitHub_Stop() => StopReasonAsync(GH()); private static LlmConnectionFactory GH() => MakeFactory("github", "github-models", "gpt-4o-mini", "REDB_LLM_GITHUB_KEY"); // ---------- Groq ---------- [EnvFact("REDB_LLM_GROQ_KEY")] public Task Groq_Smoke() => SmokeAsync(Groq()); [EnvFact("REDB_LLM_GROQ_KEY")] public Task Groq_NonAscii() => NonAsciiAsync(Groq()); [EnvFact("REDB_LLM_GROQ_KEY")] public Task Groq_ToolUse() => ToolUseAsync(Groq()); [EnvFact("REDB_LLM_GROQ_KEY")] public Task Groq_Usage() => UsageReportedAsync(Groq()); [EnvFact("REDB_LLM_GROQ_KEY")] public Task Groq_Stop() => StopReasonAsync(Groq()); private static LlmConnectionFactory Groq() => MakeFactory("groq", "groq", "llama-3.3-70b-versatile", "REDB_LLM_GROQ_KEY"); // ---------- xAI Grok ---------- [EnvFact("REDB_LLM_GROK_KEY")] public Task Grok_Smoke() => SmokeAsync(Grok()); [EnvFact("REDB_LLM_GROK_KEY")] public Task Grok_NonAscii() => NonAsciiAsync(Grok()); [EnvFact("REDB_LLM_GROK_KEY")] public Task Grok_ToolUse() => ToolUseAsync(Grok()); [EnvFact("REDB_LLM_GROK_KEY")] public Task Grok_Usage() => UsageReportedAsync(Grok()); [EnvFact("REDB_LLM_GROK_KEY")] public Task Grok_Stop() => StopReasonAsync(Grok()); private static LlmConnectionFactory Grok() => MakeFactory("grok", "grok", "grok-3-mini", "REDB_LLM_GROK_KEY"); // ---------- Cerebras (current free models: gpt-oss-120b, zai-glm-4.7) ---------- [EnvFact("REDB_LLM_CEREBRAS_KEY")] public Task Cerebras_Smoke() => SmokeAsync(Cerebras()); [EnvFact("REDB_LLM_CEREBRAS_KEY")] public Task Cerebras_NonAscii() => NonAsciiAsync(Cerebras()); [EnvFact("REDB_LLM_CEREBRAS_KEY")] public Task Cerebras_ToolUse() => ToolUseAsync(Cerebras()); [EnvFact("REDB_LLM_CEREBRAS_KEY")] public Task Cerebras_Usage() => UsageReportedAsync(Cerebras()); private static LlmConnectionFactory Cerebras() => MakeFactory("cerebras", "cerebras", "gpt-oss-120b", "REDB_LLM_CEREBRAS_KEY"); // ---------- OpenRouter (use Gemma — most stable :free upstream) ---------- [EnvFact("REDB_LLM_OPENROUTER_KEY")] public Task OpenRouter_Smoke() => SmokeAsync(OR()); [EnvFact("REDB_LLM_OPENROUTER_KEY")] public Task OpenRouter_NonAscii() => NonAsciiAsync(OR()); [EnvFact("REDB_LLM_OPENROUTER_KEY")] public Task OpenRouter_ToolUse() => ToolUseAsync(OR()); private static LlmConnectionFactory OR() => MakeFactory("openrouter", "openrouter", "meta-llama/llama-3.3-70b-instruct:free", "REDB_LLM_OPENROUTER_KEY"); // ---------- Google Gemini (OpenAI-compat) ---------- [EnvFact("REDB_LLM_GEMINI_KEY")] public Task Gemini_Smoke() => SmokeAsync(Gemini()); [EnvFact("REDB_LLM_GEMINI_KEY")] public Task Gemini_NonAscii() => NonAsciiAsync(Gemini()); [EnvFact("REDB_LLM_GEMINI_KEY")] public Task Gemini_ToolUse() => ToolUseAsync(Gemini()); [EnvFact("REDB_LLM_GEMINI_KEY")] public Task Gemini_Usage() => UsageReportedAsync(Gemini()); private static LlmConnectionFactory Gemini() => MakeFactory("gemini", "gemini", "gemini-2.0-flash", "REDB_LLM_GEMINI_KEY"); // ---------- Mistral ---------- [EnvFact("REDB_LLM_MISTRAL_KEY")] public Task Mistral_Smoke() => SmokeAsync(Mistral()); [EnvFact("REDB_LLM_MISTRAL_KEY")] public Task Mistral_NonAscii() => NonAsciiAsync(Mistral()); [EnvFact("REDB_LLM_MISTRAL_KEY")] public Task Mistral_ToolUse() => ToolUseAsync(Mistral()); [EnvFact("REDB_LLM_MISTRAL_KEY")] public Task Mistral_Usage() => UsageReportedAsync(Mistral()); private static LlmConnectionFactory Mistral() => MakeFactory("mistral", "mistral", "mistral-small-latest", "REDB_LLM_MISTRAL_KEY"); } Path: redb-route/tests/redb.Route.Tests.Llm/LiveStreamingTests.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/LiveStreamingTests.cs ---- using System.Net.Http; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm; /// /// Live integration tests for provider-level streaming (). /// Each test is env-gated and auto-skips when the corresponding key is missing. /// /// What we assert (per provider): /// /// more than one chunk arrives — proves the wire is truly streaming, not a single /// buffered response delivered in one frame; /// at least one chunk carries a text delta; /// the concatenated answer contains the expected substring ("4" for "2+2"); /// some chunk reports a non-null StopReason (the terminal frame). /// /// /// [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] public sealed class LiveStreamingTests { private static readonly HttpClient SharedHttp = new() { Timeout = TimeSpan.FromSeconds(60) }; private static LlmConnectionFactory MakeFactory(string name, string provider, string modelId, string envVar) => new() { Name = name, Provider = provider, ModelId = modelId, ApiKey = Environment.GetEnvironmentVariable(envVar), Temperature = 0.0, MaxTokens = 64 }; private static LlmRequest MathRequest() => new() { SystemPrompt = "You are a calculator. Answer with the number only, no words.", Messages = [LlmMessage.User("What is 2+2?")], Temperature = 0.0, MaxTokens = 512 }; private sealed record StreamSummary( int ChunkCount, int TextDeltaCount, string Text, bool SawStopReason, LlmUsage? LastUsage); private static async Task CollectAsync(ILlmProvider provider, LlmRequest request) { const int maxAttempts = 4; for (var attempt = 1; ; attempt++) { try { return await CollectOnceAsync(provider, request).ConfigureAwait(false); } catch (HttpRequestException ex) when (attempt < maxAttempts && Is429(ex.Message)) { await Task.Delay(TimeSpan.FromSeconds(5 * attempt)).ConfigureAwait(false); } } } private static async Task CollectOnceAsync(ILlmProvider provider, LlmRequest request) { var chunkCount = 0; var textCount = 0; var sb = new System.Text.StringBuilder(); var sawStop = false; LlmUsage? lastUsage = null; using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60)); await foreach (var chunk in provider.StreamAsync(request, cts.Token).ConfigureAwait(false)) { chunkCount++; foreach (var block in chunk.Content) { if (block is LlmTextBlock text) { textCount++; sb.Append(text.Text); } } if (chunk.StopReason is not null) sawStop = true; if (chunk.Usage is not null) lastUsage = chunk.Usage; } return new StreamSummary(chunkCount, textCount, sb.ToString(), sawStop, lastUsage); } private static bool Is429(string message) => message.Contains("429") || message.Contains("Too Many Requests", StringComparison.OrdinalIgnoreCase); private static async Task SmokeStreamAsync(ILlmProvider provider) { var summary = await CollectAsync(provider, MathRequest()).ConfigureAwait(false); summary.ChunkCount.Should().BeGreaterThan(1, $"{provider.ProviderId}: streaming must yield more than one chunk, got {summary.ChunkCount}"); summary.TextDeltaCount.Should().BeGreaterThan(0, $"{provider.ProviderId}: at least one text delta expected"); summary.Text.Should().Contain("4", $"{provider.ProviderId}: accumulated text should contain the answer, got '{summary.Text}'"); summary.SawStopReason.Should().BeTrue( $"{provider.ProviderId}: terminal chunk must carry a StopReason"); } // ---------- Anthropic Claude Haiku (true SSE) ---------- [EnvFact("REDB_LLM_ANT_API03_KEY")] public Task Anthropic_ClaudeHaiku_Stream() => SmokeStreamAsync( new AnthropicProvider( new LlmConnectionFactory { Name = "anthropic-haiku", Provider = "anthropic", ModelId = "claude-haiku-4-5", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_ANT_API03_KEY"), Temperature = 0.0, MaxTokens = 64 }, SharedHttp)); // ---------- Groq (OpenAI-compatible SSE) ---------- [EnvFact("REDB_LLM_GROQ_KEY")] public Task Groq_Stream() => SmokeStreamAsync( new OpenAiProvider( MakeFactory("groq", "groq", "llama-3.3-70b-versatile", "REDB_LLM_GROQ_KEY"), SharedHttp)); // ---------- Cerebras ---------- [EnvFact("REDB_LLM_CEREBRAS_KEY")] public Task Cerebras_Stream() => SmokeStreamAsync( new OpenAiProvider( MakeFactory("cerebras", "cerebras", "gpt-oss-120b", "REDB_LLM_CEREBRAS_KEY"), SharedHttp)); // ---------- Google Gemini (OpenAI-compat) ---------- [EnvFact("REDB_LLM_GEMINI_KEY")] public Task Gemini_Stream() => SmokeStreamAsync( new OpenAiProvider( MakeFactory("gemini", "gemini", "gemini-2.0-flash", "REDB_LLM_GEMINI_KEY"), SharedHttp)); // ---------- Mistral ---------- [EnvFact("REDB_LLM_MISTRAL_KEY")] public Task Mistral_Stream() => SmokeStreamAsync( new OpenAiProvider( MakeFactory("mistral", "mistral", "mistral-small-latest", "REDB_LLM_MISTRAL_KEY"), SharedHttp)); // ---------- OpenRouter ---------- [EnvFact("REDB_LLM_OPENROUTER_KEY")] public Task OpenRouter_Stream() => SmokeStreamAsync( new OpenAiProvider( MakeFactory("openrouter", "openrouter", "meta-llama/llama-3.3-70b-instruct:free", "REDB_LLM_OPENROUTER_KEY"), SharedHttp)); } Path: redb-route/tests/redb.Route.Tests.Llm/LiveTranscriptionTests.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/LiveTranscriptionTests.cs ---- using System.Text; using AwesomeAssertions; using redb.Route.Llm; using redb.Route.Llm.Providers; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm; /// /// A live check of the transcription transport against a real server. /// /// The stub tests () prove the shape of the request /// as the transport's author meant it. What they do not prove is that a real server accepts EXACTLY /// that shape: the form field names, the file name, the content type and how it /// reads response_format. That is exactly where multipart transports break, and a stub /// cannot show it at all. /// /// Turned on by the variable REDB_STT_BASE_URL, for example /// http://127.0.0.1:8083/v1/ (whisper.cpp server, Speaches, LM Studio or a local speech-to-text /// container). Unset, the fact is skipped, like the other live ones. /// public sealed class LiveTranscriptionTests { private const string BaseUrlVariable = "REDB_STT_BASE_URL"; private const string ModelVariable = "REDB_STT_MODEL"; private static OpenAiTranscriptionProvider Provider() { var baseUrl = Environment.GetEnvironmentVariable(BaseUrlVariable)!; return OpenAiTranscriptionProvider.Create(new LlmConnectionFactory { Name = "live-stt", Provider = "whisper", ModelId = Environment.GetEnvironmentVariable(ModelVariable) ?? "medium", BaseUrl = new Uri(baseUrl), ApiKey = Environment.GetEnvironmentVariable("REDB_STT_KEY"), RequestTimeoutMs = 300_000, }); } /// /// A valid WAV: one second of tone, one second of silence. There is no speech in it, and here that is a /// convenience, not a problem: the transport is checked, not the model's hearing. /// private static byte[] ToneWav(int seconds = 2, int rate = 16000, double hz = 220) { var samples = rate * seconds; var data = new byte[samples * 2]; for (var i = 0; i < samples; i++) { short value = i < samples / 2 ? (short)(12000 * Math.Sin(2 * Math.PI * hz * i / rate)) : (short)0; data[i * 2] = (byte)(value & 0xFF); data[i * 2 + 1] = (byte)((value >> 8) & 0xFF); } using var stream = new MemoryStream(); using var writer = new BinaryWriter(stream, Encoding.ASCII, leaveOpen: true); writer.Write("RIFF"u8.ToArray()); writer.Write(36 + data.Length); writer.Write("WAVE"u8.ToArray()); writer.Write("fmt "u8.ToArray()); writer.Write(16); // format block size writer.Write((short)1); // PCM writer.Write((short)1); // mono writer.Write(rate); writer.Write(rate * 2); // bytes per second writer.Write((short)2); // block alignment writer.Write((short)16); // bits per sample writer.Write("data"u8.ToArray()); writer.Write(data.Length); writer.Write(data); writer.Flush(); return stream.ToArray(); } [EnvFact(BaseUrlVariable)] public async Task A_live_server_accepts_our_upload_form() { var provider = Provider(); var result = await provider.TranscribeAsync( new TranscriptionRequest(ToneWav(), "probe.wav", Language: "ru")); // The text may be anything, empty included: the server may hear no speech in a tone. // What is proven is something else: the request arrived, was understood and parsed without an exception. result.Text.Should().NotBeNull(); provider.ModelId.Should().NotBeNullOrWhiteSpace(); } /// /// A recording without speech must come back EMPTY. Whisper does not stay silent on silence, it /// makes things up: on the very first run of the synthetic tone it produced a stock phrase /// (a typical hallucination learned from video subtitles). For a route this is not a curiosity: /// the invented phrase would go to the model as the words of a person. /// /// The server itself suppresses it (the no_speech_prob threshold), not the transport, so /// the fact is live: it checks the stand, not our code. /// [EnvFact(BaseUrlVariable)] public async Task A_live_server_does_not_invent_words_for_a_recording_without_speech() { var result = await Provider().TranscribeAsync( new TranscriptionRequest(ToneWav(), "probe.wav", Language: "ru")); result.Text.Should().BeEmpty( "a recording without speech must come back as an empty string: an invented phrase would go " + "into the conversation as the person's words"); } } Path: redb-route/tests/redb.Route.Tests.Llm/LlmAuditPersistenceTests.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/LlmAuditPersistenceTests.cs ---- using redb.Route.Llm.Engine.Storage; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm; /// /// Producer-level coverage for the audit-extension wiring (3.1.1): /// ?user= + ?audit= URI options + llm.user.id / /// llm.audit.<name> headers reach the conversation store /// stamped on every persisted row of the run. Backed by /// — no DB required. /// public sealed class LlmAuditPersistenceTests { private static (RouteContext ctx, LlmEndpoint endpoint, InMemoryConversationStore store) Build(FakeProvider provider, string uri) { var ctx = new RouteContext(); var component = new LlmComponent(); ctx.AddComponent(component); ctx.AddToRegistry("fake", new LlmConnectionFactory { Name = "fake", Provider = "fake", ModelId = provider.ModelId, PrebuiltProvider = provider }); var store = new InMemoryConversationStore(); ctx.AddService(typeof(IAgentEngine), new AgentEngine( logger: null, producerTemplate: null, observer: null, budget: null, approval: null, redaction: null, shadow: null, conversation: store, idempotency: null, approvalStore: null)); var endpoint = (LlmEndpoint)component.CreateEndpoint(EndpointUriParser.Parse(uri)); return (ctx, endpoint, store); } private static async Task> RunAsync(string uri, Action? configureIn = null) { var fake = new FakeProvider().EnqueueText("ok", tokensIn: 1, tokensOut: 1); var (_, endpoint, store) = Build(fake, uri); var producer = (LlmProducer)endpoint.CreateProducer(); await producer.Start(); var msg = new Message("hi"); msg.Headers[LlmHeaders.ConversationId] = "c-test"; configureIn?.Invoke(msg); await producer.Process(new Exchange(msg)); return await store.LoadTreeAsync("c-test"); } [Fact] public async Task User_LiteralOption_StampedOnEveryRow() { var rows = await RunAsync("llm://fake?user=system&conversation=header"); rows.Should().NotBeEmpty(); rows.Select(r => r.Meta.UserId).Should().AllBeEquivalentTo("system"); } [Fact] public async Task User_HeaderExpression_ResolvesAtRunTime() { var encoded = "%24%7Bheader.X-User-Id%7D"; // ${header.X-User-Id} var rows = await RunAsync( $"llm://fake?user={encoded}&conversation=header", m => m.Headers["X-User-Id"] = "alice@example.com"); rows.Select(r => r.Meta.UserId).Should().AllBeEquivalentTo("alice@example.com"); } [Fact] public async Task User_HeaderFallback_FromLlmUserIdHeader() { var rows = await RunAsync( "llm://fake?conversation=header", m => m.Headers[LlmHeaders.UserId] = "bob"); rows.Select(r => r.Meta.UserId).Should().AllBeEquivalentTo("bob"); } [Fact] public async Task Audit_OptionCsv_IsStampedOnEveryRow() { var rows = await RunAsync( "llm://fake?conversation=header&audit=tier%3Dgold%2Cbucket%3DA"); rows.Should().NotBeEmpty(); foreach (var r in rows) { r.Meta.AuditTags.Should().NotBeNull(); r.Meta.AuditTags!["tier"].Should().Be("gold"); r.Meta.AuditTags!["bucket"].Should().Be("A"); } } [Fact] public async Task Audit_HeaderTags_AreMergedAndWinOnCollision() { var rows = await RunAsync( "llm://fake?conversation=header&audit=tier%3Dgold%2Cbucket%3DA", m => { m.Headers["llm.audit.tier"] = "platinum"; // overrides option-side "gold" m.Headers["llm.audit.region"] = "eu-west"; // adds new key }); var tags = rows[0].Meta.AuditTags!; tags["tier"].Should().Be("platinum"); tags["bucket"].Should().Be("A"); tags["region"].Should().Be("eu-west"); } [Fact] public async Task PromptTemplate_NameAndVersion_AreStampedOnEveryRow() { var rows = await RunAsync( "llm://fake?conversation=header&promptTemplateName=triage&promptTemplateVersion=v3"); rows.Should().NotBeEmpty(); rows.Select(r => r.Meta.PromptTemplateName).Should().AllBeEquivalentTo("triage"); rows.Select(r => r.Meta.PromptTemplateVersion).Should().AllBeEquivalentTo("v3"); } [Fact] public async Task User_OptionWins_OverHeaderFallback() { var rows = await RunAsync( "llm://fake?conversation=header&user=system", m => m.Headers[LlmHeaders.UserId] = "ignored"); rows.Select(r => r.Meta.UserId).Should().AllBeEquivalentTo("system"); } [Fact] public async Task NoUserNoAudit_LeavesMetaNull() { var rows = await RunAsync("llm://fake?conversation=header"); rows.Should().NotBeEmpty(); rows.Should().OnlyContain(r => r.Meta.UserId == null); rows.Should().OnlyContain(r => r.Meta.AuditTags == null); } [Fact] public async Task FactoryName_IsStampedOnEveryRow() { // Build helper registers the factory under name "fake". var rows = await RunAsync("llm://fake?conversation=header"); rows.Should().NotBeEmpty(); rows.Select(r => r.Meta.FactoryName).Should().AllBeEquivalentTo("fake"); } [Fact] public async Task ProviderResponseId_AndLatency_AreStampedOnAssistantRow() { var rows = await RunAsync("llm://fake?conversation=header"); var assistant = rows.Should().ContainSingle(r => r.Message.Role == "assistant").Subject; // FakeProvider sets ProviderResponseId via EnqueueText defaults; if null, latency must still be present. assistant.Meta.LatencyMs.Should().NotBeNull(); assistant.Meta.LatencyMs!.Value.Should().BeGreaterThanOrEqualTo(0); } [Fact] public async Task ProviderResponseId_RoundTripsFromProviderResponse() { // Drive the producer with a hand-built LlmResponse so we can pin a known id. var fake = new FakeProvider(); fake.Enqueue(new LlmResponse { Content = [new LlmTextBlock("ok")], StopReason = LlmStopReason.EndTurn, Usage = new LlmUsage(1, 1), ProviderResponseId = "resp_abc123" }); var (_, endpoint, store) = Build(fake, "llm://fake?conversation=header"); var producer = (LlmProducer)endpoint.CreateProducer(); await producer.Start(); var msg = new Message("hi"); msg.Headers[LlmHeaders.ConversationId] = "c-rid"; await producer.Process(new Exchange(msg)); var rows = await store.LoadTreeAsync("c-rid"); var assistant = rows.Should().ContainSingle(r => r.Message.Role == "assistant").Subject; assistant.Meta.ProviderResponseId.Should().Be("resp_abc123"); } [Fact] public async Task LatencyAndResponseId_AreNullOnNonAssistantRows() { var rows = await RunAsync("llm://fake?conversation=header"); rows.Where(r => r.Message.Role != "assistant") .Should().OnlyContain(r => r.Meta.LatencyMs == null); rows.Where(r => r.Message.Role != "assistant") .Should().OnlyContain(r => r.Meta.ProviderResponseId == null); } [Fact] public async Task RetryCount_NullByDefault_OnFirstDelivery() { var rows = await RunAsync("llm://fake?conversation=header"); rows.Should().NotBeEmpty(); rows.Should().OnlyContain(r => r.Meta.RetryCount == null); } [Fact] public async Task RetryCount_FromRetryAttemptProperty_StampedOnEveryRow() { var fake = new FakeProvider().EnqueueText("ok", tokensIn: 1, tokensOut: 1); var (_, endpoint, store) = Build(fake, "llm://fake?conversation=header"); var producer = (LlmProducer)endpoint.CreateProducer(); await producer.Start(); var msg = new Message("hi"); msg.Headers[LlmHeaders.ConversationId] = "c-retry-prop"; var exchange = new Exchange(msg); // RetryProcessor.cs writes this property each retry attempt. exchange.Properties["RetryAttempt"] = 2; await producer.Process(exchange); var rows = await store.LoadTreeAsync("c-retry-prop"); rows.Should().NotBeEmpty(); rows.Select(r => r.Meta.RetryCount).Should().AllBeEquivalentTo(2); } [Fact] public async Task RetryCount_FallsBackTo_CamelRedeliveryCounter() { var fake = new FakeProvider().EnqueueText("ok", tokensIn: 1, tokensOut: 1); var (_, endpoint, store) = Build(fake, "llm://fake?conversation=header"); var producer = (LlmProducer)endpoint.CreateProducer(); await producer.Start(); var msg = new Message("hi"); msg.Headers[LlmHeaders.ConversationId] = "c-retry-hdr"; // OnExceptionProcessor stamps this header on the inbound message. msg.Headers["CamelRedeliveryCounter"] = 3; await producer.Process(new Exchange(msg)); var rows = await store.LoadTreeAsync("c-retry-hdr"); rows.Should().NotBeEmpty(); rows.Select(r => r.Meta.RetryCount).Should().AllBeEquivalentTo(3); } } Path: redb-route/tests/redb.Route.Tests.Llm/LlmBuilderTests.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/LlmBuilderTests.cs ---- using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm; public sealed class LlmBuilderTests { [Fact] public void Factory_StartsWithLlmScheme() { LlmDsl.Factory("claude").AsUri().Should().StartWith("llm://claude"); } [Fact] public void NullFactory_Throws() { var act = () => LlmDsl.Factory(null!); act.Should().Throw(); } [Fact] public void EmptyFactory_Throws() { var act = () => LlmDsl.Factory(" "); act.Should().Throw(); } [Fact] public void Temperature_SetsParam() { LlmDsl.Factory("c").Temperature(0.25).AsUri().Should().Contain("temperature=0.25"); } [Fact] public void MaxTokens_SetsParam() { LlmDsl.Factory("c").MaxTokens(1024).AsUri().Should().Contain("maxTokens=1024"); } [Fact] public void TopP_SetsParam() { LlmDsl.Factory("c").TopP(0.9).AsUri().Should().Contain("topP=0.9"); } [Fact] public void SystemPromptRef_SetsParam() { LlmDsl.Factory("c").SystemPromptRef("translate-en").AsUri().Should().Contain("systemPromptRef=translate-en"); } [Fact] public void Conversation_FromHeader_SetsParam() { LlmDsl.Factory("c").ConversationFromHeader().AsUri().Should().Contain("conversation=header"); } [Fact] public void Conversation_FromRoute_SetsParam() { LlmDsl.Factory("c").ConversationFromRoute().AsUri().Should().Contain("conversation=property"); } [Fact] public void Stream_SetsTheMode() { LlmDsl.Factory("c").Stream(LlmStreamMode.Calls).AsUri().Should().Contain("stream=calls"); LlmDsl.Factory("c").Stream(LlmStreamMode.Body).AsUri().Should().Contain("stream=body"); LlmDsl.Factory("c").AsUri().Should().NotContain("stream", "no streaming is the absence of the option"); } [Fact] public void Schedule_SetsParam() { LlmDsl.Factory("c").Schedule("0 0/5 * * * ?").AsUri() .Should().Contain("schedule="); } [Fact] public void MaxIterations_SetsParam() { LlmDsl.Factory("c").MaxIterations(4).AsUri().Should().Contain("maxIterations=4"); } [Fact] public void CacheSystemPrompt_SetsParam_AndBindsToTheOption() { LlmDsl.Factory("c").CacheSystemPrompt().AsUri().Should().Contain("cacheSystemPrompt=true"); // The URI is only half the contract: the parameter has to land on the option the // producer reads, or the flag would be a string nobody acts on. var options = new LlmEndpointOptions(); options.BindFromUri(EndpointUriParser.Parse( LlmDsl.Factory("c").CacheSystemPrompt().AsUri()).RawParameters); options.CacheSystemPrompt.Should().BeTrue(); } [Fact] public void CacheSystemPrompt_IsAbsentUnlessAskedFor() { // Off by default and absent from the URI entirely: an address that says nothing about // caching must behave exactly as it did before the option existed. LlmDsl.Factory("c").MaxIterations(4).AsUri() .Should().NotContain("cacheSystemPrompt"); new LlmEndpointOptions().CacheSystemPrompt.Should().BeFalse(); } [Fact] public void Combined_ProducesMultipleParams() { var uri = LlmDsl.Factory("claude") .Temperature(0.0) .MaxTokens(512) .ConversationFromHeader() .Stream(LlmStreamMode.Body) .AsUri(); uri.Should().Contain("temperature=0"); uri.Should().Contain("maxTokens=512"); uri.Should().Contain("conversation=header"); uri.Should().Contain("stream=body"); } [Fact] public void ImplicitConversion_ProducesValidEndpointUri() { EndpointUri uri = LlmDsl.Factory("claude").Temperature(0.1).MaxTokens(64); uri.Scheme.Should().Be("llm"); uri.Path.Should().Be("claude"); } [Fact] public void User_LiteralExpression_SetsParam() { LlmDsl.Factory("c").User("system").AsUri().Should().Contain("user=system"); } [Fact] public void User_HeaderExpression_IsUrlEncodedOnce() { var uri = LlmDsl.Factory("c").User("${header.X-User-Id}").AsUri(); // ${header.X-User-Id} → URL-encoded values can be %24/%24 etc; just assert the key/value survive a parse. var parsed = EndpointUriParser.Parse(uri); parsed.RawParameters["user"].Should().Be("${header.X-User-Id}"); } [Fact] public void Audit_SinglePair_SetsParam() { var uri = LlmDsl.Factory("c").Audit("tier", "gold").AsUri(); var parsed = EndpointUriParser.Parse(uri); parsed.RawParameters["audit"].Should().Be("tier=gold"); } [Fact] public void Audit_MultiplePairs_JoinedWithComma() { var uri = LlmDsl.Factory("c").Audit("tier", "gold").Audit("bucket", "A").AsUri(); var parsed = EndpointUriParser.Parse(uri); parsed.RawParameters["audit"].Should().Be("tier=gold,bucket=A"); } [Fact] public void Audit_ValueWithCommaAndEquals_RoundTripsAfterUrlDecode() { var uri = LlmDsl.Factory("c").Audit("expr", "a=1,b=2").AsUri(); var parsed = EndpointUriParser.Parse(uri); // The CSV uses URL-encoded commas/equals inside the value, so the inner comma // does NOT split the pair — the producer's CSV parser sees "expr=a%3D1%2Cb%3D2" // (or similar) and URL-decodes each side. parsed.RawParameters["audit"].Should().Contain("expr="); parsed.RawParameters["audit"].Split(',').Should().HaveCount(1); } [Fact] public void Audit_NullKey_Throws() { var b = LlmDsl.Factory("c"); var act = () => b.Audit(null!, "v"); act.Should().Throw(); } [Fact] public void PromptTemplate_SetsBothParams() { var uri = LlmDsl.Factory("c").PromptTemplate("triage", "v3").AsUri(); uri.Should().Contain("promptTemplateName=triage"); uri.Should().Contain("promptTemplateVersion=v3"); } } Path: redb-route/tests/redb.Route.Tests.Llm/LlmComponentTests.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/LlmComponentTests.cs ---- namespace redb.Route.Tests.Llm; public sealed class LlmComponentTests { [Fact] public void Scheme_IsLlm() { new LlmComponent().Scheme.Should().Be("llm"); } [Fact] public void CreateEndpoint_ParsesPathAsFactoryName() { var component = new LlmComponent(); var uri = EndpointUriParser.Parse("llm://claude?temperature=0.2"); var endpoint = (LlmEndpoint)component.CreateEndpoint(uri); endpoint.ConnectionFactoryName.Should().Be("claude"); endpoint.Uri.RawParameters["temperature"].Should().Be("0.2"); } [Fact] public void CreateEndpoint_FactoryNameViaQuery_Works() { var component = new LlmComponent(); var uri = EndpointUriParser.Parse("llm://?connectionFactory=local"); var endpoint = (LlmEndpoint)component.CreateEndpoint(uri); endpoint.ConnectionFactoryName.Should().Be("local"); } [Fact] public void CreateEndpoint_NoFactoryName_Throws() { var component = new LlmComponent(); var uri = EndpointUriParser.Parse("llm://?temperature=0.1"); var act = () => component.CreateEndpoint(uri); act.Should().Throw().WithMessage("*connection factory*"); } [Fact] public void CreateEndpoint_InvalidTemperature_Throws() { var component = new LlmComponent(); var uri = EndpointUriParser.Parse("llm://c?temperature=5.0"); var act = () => component.CreateEndpoint(uri); act.Should().Throw(); } [Fact] public void CreateEndpoint_NullUri_Throws() { var component = new LlmComponent(); var act = () => component.CreateEndpoint(null!); act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests.Llm/LlmConnectionFactoryTests.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/LlmConnectionFactoryTests.cs ---- namespace redb.Route.Tests.Llm; public sealed class LlmConnectionFactoryTests { [Fact] public void Defaults_AreReasonable() { var f = new LlmConnectionFactory(); f.Provider.Should().Be("stub"); f.ModelId.Should().Be("stub-model"); f.RequestTimeoutMs.Should().Be(600_000, "ten minutes, like the official Anthropic and OpenAI SDKs: a thinking model's non-streaming answer takes minutes"); } [Fact] public void Build_StubProvider_Works() { var f = new LlmConnectionFactory { Provider = "stub", ModelId = "x" }; var p = f.Build(); p.Should().BeOfType(); p.ProviderId.Should().Be("stub"); p.ModelId.Should().Be("x"); } [Fact] public void Build_AnthropicProvider_ReturnsAnthropicType() { // Anthropic is placeholder; ctor must succeed even though CompleteAsync isn't implemented. var f = new LlmConnectionFactory { Provider = "anthropic", ModelId = "claude-haiku" }; var p = f.Build(); p.Should().BeOfType(); } [Fact] public void Build_UnknownProvider_Throws() { var f = new LlmConnectionFactory { Provider = "does-not-exist" }; var act = () => f.Build(); act.Should().Throw().WithMessage("*Unknown LLM provider*"); } [Fact] public void Build_PrebuiltProvider_TakesPrecedence() { var prebuilt = new StubProvider(new LlmConnectionFactory { ModelId = "x" }) { FixedReply = "pre" }; var f = new LlmConnectionFactory { Provider = "does-not-exist", // ignored PrebuiltProvider = prebuilt }; f.Build().Should().BeSameAs(prebuilt); } [Fact] public void ProviderName_IsCaseInsensitive() { var f = new LlmConnectionFactory { Provider = "STUB" }; f.Build().Should().BeOfType(); } } Path: redb-route/tests/redb.Route.Tests.Llm/LlmConsumerPromptExchangeTests.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/LlmConsumerPromptExchangeTests.cs ---- using System.Collections.Concurrent; using redb.Route.Llm.Engine.Storage; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm; /// /// The scheduled agent (From("llm://...?schedule=...")) resolves its prompt references with the tick's /// own exchange. A redb-backed template registry needs it to resolve a scope of that tick instead of the one /// shared instance every concurrent tick would land on. The lookup runs inside the block that owns the /// exchange, so a failing template releases it. /// public sealed class LlmConsumerPromptExchangeTests { /// Records every lookup: the exchange it was made with and whether that exchange had a DI scope. private sealed class RecordingTemplates(Func lookup) : IPromptTemplateRegistry { private readonly ConcurrentQueue<(IExchange? Exchange, bool HadScope)> _lookups = new(); public (IExchange? Exchange, bool HadScope)[] Lookups => _lookups.ToArray(); public Task GetAsync(string name, string? version = null, IExchange? exchange = null, CancellationToken ct = default) { _lookups.Enqueue((exchange, exchange?.ServiceProvider is not null)); return Task.FromResult(lookup(name)); } public Task SetAsync(PromptTemplate template, IExchange? exchange = null, CancellationToken ct = default) => Task.CompletedTask; public Task> ListAsync(IExchange? exchange = null, CancellationToken ct = default) => Task.FromResult>([]); } private static LiveLlmHost Host(FakeProvider fake, IPromptTemplateRegistry templates) { var host = LiveLlmHost.Build(); host.AddFactory("fake", new LlmConnectionFactory { Name = "fake", Provider = "fake", ModelId = fake.ModelId, PrebuiltProvider = fake }); host.Context.AddService(typeof(IPromptTemplateRegistry), templates); return host; } private static async Task WaitUntilAsync(Func condition) { var deadline = DateTime.UtcNow.AddSeconds(10); while (!condition() && DateTime.UtcNow < deadline) await Task.Delay(20); } [Fact] public async Task ScheduledTick_ResolvesPromptsWithItsExchange() { var calls = new ConcurrentQueue<(string? SystemPrompt, string? UserText)>(); var fake = new FakeProvider { OnCall = (request, _) => { var userText = request.Messages.LastOrDefault()?.Content.OfType().FirstOrDefault()?.Text; calls.Enqueue((request.SystemPrompt, userText)); return Task.CompletedTask; } }.EnqueueText("tick!"); var templates = new RecordingTemplates(name => new PromptTemplate { Name = name, Version = "1", Body = name == "go" ? "status of order 42?" : "Reply tersely." }); await using var host = Host(fake, templates); await host.StartAsync(r => r.From("llm://fake?schedule=200ms&initialBodyRef=#go&systemPromptRef=#terse") .To("mock:llm-ticks")); var sink = host.Mock("mock:llm-ticks"); await WaitUntilAsync(() => sink.ReceivedCount > 0); sink.ReceivedCount.Should().BeGreaterThan(0, "at least one tick has to reach the route"); var lookups = templates.Lookups; lookups.Should().NotBeEmpty(); lookups.Should().OnlyContain(l => l.Exchange != null, "a lookup without the tick's exchange lands every concurrent tick on one shared redb instance"); lookups.Should().OnlyContain(l => l.HadScope, "the exchange carries the tick's DI scope when the prompts resolve"); var first = calls.Should().NotBeEmpty().And.Subject.First(); first.SystemPrompt.Should().Be("Reply tersely."); first.UserText.Should().Be("status of order 42?", "the resolved initial body is still what the model is asked"); } [Fact] public async Task ScheduledTick_TemplateFailure_ReleasesTheExchange() { var fake = new FakeProvider(); var templates = new RecordingTemplates(_ => throw new InvalidOperationException("template store is down")); await using var host = Host(fake, templates); await host.StartAsync(r => r.From("llm://fake?schedule=200ms&initialBodyRef=#go").To("mock:llm-ticks")); await WaitUntilAsync(() => templates.Lookups.Length > 0); var lookup = templates.Lookups.Should().NotBeEmpty().And.Subject.First(); lookup.Exchange.Should().NotBeNull("the prompt is resolved with the tick's exchange"); lookup.HadScope.Should().BeTrue("the exchange owned a DI scope when the lookup failed"); // The failing lookup runs inside the block that owns the exchange, so the tick's scope is released. await WaitUntilAsync(() => lookup.Exchange!.ServiceProvider is null); lookup.Exchange!.ServiceProvider.Should().BeNull("a failed template lookup must not leak the tick's DI scope"); fake.CallCount.Should().Be(0, "the tick failed before the model was called"); } } Path: redb-route/tests/redb.Route.Tests.Llm/LlmEndpointOptionsTests.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/LlmEndpointOptionsTests.cs ---- namespace redb.Route.Tests.Llm; public sealed class LlmEndpointOptionsTests { private static LlmEndpointOptions Bind(string uriStr) { var uri = EndpointUriParser.Parse(uriStr); var opts = new LlmEndpointOptions(); opts.BindFromUri(uri.RawParameters); return opts; } [Fact] public void Defaults_AreSet() { var opts = new LlmEndpointOptions(); opts.MaxIterations.Should().Be(8); opts.Conversation.Should().Be("none"); opts.Stream.Should().Be(LlmStreamMode.Off); } [Fact] public void BindFromUri_PullsTemperatureAndMaxTokens() { var opts = Bind("llm://c?temperature=0.3&maxTokens=512"); opts.Temperature.Should().Be(0.3); opts.MaxTokens.Should().Be(512); } [Fact] public void BindFromUri_PullsConversationAndStream() { var opts = Bind("llm://c?conversation=header&stream=calls"); opts.Conversation.Should().Be("header"); opts.Stream.Should().Be(LlmStreamMode.Calls); } [Fact] public void BindFromUri_PullsSystemPromptRef() { var opts = Bind("llm://c?systemPromptRef=translate-en"); opts.SystemPromptRef.Should().Be("translate-en"); } [Fact] public void BindFromUri_PullsMaxIterations() { var opts = Bind("llm://c?maxIterations=3"); opts.MaxIterations.Should().Be(3); } [Fact] public void Validate_NegativeIterations_Throws() { var opts = new LlmEndpointOptions { MaxIterations = 0 }; var act = () => opts.Validate(); act.Should().Throw(); } [Fact] public void Validate_TemperatureOutOfRange_Throws() { var opts = new LlmEndpointOptions { Temperature = 3.0 }; var act = () => opts.Validate(); act.Should().Throw(); } [Fact] public void Validate_ValidConfig_DoesNotThrow() { var opts = new LlmEndpointOptions { Temperature = 0.5, MaxIterations = 4 }; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void BindFromUri_PullsUser() { var opts = Bind("llm://c?user=system"); opts.User.Should().Be("system"); } [Fact] public void BindFromUri_PullsUserHeaderExpression() { var opts = Bind("llm://c?user=" + System.Web.HttpUtility.UrlEncode("${header.X-User-Id}")); opts.User.Should().Be("${header.X-User-Id}"); } [Fact] public void BindFromUri_PullsAuditCsv() { var opts = Bind("llm://c?audit=tier%3Dgold%2Cbucket%3DA"); opts.Audit.Should().Be("tier=gold,bucket=A"); } [Fact] public void BindFromUri_PullsPromptTemplateNameAndVersion() { var opts = Bind("llm://c?promptTemplateName=triage&promptTemplateVersion=v3"); opts.PromptTemplateName.Should().Be("triage"); opts.PromptTemplateVersion.Should().Be("v3"); } // The core binder leaves an unknown name, or a value that does not convert, among the unmapped // parameters, where nothing reads it: a typo used to drop the option without a word. [Fact] public void Validate_UnknownOption_IsRefused_WithTheNearestName() { // Refused while binding, in the core, before Validate runs. var act = () => Bind("llm://c?tempreature=0.2"); act.Should().Throw("a misspelt option would silently run with the default") .Which.Message.Should().Contain("tempreature").And.Contain("temperature", "the nearest option is named"); } [Fact] public void Validate_ValueThatDoesNotConvert_IsRefused() { var act = () => Bind("llm://c?maxIterations=abc"); act.Should().Throw("the option would silently keep its default") .Which.Message.Should().Contain("maxIterations").And.Contain("abc"); } [Fact] public void EveryDslOption_IsAnOptionTheEndpointKnows() { var uri = redb.Route.Llm.Fluent.Llm.Factory("c") .Temperature(0.2).MaxTokens(512).TopP(0.9) .SystemPromptRef("#sys").ConversationFromHeader().Stream(LlmStreamMode.Calls) .Schedule("30s").InitialBody("#first").MaxIterations(4) .Budget(inputTokens: 100, outputTokens: 50, costUsd: 0.5m).CacheSystemPrompt() .Tools("*").User("${header.userId}").Audit("tenant", "acme") .PropagateToolHeaders("x-tenant-id").PromptTemplate("triage", "v3") .AsUri() + "&redb=main&connectionFactory=c"; var opts = Bind(uri); opts.UnmappedParameters.Should().BeEmpty("every option the DSL writes is one the endpoint reads"); opts.Invoking(o => o.Validate()).Should().NotThrow(); } [Fact] public void Bind_StreamWithoutAMode_SaysWhatEachModeDoes() { var act = () => Bind("llm://c?stream=true"); act.Should().Throw() .Which.Message.Should().Contain("stream=calls").And.Contain("stream=body") .And.Contain("inside the route", "the connector says what each mode does, not only that it exists"); } [Fact] public void Bind_StreamNumberThatNamesNoMode_IsRefused() { // A number converts into any enum; 5 names no mode, and the binding refuses it. var act = () => Bind("llm://c?stream=5"); act.Should().Throw().Which.Message.Should().Contain("stream=5"); } } Path: redb-route/tests/redb.Route.Tests.Llm/LlmEndpointTests.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/LlmEndpointTests.cs ---- namespace redb.Route.Tests.Llm; public sealed class LlmEndpointTests { private static LlmEndpoint CreateEndpoint(string uriStr) { var component = new LlmComponent(); var uri = EndpointUriParser.Parse(uriStr); return (LlmEndpoint)component.CreateEndpoint(uri); } [Fact] public void ConnectionFactoryName_FromPath() { CreateEndpoint("llm://claude").ConnectionFactoryName.Should().Be("claude"); } [Fact] public void CreateProducer_ReturnsLlmProducer() { CreateEndpoint("llm://c").CreateProducer().Should().BeOfType(); } [Fact] public void CreateConsumer_ReturnsLlmConsumer() { var ep = CreateEndpoint("llm://c"); var processor = Substitute.For(); ep.CreateConsumer(processor).Should().BeOfType(); } [Fact] public void Uri_PreservesSchemeAndPath() { var ep = CreateEndpoint("llm://my-factory?temperature=0.1"); ep.Uri.Scheme.Should().Be("llm"); ep.Uri.Path.Should().Be("my-factory"); } [Fact] public void Component_IsLlmComponent() { CreateEndpoint("llm://c").Component.Should().BeOfType(); } [Fact] public void Statistics_AreInitialized() { var ep = CreateEndpoint("llm://c"); ep.MessagesIn.Should().Be(0); ep.MessagesOut.Should().Be(0); ep.Errors.Should().Be(0); ep.BytesIn.Should().Be(0); } } Path: redb-route/tests/redb.Route.Tests.Llm/LlmHttpTransportTests.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/LlmHttpTransportTests.cs ---- using System.Net; using System.Text; namespace redb.Route.Tests.Llm; /// /// Every model client of the package keeps a long silent call alive the same way: HTTP/2 when the server offers it, /// and a PING frame while the request is in flight. The client built by Create asks for HTTP/2, and every /// request carries the client's version: a hand-built request starts at HTTP/1.1, and then the pings never happen. /// public sealed class LlmHttpTransportTests { /// Records the HTTP version every request asked for and answers with a fixed body. private sealed class VersionRecordingHandler(string body, string mediaType = "application/json") : HttpMessageHandler { public List<(Version Version, HttpVersionPolicy Policy)> Requests { get; } = []; protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) { Requests.Add((request.Version, request.VersionPolicy)); return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body, Encoding.UTF8, mediaType) }); } } /// A caller's client that asks for HTTP/2, the way the package's own default client does. private static HttpClient Http2Client(HttpMessageHandler handler) => new(handler) { DefaultRequestVersion = HttpVersion.Version20, DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower }; private static LlmConnectionFactory Factory(string provider, string model) => new() { Provider = provider, ModelId = model, ApiKey = "sk-test", RequestTimeoutMs = 90_000 }; [Fact] public void OpenAi_DefaultClient_AsksForHttp2() { var provider = OpenAiProvider.Create(Factory("deepseek", "deepseek-flash")); provider.Http.DefaultRequestVersion.Should().Be(HttpVersion.Version20, "the keep-alive pings ride on HTTP/2 frames; a thinking model's call is minutes of silence"); provider.Http.DefaultVersionPolicy.Should().Be(HttpVersionPolicy.RequestVersionOrLower, "HTTP/1.1 stays the fallback"); provider.Http.Timeout.Should().Be(Timeout.InfiniteTimeSpan, "RequestTimeoutMs limits the whole call and is applied per call (RequestTimeoutTests)"); } [Fact] public async Task OpenAi_Request_CarriesTheClientsHttpVersion() { var handler = new VersionRecordingHandler("""{"choices":[{"message":{"role":"assistant","content":"done"}}]}"""); var provider = new OpenAiProvider(Factory("deepseek", "deepseek-flash"), Http2Client(handler)); await provider.CompleteAsync(new LlmRequest { Messages = [LlmMessage.User("hi")] }); var sent = handler.Requests.Should().ContainSingle().Subject; sent.Version.Should().Be(HttpVersion.Version20, "a hand-built request must carry the client's version"); sent.Policy.Should().Be(HttpVersionPolicy.RequestVersionOrLower); } [Fact] public async Task OpenAi_StreamRequest_CarriesTheClientsHttpVersion() { var handler = new VersionRecordingHandler( "data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n", "text/event-stream"); var provider = new OpenAiProvider(Factory("deepseek", "deepseek-flash"), Http2Client(handler)); await foreach (var _ in provider.StreamAsync(new LlmRequest { Messages = [LlmMessage.User("hi")] })) { } var sent = handler.Requests.Should().ContainSingle().Subject; sent.Version.Should().Be(HttpVersion.Version20, "the streaming request is hand-built too"); sent.Policy.Should().Be(HttpVersionPolicy.RequestVersionOrLower); } [Fact] public void Transcription_DefaultClient_AsksForHttp2() { var provider = OpenAiTranscriptionProvider.Create(Factory("openai", "whisper-1")); provider.Http.DefaultRequestVersion.Should().Be(HttpVersion.Version20, "a long recording is minutes of compute with nothing on the wire"); provider.Http.DefaultVersionPolicy.Should().Be(HttpVersionPolicy.RequestVersionOrLower, "HTTP/1.1 stays the fallback"); provider.Http.Timeout.Should().Be(Timeout.InfiniteTimeSpan, "RequestTimeoutMs limits the whole call and is applied per call (RequestTimeoutTests)"); } [Fact] public async Task Transcription_Request_CarriesTheClientsHttpVersion() { var handler = new VersionRecordingHandler("""{"text":"hi"}"""); var provider = new OpenAiTranscriptionProvider(Factory("openai", "whisper-1"), Http2Client(handler)); await provider.TranscribeAsync(new TranscriptionRequest(new byte[] { 0x4F, 0x67, 0x67, 0x53 }, "voice.oga", Language: "ru")); var sent = handler.Requests.Should().ContainSingle().Subject; sent.Version.Should().Be(HttpVersion.Version20, "a hand-built request must carry the client's version"); sent.Policy.Should().Be(HttpVersionPolicy.RequestVersionOrLower); } } Path: redb-route/tests/redb.Route.Tests.Llm/LlmIntegrationTests.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/LlmIntegrationTests.cs ---- using System.Diagnostics.Metrics; using OpenTelemetry; using OpenTelemetry.Metrics; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Observability; using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm; /// /// End-to-end pipeline tests using a scriptable . /// Verifies that LlmComponent → LlmEndpoint → LlmProducer → AgentEngine /// correctly forwards user content, dispatches tool calls through the producer /// template against a real direct: route, and emits the canonical /// metrics. Because the provider is scripted, these tests run without any /// network access or API keys. /// public sealed class LlmIntegrationTests { private static (RouteContext ctx, LlmProducer producer, LlmEndpoint endpoint, IProducerTemplate pt) BuildRoute(FakeProvider fake, string factoryName = "fake", string uri = "llm://fake") { var ctx = new RouteContext(); var component = new LlmComponent(); ctx.AddComponent(component); ctx.AddToRegistry(factoryName, new LlmConnectionFactory { Name = factoryName, Provider = "fake", ModelId = fake.ModelId, PrebuiltProvider = fake }); var pt = new ProducerTemplate(ctx); ctx.AddService(typeof(IProducerTemplate), pt); var engine = new AgentEngine( logger: null, producerTemplate: pt, observer: new NoopAgentObserver(), budget: new NoopBudgetEnforcer(), approval: new AutoApproveGate(), redaction: new NoopRedactionFilter(), shadow: new NoopShadowRunner(), conversation: null, idempotency: null, approvalStore: null); ctx.AddService(typeof(IAgentEngine), engine); var registry = new ToolDescriptorRegistry(); ctx.AddService(typeof(IToolDescriptorRegistry), registry); var endpoint = (LlmEndpoint)component.CreateEndpoint(EndpointUriParser.Parse(uri)); var producer = (LlmProducer)endpoint.CreateProducer(); return (ctx, producer, endpoint, pt); } [Fact] public async Task EndToEnd_StubProvider_RoundTrip() { var ctx = new RouteContext(); var component = new LlmComponent(); ctx.AddComponent(component); ctx.AddToRegistry("local", new LlmConnectionFactory { Name = "local", Provider = "stub", ModelId = "echo-1" }); ctx.AddService(typeof(IAgentEngine), new AgentEngine()); var endpoint = (LlmEndpoint)component.CreateEndpoint( EndpointUriParser.Parse(LlmDsl.Factory("local").Temperature(0.0).AsUri())); var producer = (LlmProducer)endpoint.CreateProducer(); await producer.Start(); var ex = new Exchange(new Message("translate this")); await producer.Process(ex); ex.Out!.Body.Should().Be("[stub] translate this"); ex.Out.Headers[LlmHeaders.ProviderId].Should().Be("stub"); ex.Out.Headers[LlmHeaders.ModelId].Should().Be("echo-1"); // Ownership audit: the connector keeps MessagesIn (a user turn arrived - no core wrapper // counts that for a producer); MessagesOut/Errors/Time belong to the core (ToProcessor on // a routed .To(), the ProducerTemplate for template sends). A bare producer.Process call // like this one therefore moves nothing into MessagesOut - and no longer double-counts // on the routed path the tsak dashboard actually watches. endpoint.MessagesIn.Should().Be(1); endpoint.MessagesOut.Should().Be(0); // The prompt goes out, the model's answer comes back in. Both used to compete for the one // byte counter, so the prompt sat in BytesIn and the answer was discarded. endpoint.BytesOut.Should().Be("translate this".Length); } [Fact] public async Task EndToEnd_ToolLoop_DispatchesViaProducerTemplate() { // Scripted provider asks for tool 'echo' once, then ends the turn with text. var fake = new FakeProvider() .EnqueueToolUse("echo", "{\"v\":1}") .EnqueueText("done"); // Set up everything via host helper so the tool route shares the registry. await using var host = LiveLlmHost.Build(); host.Context.AddToRegistry("fake", new LlmConnectionFactory { Name = "fake", Provider = "fake", ModelId = fake.ModelId, PrebuiltProvider = fake }); var echoTool = new EchoToolRoute( toolName: "echo", description: "echo back the result", inputSchema: """{"type":"object","properties":{"v":{"type":"number"}}}""", replyJson: """{"r":42}"""); await host.StartAsync(echoTool, r => { r.From("direct:agent") .To(LlmDsl.Factory("fake").Tools("echo").AsUri()) .To("mock:done"); }); var ex = await host.SendAsync("direct:agent", "go"); // After running through the route, the body has rotated into In on the next hop. var sink = host.Mock("mock:done"); sink.ReceivedCount.Should().Be(1); ((string)sink.ReceivedExchanges[0].In.Body!).Should().Be("done"); echoTool.CapturedInputs.Should().ContainSingle() .Which.Should().Contain("\"v\":1"); fake.CallCount.Should().Be(2); // The second LLM request must contain the tool_result that came back from the route. var followUp = fake.CapturedRequests[^1]; followUp.Messages.SelectMany(m => m.Content) .OfType() .Should().ContainSingle() .Which.OutputJson.Should().Contain("42"); } [Fact] public async Task EndToEnd_EmitsOpenTelemetryMetrics() { var exported = new List(); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter("redb.Route") .AddInMemoryExporter(exported) .Build(); var fake = new FakeProvider().EnqueueText("hi", tokensIn: 7, tokensOut: 11); var (_, producer, _, _) = BuildRoute(fake); await producer.Start(); await producer.Process(new Exchange(new Message("ping"))); meterProvider.ForceFlush(2000); exported.Should().Contain(m => m.Name == "redb.route.llm.calls"); exported.Should().Contain(m => m.Name == "redb.route.llm.agent.runs"); exported.Should().Contain(m => m.Name == "redb.route.llm.tokens.in"); exported.Should().Contain(m => m.Name == "redb.route.llm.tokens.out"); } [Fact] public async Task EndToEnd_ConversationFromHeader_PropagatesToRequest() { var fake = new FakeProvider().EnqueueText("ack"); var (_, producer, _, _) = BuildRoute(fake, uri: "llm://fake?conversation=header"); await producer.Start(); var msg = new Message("hello"); msg.Headers[LlmHeaders.ConversationId] = "conv-42"; await producer.Process(new Exchange(msg)); // ConversationId is forwarded to the agent request; persistence is opt-in (Phase 2). fake.CallCount.Should().Be(1); } } Path: redb-route/tests/redb.Route.Tests.Llm/LlmPreambleTests.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/LlmPreambleTests.cs ---- using redb.Route.Llm.Engine.Storage; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm; /// /// Producer-level coverage for the header: fixed opening /// messages open the transcript on every call, sit before the loaded history, and never reach /// the conversation store. Backed by — no DB required. /// public sealed class LlmPreambleTests { private const string Question = "Read it? Now, in your own words: do you accept?"; private const string Reply = "I accept — as a working rule, with the reservations named."; private static (LlmProducer producer, FakeProvider fake, InMemoryConversationStore store) Build() { var ctx = new RouteContext(); var component = new LlmComponent(); ctx.AddComponent(component); var fake = new FakeProvider(); ctx.AddToRegistry("fake", new LlmConnectionFactory { Name = "fake", Provider = "fake", ModelId = fake.ModelId, PrebuiltProvider = fake }); var store = new InMemoryConversationStore(); ctx.AddService(typeof(IAgentEngine), new AgentEngine( logger: null, producerTemplate: null, observer: null, budget: null, approval: null, redaction: null, shadow: null, conversation: store, idempotency: null, approvalStore: null)); var endpoint = (LlmEndpoint)component.CreateEndpoint( EndpointUriParser.Parse("llm://fake?conversation=header")); return ((LlmProducer)endpoint.CreateProducer(), fake, store); } private static IReadOnlyList Preamble() => [ LlmMessage.User(Question), new LlmMessage { Role = "assistant", Content = [new LlmTextBlock(Reply)], CacheBreakpoint = true } ]; private static async Task TurnAsync(LlmProducer producer, string text) { var msg = new Message(text); msg.Headers[LlmHeaders.ConversationId] = "c-test"; msg.Headers[LlmHeaders.Preamble] = Preamble(); await producer.Process(new Exchange(msg)); } private static string Text(LlmMessage m) => m.Content.OfType().First().Text; [Fact] public async Task Preamble_OpensTheTranscript_AndSitsBeforeTheLoadedHistory() { var (producer, fake, _) = Build(); fake.EnqueueText("first").EnqueueText("second"); await producer.Start(); await TurnAsync(producer, "hi"); await TurnAsync(producer, "again"); fake.CapturedRequests.Should().HaveCount(2); // Second call: preamble first, then the stored history, then the new turn. (The captured // list is the engine's live transcript, so the tail also carries the reply appended after // the call — the prefix is what this fact is about.) var seen = fake.CapturedRequests[1].Messages; seen.Take(5).Select(m => m.Role).Should().Equal("user", "assistant", "user", "assistant", "user"); Text(seen[0]).Should().Be(Question); Text(seen[1]).Should().Be(Reply); seen[1].CacheBreakpoint.Should().BeTrue("the breakpoint rides on the message into the provider"); Text(seen[2]).Should().Be("hi"); Text(seen[3]).Should().Be("first"); Text(seen[4]).Should().Be("again"); } [Fact] public async Task Preamble_IsNeverPersisted() { var (producer, fake, store) = Build(); fake.EnqueueText("ok"); await producer.Start(); await TurnAsync(producer, "hi"); // The store holds what was said in this dialog — one user turn, one reply — and nothing // of the fixed opening exchange. var rows = await store.LoadTreeAsync("c-test"); rows.Should().HaveCount(2); rows.Select(r => r.Message.Role).Should().Equal("user", "assistant"); rows.Select(r => Text(r.Message)).Should().NotContain(Question).And.NotContain(Reply); } [Fact] public async Task WithoutTheHeader_NothingChanges() { var (producer, fake, _) = Build(); fake.EnqueueText("ok"); await producer.Start(); var msg = new Message("hi"); msg.Headers[LlmHeaders.ConversationId] = "c-test"; await producer.Process(new Exchange(msg)); fake.CapturedRequests.Single().Messages[0].Role.Should().Be("user"); Text(fake.CapturedRequests.Single().Messages[0]).Should().Be("hi"); } } Path: redb-route/tests/redb.Route.Tests.Llm/LlmProducerTests.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/LlmProducerTests.cs ---- using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm; public sealed class LlmProducerTests { private static (RouteContext ctx, LlmEndpoint endpoint) Build( FakeProvider provider, string factoryName = "fake", string uri = "llm://fake", Action? configure = null) { var ctx = new RouteContext(); var component = new LlmComponent(); ctx.AddComponent(component); var factory = new LlmConnectionFactory { Name = factoryName, Provider = "fake", ModelId = provider.ModelId, PrebuiltProvider = provider }; configure?.Invoke(factory); ctx.AddToRegistry(factoryName, factory); ctx.AddService(typeof(IAgentEngine), new AgentEngine()); var endpoint = (LlmEndpoint)component.CreateEndpoint(EndpointUriParser.Parse(uri)); return (ctx, endpoint); } [Fact] public void Ctor_NullEndpoint_Throws() { var act = () => new LlmProducer(null!, new LlmEndpointOptions()); act.Should().Throw(); } [Fact] public void Ctor_NullOptions_Throws() { var (_, endpoint) = Build(new FakeProvider()); var act = () => new LlmProducer(endpoint, null!); act.Should().Throw(); } [Fact] public async Task Process_BeforeStart_Throws() { var (_, endpoint) = Build(new FakeProvider()); var producer = new LlmProducer(endpoint, new LlmEndpointOptions()); var act = () => producer.Process(new Exchange(new Message("hi"))); await act.Should().ThrowAsync().WithMessage("*not been started*"); } [Fact] public async Task Process_WritesAssistantTextAndHeaders() { var fake = new FakeProvider().EnqueueText("hello back", tokensIn: 3, tokensOut: 4); var (_, endpoint) = Build(fake); var producer = new LlmProducer(endpoint, new LlmEndpointOptions()); await producer.Start(); var exchange = new Exchange(new Message("hi")); await producer.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().Be("hello back"); exchange.Out.Headers[LlmHeaders.ProviderId].Should().Be("fake"); exchange.Out.Headers[LlmHeaders.ModelId].Should().Be("fake-model"); exchange.Out.Headers[LlmHeaders.TokensIn].Should().Be(3); exchange.Out.Headers[LlmHeaders.TokensOut].Should().Be(4); exchange.Out.Headers[LlmHeaders.ToolIterations].Should().Be(1); exchange.Out.Headers[LlmHeaders.StopReason].Should().Be(nameof(LlmStopReason.EndTurn)); } [Fact] public async Task Process_RecordsThePromptAsBytesOut() { var fake = new FakeProvider().EnqueueText("ok"); var (_, endpoint) = Build(fake); var producer = (LlmProducer)endpoint.CreateProducer(); await producer.Start(); var prompt = "abcdefghij"; // 10 bytes await producer.Process(new Exchange(new Message(prompt))); // The prompt LEAVES the endpoint. It was recorded as BytesIn while RecordBytesOut did not // exist — the one byte counter had to hold both directions. endpoint.BytesOut.Should().Be(prompt.Length); } [Fact] public async Task Process_CountsThePromptInUtf8Bytes() { var fake = new FakeProvider().EnqueueText("ok"); var (_, endpoint) = Build(fake); var producer = (LlmProducer)endpoint.CreateProducer(); await producer.Start(); var prompt = "привет"; // 6 UTF-16 chars, 12 UTF-8 bytes await producer.Process(new Exchange(new Message(prompt))); endpoint.BytesOut.Should().Be(12, "the counter is called Bytes, yet UTF-16 chars were counted"); } [Fact] public async Task Process_MissingFactory_Throws() { var ctx = new RouteContext(); var component = new LlmComponent(); ctx.AddComponent(component); ctx.AddService(typeof(IAgentEngine), new AgentEngine()); var endpoint = (LlmEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("llm://nope")); var producer = (LlmProducer)endpoint.CreateProducer(); await producer.Start(); var act = () => producer.Process(new Exchange(new Message("hi"))); await act.Should().ThrowAsync() .WithMessage("*nope*not registered*"); } [Fact] public async Task Process_MissingEngine_Throws() { var ctx = new RouteContext(); var component = new LlmComponent(); ctx.AddComponent(component); ctx.AddToRegistry("fake", new LlmConnectionFactory { Name = "fake", Provider = "stub", ModelId = "x" }); var endpoint = (LlmEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("llm://fake")); var producer = (LlmProducer)endpoint.CreateProducer(); await producer.Start(); var act = () => producer.Process(new Exchange(new Message("hi"))); await act.Should().ThrowAsync() .WithMessage("*IAgentEngine*"); } [Fact] public async Task Process_PassesSystemPromptFromHeader() { var fake = new FakeProvider().EnqueueText("ok"); var (_, endpoint) = Build(fake); var producer = (LlmProducer)endpoint.CreateProducer(); await producer.Start(); var msg = new Message("translate me"); msg.Headers[LlmHeaders.SystemPrompt] = "you are a translator"; await producer.Process(new Exchange(msg)); fake.CapturedRequests.Single().SystemPrompt.Should().Be("you are a translator"); } } Path: redb-route/tests/redb.Route.Tests.Llm/LlmScheduledOwnershipTests.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/LlmScheduledOwnershipTests.cs ---- using redb.Route.Abstractions; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm; /// /// Statistics ownership for the scheduled agent (From("llm://...?schedule=...")): /// the route pipeline is wrapped by the core's StatisticsProcessor, so the consumer must not /// self-record what the core already counts. It records only what the core cannot see — /// a tick that failed before the exchange reached the pipeline. /// public sealed class LlmScheduledOwnershipTests { [Fact] public async Task ScheduledTick_IsCountedByTheCore_NotByTheConsumer() { var fake = new FakeProvider().EnqueueText("tick!"); await using var host = LiveLlmHost.Build(); host.AddFactory("fake", new LlmConnectionFactory { Name = "fake", Provider = "fake", ModelId = fake.ModelId, PrebuiltProvider = fake }); const string uri = "llm://fake?schedule=200ms&initialBodyRef=go"; await host.StartAsync(r => r.From(uri).To("mock:llm-ticks")); var sink = host.Mock("mock:llm-ticks"); var deadline = DateTime.UtcNow.AddSeconds(10); while (sink.ReceivedCount == 0 && DateTime.UtcNow < deadline) await Task.Delay(50); sink.ReceivedCount.Should().BeGreaterThan(0, "at least one tick must reach the route"); var ep = (IEndpointStatistics)host.Context.GetEndpoint(uri); // The pipeline leg is the core's: MessagesIn per tick from StatisticsProcessor. ep.MessagesIn.Should().BeGreaterThan(0, "MessagesIn is written by StatisticsProcessor around From()"); // Nothing produces THROUGH the scheduled endpoint - self-recording a MessagesOut per // tick doubled the picture (core wrote its own success number on the same endpoint). ep.MessagesOut.Should().Be(0, "MessagesOut is a producer counter, a tick is not one"); ep.Errors.Should().Be(0, "successful ticks must bring no errors"); } [Fact] public async Task A_tick_whose_model_call_failed_is_recorded_with_its_text() { var fake = new FakeProvider { ThrowOnCall = new InvalidOperationException("model refused by the test") }; await using var host = LiveLlmHost.Build(); host.AddFactory("fake", new LlmConnectionFactory { Name = "fake", Provider = "fake", ModelId = fake.ModelId, PrebuiltProvider = fake }); const string uri = "llm://fake?schedule=200ms&initialBodyRef=go"; await host.StartAsync(r => r.From(uri).To("mock:llm-failed-ticks")); var ep = (IEndpointStatistics)host.Context.GetEndpoint(uri); var deadline = DateTime.UtcNow.AddSeconds(10); while (ep.Errors == 0 && DateTime.UtcNow < deadline) await Task.Delay(50); ep.Errors.Should().BeGreaterThan(0, "a tick that failed before the pipeline is the consumer's to count"); ep.LastErrorMessage.Should().Contain("model refused by the test"); } } Path: redb-route/tests/redb.Route.Tests.Llm/LlmServiceCollectionExtensionsTests.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/LlmServiceCollectionExtensionsTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Extensions; using redb.Route.Llm.Storage.Redb; namespace redb.Route.Tests.Llm; public sealed class LlmServiceCollectionExtensionsTests { [Fact] public void AddRedbRouteLlm_RegistersComponentEngineAndRegistry() { var services = new ServiceCollection(); var ctx = new RouteContext(); services.AddSingleton(ctx); services.AddRedbRouteLlm(); var sp = services.BuildServiceProvider(); sp.GetRequiredService().Should().BeOfType(); sp.GetRequiredService().Should().BeOfType(); // The startup hook RouteHostedService applies foreach (var configurator in sp.GetServices()) configurator.Configure(ctx); ctx.GetComponent("llm").Should().NotBeNull(); } [Fact] public void AddLlmConnectionFactory_RegistersFactoryByName() { var services = new ServiceCollection(); var ctx = new RouteContext(); services.AddSingleton(ctx); services.AddRedbRouteLlm(); services.AddLlmConnectionFactory("claude", f => { f.Provider = "stub"; f.ModelId = "haiku"; }); var sp = services.BuildServiceProvider(); foreach (var configurator in sp.GetServices()) configurator.Configure(ctx); var factory = ctx.GetFromRegistry("claude"); factory.Should().NotBeNull(); factory!.Name.Should().Be("claude"); factory.Provider.Should().Be("stub"); factory.ModelId.Should().Be("haiku"); } [Fact] public void AddLlmConnectionFactory_NameWinsOverConfigureOverride() { var services = new ServiceCollection(); var ctx = new RouteContext(); services.AddSingleton(ctx); services.AddRedbRouteLlm(); services.AddLlmConnectionFactory("registered-name", f => { f.Name = "evil-rename"; // user attempted override f.Provider = "stub"; }); var sp = services.BuildServiceProvider(); foreach (var configurator in sp.GetServices()) configurator.Configure(ctx); var factory = ctx.GetFromRegistry("registered-name"); factory.Should().NotBeNull(); factory!.Name.Should().Be("registered-name"); ctx.GetFromRegistry("evil-rename").Should().BeNull(); } [Fact] public void AddLlmConnectionFactory_NullName_Throws() { var services = new ServiceCollection(); var act = () => services.AddLlmConnectionFactory(null!, _ => { }); act.Should().Throw(); } [Fact] public void AddLlmConnectionFactory_NullConfigure_Throws() { var services = new ServiceCollection(); var act = () => services.AddLlmConnectionFactory("c", null!); act.Should().Throw(); } // ── The tool idempotency store: an in-memory default that any other registration replaces ── private static ServiceProvider Build(Action register) { var services = new ServiceCollection(); services.AddSingleton(new RouteContext()); register(services); return services.BuildServiceProvider(); } private sealed class HostStore : IToolIdempotencyStore { public Task TryReserveAsync(string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default) => Task.FromResult(ToolIdempotencyReservation.NewReservation); public Task CompleteAsync(string conversationId, string toolUseId, string outputJson, IExchange? exchange = null, CancellationToken ct = default) => Task.CompletedTask; public Task ReleaseAsync(string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default) => Task.CompletedTask; } [Fact] public async Task AddRedbRouteLlm_Alone_RegistersAnInMemoryToolIdempotencyStore_ThatDeduplicates() { await using var sp = Build(s => s.AddRedbRouteLlm()); var store = sp.GetRequiredService(); store.Should().BeOfType(); (await store.TryReserveAsync("conv", "tu-1")).IsNew.Should().BeTrue(); await store.CompleteAsync("conv", "tu-1", """{"sent":true}"""); var again = await store.TryReserveAsync("conv", "tu-1"); again.IsNew.Should().BeFalse("a repeated call with the same key gets the stored output"); again.CachedOutputJson.Should().Be("""{"sent":true}"""); } [Fact] public async Task AddRedbLlmStorage_Wins_WhenCalledAfterAddRedbRouteLlm() { await using var sp = Build(s => { s.AddRedbRouteLlm(); s.AddRedbLlmStorage(); }); sp.GetRequiredService().Should().BeOfType(); } [Fact] public async Task AddRedbLlmStorage_Wins_WhenCalledBeforeAddRedbRouteLlm() { await using var sp = Build(s => { s.AddRedbLlmStorage(); s.AddRedbRouteLlm(); }); sp.GetRequiredService().Should().BeOfType(); } [Fact] public async Task AHostsOwnStore_Wins_WhenRegisteredBeforeAddRedbRouteLlm() { await using var sp = Build(s => { s.AddSingleton(); s.AddRedbRouteLlm(); }); sp.GetRequiredService().Should().BeOfType(); } [Fact] public async Task AHostsOwnStore_Wins_WhenRegisteredAfterAddRedbRouteLlm() { await using var sp = Build(s => { s.AddRedbRouteLlm(); s.AddSingleton(); }); sp.GetRequiredService().Should().BeOfType(); } } Path: redb-route/tests/redb.Route.Tests.Llm/LlmTraceTests.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/LlmTraceTests.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Tests.Llm.TestHelpers; using redb.Route.Tests.Telemetry; namespace redb.Route.Tests.Llm; /// /// A scheduled agent opens a root span per tick, with the model call and the route under it, never a child of the /// activity that started the routes; a failed tick marks it red, our own stop does not. The model call of the producer /// is a transport span of its endpoint: it honours EnableTelemetry and a failed call marks it red. Stub providers /// only: no model is called. /// public sealed class LlmTraceTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10); private readonly string _factory = $"trace{Guid.NewGuid():N}"; private RouteTelemetryProbe Spans(ActivityKind kind) => new(a => a.Kind == kind && RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains(_factory, StringComparison.Ordinal) == true); private async Task Start(ILlmProvider provider, Action routes, bool telemetry = true) { var host = LiveLlmHost.Build(options: new RouteEngineOptions { EnableTelemetry = telemetry }); host.AddFactory(_factory, new LlmConnectionFactory { Name = _factory, Provider = "fake", ModelId = "fake-model", PrebuiltProvider = provider }); using (new Activity("host startup").SetIdFormat(ActivityIdFormat.W3C).Start()) await host.StartAsync(routes); return host; } private string Scheduled(string schedule = "100ms") => $"llm://{_factory}?schedule={schedule}&initialBodyRef=go"; private static async Task Until(Func done) { var deadline = DateTime.UtcNow + Wait; while (!done() && DateTime.UtcNow < deadline) await Task.Delay(50); } [Fact] public async Task Each_tick_opens_a_root_span_even_under_an_ambient_activity() { using var probe = Spans(ActivityKind.Consumer); await using (await Start(new FakeProvider(), r => r.From(Scheduled()).Process(_ => { }))) await Until(() => probe.Activities.Count >= 2); probe.Activities.Should().HaveCountGreaterThanOrEqualTo(2, "one span per tick"); probe.Activities.Should().OnlyContain(a => a.ParentSpanId == default(ActivitySpanId), "a tick starts a trace rather than joining the host's"); probe.Activities.Select(a => a.TraceId).Should().OnlyHaveUniqueItems(); probe.Activities.Should().OnlyContain(a => a.Status != ActivityStatusCode.Error); } [Fact] public async Task No_tick_opens_no_span() { using var probe = Spans(ActivityKind.Consumer); await using (await Start(new FakeProvider(), r => r.From(Scheduled("1h")).Process(_ => { }))) await Task.Delay(800); probe.Activities.Should().BeEmpty(); } [Fact] public async Task A_failed_route_marks_the_tick_span_red() { using var probe = Spans(ActivityKind.Consumer); await using (await Start(new FakeProvider(), r => r.From(Scheduled()).Process(_ => throw new InvalidOperationException("route failed")))) await Until(() => probe.Activities.Count >= 1); probe.Activities.Should().NotBeEmpty(); probe.Activities.Should().OnlyContain(a => a.Status == ActivityStatusCode.Error); } [Fact] public async Task A_failed_model_call_marks_the_tick_span_red() { using var probe = Spans(ActivityKind.Consumer); var provider = new FakeProvider { ThrowOnCall = new HttpRequestException("model unavailable") }; await using (await Start(provider, r => r.From(Scheduled()).Process(_ => { }))) await Until(() => probe.Activities.Count >= 1); probe.Activities.Should().NotBeEmpty(); probe.Activities.Should().OnlyContain(a => a.Status == ActivityStatusCode.Error); } [Fact] public async Task Our_stop_cancelling_the_tick_does_not_mark_the_span() { using var probe = Spans(ActivityKind.Consumer); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var provider = new FakeProvider { OnCall = async (_, ct) => { entered.TrySetResult(); await Task.Delay(Timeout.Infinite, ct); }, }; await using (await Start(provider, r => r.From(Scheduled()).Process(_ => { }))) { (await Task.WhenAny(entered.Task, Task.Delay(Wait))).Should().Be(entered.Task); } probe.Activities.Should().ContainSingle().Which.Status.Should().NotBe(ActivityStatusCode.Error, "our own stop cancelling the tick is not a failure"); } [Fact] public async Task The_model_call_is_a_span_of_its_endpoint() { using var probe = Spans(ActivityKind.Client); await using var host = await Start(new FakeProvider().EnqueueText("hi"), r => r.From("direct:agent").To($"llm://{_factory}")); await host.ProducerTemplate.SendAsync("direct:agent", "hello"); var span = probe.Activities.Should().ContainSingle().Subject; span.Status.Should().NotBe(ActivityStatusCode.Error); RouteTelemetryProbe.Tag(span, "llm.provider").Should().Be("fake"); } [Fact] public async Task A_failed_model_call_marks_the_producer_span_red() { using var probe = Spans(ActivityKind.Client); var provider = new FakeProvider { ThrowOnCall = new HttpRequestException("model unavailable") }; await using var host = await Start(provider, r => r.From("direct:agent").To($"llm://{_factory}")); var send = () => host.ProducerTemplate.SendAsync("direct:agent", "hello"); await send.Should().ThrowAsync(); probe.Activities.Should().ContainSingle().Which.Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task A_failed_streamed_run_marks_the_stream_span_red() { using var probe = Spans(ActivityKind.Client); var provider = new StreamingFakeProvider(new FakeProvider { ThrowOnCall = new HttpRequestException("model unavailable") }); await using var host = await Start(provider, r => r.From("direct:agent").To($"llm://{_factory}?stream=body")); var exchange = await host.ProducerTemplate.RequestAsync("direct:agent", new Exchange(new Message("hello"))); var body = (IAsyncEnumerable)exchange.Out!.Body!; var read = async () => { await foreach (var _ in body) { } }; await read.Should().ThrowAsync(); probe.Activities.Should().ContainSingle().Which.Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task Tracing_off_opens_no_span_on_either_side() { using var probe = new RouteTelemetryProbe(a => RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains(_factory, StringComparison.Ordinal) == true || RouteTelemetryProbe.Tag(a, "llm.provider") == "fake-off"); var ticked = new TaskCompletionSource(); var provider = new FakeProvider(); var host = LiveLlmHost.Build(options: new RouteEngineOptions { EnableTelemetry = false }); host.AddFactory(_factory, new LlmConnectionFactory { Name = _factory, Provider = "fake-off", ModelId = "fake-model", PrebuiltProvider = provider }); await using (host) { await host.StartAsync(r => { r.From(Scheduled()).Process(_ => ticked.TrySetResult()); r.From("direct:agent").To($"llm://{_factory}"); }); (await Task.WhenAny(ticked.Task, Task.Delay(Wait))).Should().Be(ticked.Task); await host.ProducerTemplate.SendAsync("direct:agent", "hello"); } probe.Activities.Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.Llm/OpenAiBaseUrlTests.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/OpenAiBaseUrlTests.cs ---- using redb.Route.Llm.Providers; namespace redb.Route.Tests.Llm; /// /// Default base URLs are contracts with other people's servers, so the divergent one is pinned. /// DeepSeek's documented base is the ROOT — unlike every /v1 neighbour in the table — verified /// 2026-09-10 against api-docs.deepseek.com after the V4.1-Flash release: /v1 still answers as a /// legacy alias (401, not 404) but vanished from the docs, so the canonical form is the durable /// one. If a future edit "harmonises" it back to /v1, this test is the tripwire. /// public sealed class OpenAiBaseUrlTests { [Fact] public void DeepSeek_base_is_the_documented_root_not_v1() { OpenAiProvider.ResolveDefaultBaseUrl("deepseek") .Should().Be(new Uri("https://api.deepseek.com/")); } [Fact] public void The_v1_neighbours_stay_on_v1() { OpenAiProvider.ResolveDefaultBaseUrl("openai").Should().Be(new Uri("https://api.openai.com/v1/")); OpenAiProvider.ResolveDefaultBaseUrl("mistral").Should().Be(new Uri("https://api.mistral.ai/v1/")); } } Path: redb-route/tests/redb.Route.Tests.Llm/OpenAiProviderRequestTests.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/OpenAiProviderRequestTests.cs ---- using System.Net; using System.Text.Json.Nodes; namespace redb.Route.Tests.Llm; /// /// Verifies the OpenAI-compatible request/response shape for reasoning models: DeepSeek returns its /// chain of thought in reasoning_content, and the contract asks for that field back on the /// assistant message that carries the tool call — which is the only place the field belongs. /// public sealed class OpenAiProviderRequestTests { /// Captures the body of every request and answers with the scripted body per call. private sealed class ScriptedHandler : HttpMessageHandler { private readonly string[] _bodies; private int _calls; public ScriptedHandler(params string[] bodies) => _bodies = bodies; public List Bodies { get; } = []; protected override async Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { Bodies.Add(JsonNode.Parse(await request.Content!.ReadAsStringAsync(cancellationToken))!.AsObject()); var body = _bodies[Math.Min(_calls++, _bodies.Length - 1)]; return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body) }; } } /// A thinking model that asks for a tool: content is null, the reasoning is beside it. private const string ToolCallReply = """ {"id":"chatcmpl_1","choices":[{"index":0,"message":{ "role":"assistant","content":null, "reasoning_content":"the user asks about order 42; call the tool", "tool_calls":[{"id":"call_1","type":"function", "function":{"name":"order_lookup","arguments":"{\"orderId\":\"42\"}"}}]}, "finish_reason":"tool_calls"}], "usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}} """; private static LlmToolCapability LookupTool() => new() { Name = "order_lookup", Description = "Look up an order by id.", InputSchema = """{"type":"object","properties":{"orderId":{"type":"string"}},"required":["orderId"]}""" }; private static OpenAiProvider Provider(HttpMessageHandler handler) => new(new LlmConnectionFactory { Provider = "deepseek", ModelId = "deepseek-flash", ApiKey = "test-key" }, new HttpClient(handler)); [Fact] public async Task DeepSeek_ToolLoop_SecondRequest_CarriesReasoningContent() { var handler = new ScriptedHandler(ToolCallReply); var provider = Provider(handler); var first = await provider.CompleteAsync(new LlmRequest { Messages = [LlmMessage.User("what is the status of order 42?")], Tools = [LookupTool()] }); var thinking = first.Content.OfType().Should().ContainSingle( "reasoning_content is a block of its own, not the answer").Which; thinking.Text.Should().Be("the user asks about order 42; call the tool"); thinking.Signature.Should().BeNull("DeepSeek signs nothing: the text is the whole payload"); // Second iteration of the loop: the assistant turn goes back with the reasoning it produced. await provider.CompleteAsync(new LlmRequest { Messages = [ LlmMessage.User("what is the status of order 42?"), new LlmMessage { Role = "assistant", Content = first.Content }, new LlmMessage { Role = "user", Content = [new LlmToolResultBlock("call_1", """{"status":"shipped"}""")] } ], Tools = [LookupTool()] }); var assistant = handler.Bodies[1]["messages"]!.AsArray()[1]!.AsObject(); assistant["reasoning_content"]!.GetValue() .Should().Be("the user asks about order 42; call the tool"); assistant["tool_calls"]!.AsArray().Should().HaveCount(1, "the tool call travels with its reasoning"); } [Fact] public async Task DeepSeek_WithoutTools_ReasoningIsNotSent() { var handler = new ScriptedHandler("""{"choices":[{"message":{"role":"assistant","content":"done"}}]}"""); await Provider(handler).CompleteAsync(new LlmRequest { Messages = [ LlmMessage.User("hi"), new LlmMessage { Role = "assistant", Content = [new LlmThinkingBlock("the user greets me"), new LlmTextBlock("done")] } ] }); // Decision 19: with no tools in play the field is not part of the contract, so it stays home. handler.Bodies[0]["messages"]!.AsArray()[1]!.AsObject().ContainsKey("reasoning_content") .Should().BeFalse("reasoning_content goes back only where tools are declared"); } [Theory] [InlineData(true)] [InlineData(false)] public async Task MessageWithNothingToSay_IsNotSent(bool withTools) { // An assistant turn with no text and no tool call (the model spent the turn thinking, or answered // with an empty string) used to go out as {"role":"assistant","content":null}. Content may be // null only beside tool_calls, so that message is a refusal waiting in every later request of the // conversation. The turn stays in the record; it is not sent. var handler = new ScriptedHandler("""{"choices":[{"message":{"role":"assistant","content":"done"}}]}"""); await Provider(handler).CompleteAsync(new LlmRequest { Messages = [ LlmMessage.User("status of order 42?"), new LlmMessage { Role = "assistant", Content = [new LlmThinkingBlock("ran out of tokens")] }, LlmMessage.User("and now?"), new LlmMessage { Role = "assistant", Content = [new LlmTextBlock(string.Empty)] }, LlmMessage.User("still there?") ], Tools = withTools ? [LookupTool()] : [] }); var messages = handler.Bodies[0]["messages"]!.AsArray(); messages.Count.Should().Be(3, "the two turns that say nothing are not sent"); messages.Should().OnlyContain(m => m!["role"]!.GetValue() == "user"); messages.Should().OnlyContain(m => m!["content"] != null, "no message goes out with null content"); } [Fact] public async Task DeepSeek_VisibleAnswer_IsTheContent_NotTheReasoning() { var handler = new ScriptedHandler( """ {"id":"chatcmpl_2","choices":[{"index":0,"message":{ "role":"assistant","content":"shipped", "reasoning_content":"the tool said shipped, so the answer is shipped"}, "finish_reason":"stop"}], "usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}} """); var response = await Provider(handler).CompleteAsync(new LlmRequest { Messages = [LlmMessage.User("status of order 42?")] }); response.Content.OfType().Should().ContainSingle().Which.Text.Should().Be("shipped"); response.Content.OfType().Should().ContainSingle(); } } Path: redb-route/tests/redb.Route.Tests.Llm/PromptCacheUsageTests.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/PromptCacheUsageTests.cs ---- using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Observability; using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm; /// /// Prompt-cache accounting: what the provider reported has to survive the tool loop and reach the /// exchange, or nobody can tell a working cache from an expensive prompt. /// /// Why this class exists. The flag and the two counters shipped /// first; the engine, meanwhile, rebuilt its final usage as new LlmUsage(in, out) and /// dropped both — summed per iteration, then thrown away. Nothing downstream could observe the /// cache at all, so "caching works" was unfalsifiable by construction. These facts pin the whole /// path: provider → engine → producer → headers. /// public sealed class PromptCacheUsageTests(Xunit.Abstractions.ITestOutputHelper output) { private readonly Xunit.Abstractions.ITestOutputHelper _output = output; private static (RouteContext ctx, LlmProducer producer) BuildRoute(FakeProvider fake, string uri) { var ctx = new RouteContext(); var component = new LlmComponent(); ctx.AddComponent(component); ctx.AddToRegistry("fake", new LlmConnectionFactory { Name = "fake", Provider = "fake", ModelId = fake.ModelId, PrebuiltProvider = fake }); var pt = new ProducerTemplate(ctx); ctx.AddService(typeof(IProducerTemplate), pt); ctx.AddService(typeof(IAgentEngine), new AgentEngine( logger: null, producerTemplate: pt, observer: new NoopAgentObserver(), budget: new NoopBudgetEnforcer(), approval: new AutoApproveGate(), redaction: new NoopRedactionFilter(), shadow: new NoopShadowRunner(), conversation: null, idempotency: null, approvalStore: null)); ctx.AddService(typeof(IToolDescriptorRegistry), new ToolDescriptorRegistry()); var endpoint = (LlmEndpoint)component.CreateEndpoint(EndpointUriParser.Parse(uri)); return (ctx, (LlmProducer)endpoint.CreateProducer()); } private static LlmResponse Answer(string text, int input, int output, int cacheWrite, int cacheRead) => new() { Content = [new LlmTextBlock(text)], StopReason = LlmStopReason.EndTurn, Usage = new LlmUsage(input, output, cacheWrite, cacheRead) }; /// /// The two cache counters reach the exchange as headers — the only place a route can read them. /// [Fact] public async Task Cache_counters_reach_the_exchange_headers() { var fake = new FakeProvider().Enqueue(Answer("ok", input: 40, output: 7, cacheWrite: 0, cacheRead: 9000)); var (_, producer) = BuildRoute(fake, LlmDsl.Factory("fake").CacheSystemPrompt().AsUri()); await producer.Start(); var ex = new Exchange(new Message("привет")); await producer.Process(ex); ex.Out!.Headers[LlmHeaders.CacheReadTokens].Should().Be(9000); ex.Out.Headers[LlmHeaders.CacheWriteTokens].Should().Be(0); // ⚠️ And input stays the UNCACHED remainder, not the whole prompt. Reading it as "the // prompt got cheap" is the mistake these headers exist to prevent. ex.Out.Headers[LlmHeaders.TokensIn].Should().Be(40); } /// /// ⚠️ The counters are summed across the tool loop, not taken from the last call. The /// first iteration of a cached run pays the write, later ones read; keeping only the last /// would report the write as zero and understate what the run actually cost. /// [Fact] public async Task Cache_counters_are_summed_over_every_iteration() { var fake = new FakeProvider() .Enqueue(new LlmResponse { Content = [new LlmToolUseBlock("tu_1", "echo", "{}")], StopReason = LlmStopReason.ToolUse, Usage = new LlmUsage(10, 2, CacheCreationInputTokens: 9000, CacheReadInputTokens: 0) }) .Enqueue(Answer("done", input: 12, output: 3, cacheWrite: 0, cacheRead: 9000)); await using var host = LiveLlmHost.Build(); host.Context.AddToRegistry("fake", new LlmConnectionFactory { Name = "fake", Provider = "fake", ModelId = fake.ModelId, PrebuiltProvider = fake }); var echoTool = new EchoToolRoute( toolName: "echo", description: "echo", inputSchema: """{"type":"object"}""", replyJson: """{"r":1}"""); await host.StartAsync(echoTool, r => { r.From("direct:agent") .To(LlmDsl.Factory("fake").Tools("echo").CacheSystemPrompt().AsUri()) .To("mock:done"); }); await host.SendAsync("direct:agent", "go"); // Read at the route's receiver, not at the Out of the original exchange: after the next step the body and // headers have already turned over into In (the same approach as the neighbouring EndToEnd_ToolLoop). var headers = host.Mock("mock:done").ReceivedExchanges[0].In.Headers; headers[LlmHeaders.CacheWriteTokens].Should().Be(9000); headers[LlmHeaders.CacheReadTokens].Should().Be(9000); headers[LlmHeaders.TokensIn].Should().Be(22); } /// /// Headers appear even when nothing was cached — zeros included. A missing header is /// indistinguishable from an older engine that never reported one; a zero is an answer. /// [Fact] public async Task Headers_are_written_even_when_nothing_was_cached() { var fake = new FakeProvider().Enqueue(Answer("ok", input: 100, output: 5, cacheWrite: 0, cacheRead: 0)); var (_, producer) = BuildRoute(fake, LlmDsl.Factory("fake").AsUri()); await producer.Start(); var ex = new Exchange(new Message("привет")); await producer.Process(ex); ex.Out!.Headers.Should().ContainKey(LlmHeaders.CacheReadTokens); ex.Out.Headers[LlmHeaders.CacheReadTokens].Should().Be(0); ex.Out.Headers[LlmHeaders.CacheWriteTokens].Should().Be(0); } /// /// ⚠️ The only fact here that proves the cache actually WORKS. Everything above shows /// that numbers travel; a fake provider can report whatever it likes. Whether Anthropic really /// re-reads the prefix is answerable only against the live API. /// /// Two calls, byte-identical system prompt, same tools: the first pays the write, the /// second reads. Skipped without REDB_LLM_ANTHROPIC_KEY, so CI stays green and free. /// /// The prompt is padded past the model's minimum cacheable prefix on purpose — below it /// nothing is cached and no error is raised, which is the failure mode easiest to mistake for /// "the feature does not work". /// [Trait("Category", "LiveLlm")] [EnvFact("REDB_LLM_ANTHROPIC_KEY")] public async Task Live_anthropic_reads_the_system_prompt_back_from_cache() { var factory = new LlmConnectionFactory { Name = "anthropic", Provider = "anthropic", ModelId = Environment.GetEnvironmentVariable("REDB_LLM_ANTHROPIC_MODEL") ?? "claude-haiku-4-5-20251001", ApiKey = Environment.GetEnvironmentVariable("REDB_LLM_ANTHROPIC_KEY"), Temperature = 0.0, MaxTokens = 32 }; using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(60) }; var provider = new AnthropicProvider(factory, http); // Long, constant, and identical on both calls — that is the whole contract. var system = string.Join("\n", Enumerable.Range(0, 400).Select(i => $"Правило {i}. Отвечай коротко и по существу, не выдумывай фактов и не пересказывай инструкцию.")); LlmRequest Ask(string question) => new() { SystemPrompt = system, CacheSystemPrompt = true, Messages = [LlmMessage.User(question)], Temperature = 0.0, MaxTokens = 32 }; var first = await provider.CompleteAsync(Ask("Скажи слово «раз».")); var second = await provider.CompleteAsync(Ask("Скажи слово «два».")); _output.WriteLine($"model : {factory.ModelId}"); _output.WriteLine($"call 1 : in={first.Usage.InputTokens} " + $"cacheWrite={first.Usage.CacheCreationInputTokens} " + $"cacheRead={first.Usage.CacheReadInputTokens}"); _output.WriteLine($"call 2 : in={second.Usage.InputTokens} " + $"cacheWrite={second.Usage.CacheCreationInputTokens} " + $"cacheRead={second.Usage.CacheReadInputTokens}"); // First call writes the prefix. Zero here means the prompt is below the model's floor — // a different failure from "the cache is not read", and worth telling apart. (first.Usage.CacheCreationInputTokens + first.Usage.CacheReadInputTokens) .Should().BeGreaterThan(0, "the system prompt never reached the provider's cache at all"); // Second call reads it back. THIS is the number the docs point at. second.Usage.CacheReadInputTokens .Should().BeGreaterThan(0, "the prefix was not re-read — something in it is not byte-stable"); // And input stays the uncached remainder: it must be far smaller than what was read. second.Usage.InputTokens.Should().BeLessThan(second.Usage.CacheReadInputTokens); } } Path: redb-route/tests/redb.Route.Tests.Llm/ProviderStreamParityTests.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/ProviderStreamParityTests.cs ---- using System.Net; using System.Text; namespace redb.Route.Tests.Llm; /// /// A streamed call assembles exactly the answer a non-streaming call returns for it: the same blocks in the same order /// (thinking with its signature, text, tool calls), the same usage, stop reason, raw stop reason and response id. The /// agent engine runs its loop, its store and the hand-back of thinking on that answer, so the two forms must not /// differ. Each test serves one answer twice, as the JSON of a plain call and as the SSE of a streamed one. /// public sealed class ProviderStreamParityTests { private sealed class FixedHandler(string body, string mediaType) : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body, Encoding.UTF8, mediaType) }); } private static HttpClient Serving(string body, string mediaType) => new(new FixedHandler(body, mediaType)); private static LlmConnectionFactory Factory(string provider, string model) => new() { Provider = provider, ModelId = model, ApiKey = "sk-test" }; private static LlmRequest Request() => new() { Messages = [LlmMessage.User("hi")] }; /// SSE lines joined the way a server writes them. private static string Sse(params string[] lines) => string.Join("\n", lines) + "\n"; private static async Task> DrainAsync(ILlmProvider provider) { var chunks = new List(); await foreach (var chunk in provider.StreamAsync(Request())) chunks.Add(chunk); return chunks; } private static void ShouldBeTheSameAnswer(LlmResponse? streamed, LlmResponse plain) { streamed.Should().NotBeNull("the last chunk carries the assembled answer"); streamed!.Content.Should().Equal(plain.Content, "blocks, their order and their payloads match the plain call"); streamed.StopReason.Should().Be(plain.StopReason); streamed.RawStopReason.Should().Be(plain.RawStopReason); streamed.Usage.Should().Be(plain.Usage); streamed.ProviderResponseId.Should().Be(plain.ProviderResponseId); streamed.ProviderSystemFingerprint.Should().Be(plain.ProviderSystemFingerprint); } // ── OpenAI-compatible (DeepSeek shape: reasoning_content beside the answer) ── private const string DeepSeekJson = """ {"id":"chatcmpl-1","system_fingerprint":"fp_1","choices":[{"index":0,"message":{"role":"assistant","content":"Hello world","reasoning_content":"Let me think.","tool_calls":[{"id":"call_1","type":"function","function":{"name":"lookup","arguments":"{\"q\":\"x\"}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":10,"completion_tokens":5}} """; private static readonly string DeepSeekSse = Sse( """data: {"id":"chatcmpl-1","system_fingerprint":"fp_1","choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":"Let me "}}]}""", "", ": keep-alive", "", """data: {"id":"chatcmpl-1","system_fingerprint":"fp_1","choices":[{"index":0,"delta":{"reasoning_content":"think."}}]}""", "", """data: {"id":"chatcmpl-1","system_fingerprint":"fp_1","choices":[{"index":0,"delta":{"content":"Hello "}}]}""", "", """data: {"id":"chatcmpl-1","system_fingerprint":"fp_1","choices":[{"index":0,"delta":{"content":"world"}}]}""", "", """data: {"id":"chatcmpl-1","system_fingerprint":"fp_1","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"lookup","arguments":"{\"q\""}}]}}]}""", "", """data: {"id":"chatcmpl-1","system_fingerprint":"fp_1","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":":\"x\"}"}}]}}]}""", "", """data: {"id":"chatcmpl-1","system_fingerprint":"fp_1","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}""", "", """data: {"id":"chatcmpl-1","choices":[],"usage":{"prompt_tokens":10,"completion_tokens":5}}""", "", "data: [DONE]"); [Fact] public async Task OpenAi_Stream_AssemblesTheSameAnswerAsAPlainCall() { var plain = await new OpenAiProvider(Factory("deepseek", "deepseek-flash"), Serving(DeepSeekJson, "application/json")) .CompleteAsync(Request()); var chunks = await DrainAsync( new OpenAiProvider(Factory("deepseek", "deepseek-flash"), Serving(DeepSeekSse, "text/event-stream"))); plain.Content.OfType().Should().ContainSingle("the fixture carries reasoning_content"); ShouldBeTheSameAnswer(chunks[^1].Response, plain); } [Fact] public async Task OpenAi_Stream_PiecesArriveAsTheyCome_ThinkingApartFromText() { var chunks = await DrainAsync( new OpenAiProvider(Factory("deepseek", "deepseek-flash"), Serving(DeepSeekSse, "text/event-stream"))); var pieces = chunks.Take(chunks.Count - 1).SelectMany(c => c.Content).ToList(); pieces.OfType().Select(t => t.Text).Should().Equal("Hello ", "world"); pieces.OfType().Select(t => t.Text).Should().Equal( ["Let me ", "think."], "the thinking is a piece of its own kind, never visible text"); } [Fact] public async Task OpenAi_Stream_MalformedFrame_Fails() { var sse = Sse("""data: {"id":"chatcmpl-1","choices":[{"index":0,"delta":{"content":"Hel""", "", "data: [DONE]"); var thrown = await Record.ExceptionAsync(() => DrainAsync( new OpenAiProvider(Factory("deepseek", "deepseek-flash"), Serving(sse, "text/event-stream")))); thrown.Should().NotBeNull("a frame that cannot be read is lost text; skipping it would hand on a shorter answer as whole"); thrown!.Message.Should().Contain("\"content\":\"Hel", "the message shows the frame"); } [Fact] public async Task OpenAi_Stream_ErrorFrame_Fails() { var sse = Sse("""data: {"error":{"message":"the model is overloaded","type":"server_error"}}""", "", "data: [DONE]"); var thrown = await Record.ExceptionAsync(() => DrainAsync( new OpenAiProvider(Factory("deepseek", "deepseek-flash"), Serving(sse, "text/event-stream")))); thrown.Should().NotBeNull("an error reported inside the stream is a failed call, not an empty answer"); thrown!.Message.Should().Contain("the model is overloaded"); } [Fact] public async Task OpenAi_Stream_EndingWithoutFinishReason_Fails() { var sse = Sse( """data: {"id":"chatcmpl-1","choices":[{"index":0,"delta":{"content":"Hello"}}]}""", "", "data: [DONE]"); var thrown = await Record.ExceptionAsync(() => DrainAsync( new OpenAiProvider(Factory("deepseek", "deepseek-flash"), Serving(sse, "text/event-stream")))); thrown.Should().BeOfType( "a stream that ended before the model said why it stopped is a cut answer, not a finished one"); } // ── Anthropic ── private const string AnthropicJson = """ {"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-4-8","content":[{"type":"thinking","thinking":"Let me think.","signature":"sig-abc"},{"type":"redacted_thinking","data":"opaque=="},{"type":"text","text":"Hello world"},{"type":"tool_use","id":"toolu_1","name":"lookup","input":{"q":"x"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":5,"cache_creation_input_tokens":3,"cache_read_input_tokens":7}} """; private static readonly string AnthropicSse = Sse( "event: message_start", """data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-4-8","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":1,"cache_creation_input_tokens":3,"cache_read_input_tokens":7}}}""", "", "event: content_block_start", """data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}}""", "", "event: content_block_delta", """data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"Let me "}}""", "", "event: content_block_delta", """data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"think."}}""", "", "event: content_block_delta", """data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig-abc"}}""", "", "event: content_block_stop", """data: {"type":"content_block_stop","index":0}""", "", "event: content_block_start", """data: {"type":"content_block_start","index":1,"content_block":{"type":"redacted_thinking","data":"opaque=="}}""", "", "event: content_block_stop", """data: {"type":"content_block_stop","index":1}""", "", "event: content_block_start", """data: {"type":"content_block_start","index":2,"content_block":{"type":"text","text":""}}""", "", "event: content_block_delta", """data: {"type":"content_block_delta","index":2,"delta":{"type":"text_delta","text":"Hello "}}""", "", "event: ping", """data: {"type":"ping"}""", "", "event: content_block_delta", """data: {"type":"content_block_delta","index":2,"delta":{"type":"text_delta","text":"world"}}""", "", "event: content_block_stop", """data: {"type":"content_block_stop","index":2}""", "", "event: content_block_start", """data: {"type":"content_block_start","index":3,"content_block":{"type":"tool_use","id":"toolu_1","name":"lookup","input":{}}}""", "", "event: content_block_delta", """data: {"type":"content_block_delta","index":3,"delta":{"type":"input_json_delta","partial_json":"{\"q\":"}}""", "", "event: content_block_delta", """data: {"type":"content_block_delta","index":3,"delta":{"type":"input_json_delta","partial_json":"\"x\"}"}}""", "", "event: content_block_stop", """data: {"type":"content_block_stop","index":3}""", "", "event: message_delta", """data: {"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":5}}""", "", "event: message_stop", """data: {"type":"message_stop"}"""); [Fact] public async Task Anthropic_Stream_AssemblesTheSameAnswerAsAPlainCall() { var plain = await new AnthropicProvider(Factory("anthropic", "claude-opus-4-8"), Serving(AnthropicJson, "application/json")) .CompleteAsync(Request()); var chunks = await DrainAsync( new AnthropicProvider(Factory("anthropic", "claude-opus-4-8"), Serving(AnthropicSse, "text/event-stream"))); plain.Content.OfType().Should().HaveCount(2, "the fixture carries a signed and a redacted thinking block"); ShouldBeTheSameAnswer(chunks[^1].Response, plain); } [Fact] public async Task Anthropic_Stream_PiecesArriveAsTheyCome_ThinkingApartFromText() { var chunks = await DrainAsync( new AnthropicProvider(Factory("anthropic", "claude-opus-4-8"), Serving(AnthropicSse, "text/event-stream"))); var pieces = chunks.Take(chunks.Count - 1).SelectMany(c => c.Content).ToList(); pieces.OfType().Select(t => t.Text).Should().Equal("Hello ", "world"); pieces.OfType().Select(t => t.Text).Should().Equal( ["Let me ", "think."], "the thinking is a piece of its own kind, never visible text"); } [Fact] public async Task Anthropic_Stream_MalformedFrame_Fails() { var sse = Sse( "event: message_start", """data: {"type":"message_start","message":{"id":"msg_1","usage":{"input_tokens":1,"output_tokens":1"""); var thrown = await Record.ExceptionAsync(() => DrainAsync( new AnthropicProvider(Factory("anthropic", "claude-opus-4-8"), Serving(sse, "text/event-stream")))); thrown.Should().NotBeNull("a frame that cannot be read must not be skipped"); thrown!.Message.Should().Contain("\"message_start\"", "the message shows the frame"); } [Fact] public async Task Anthropic_Stream_EndingWithoutStopReason_Fails() { var sse = Sse( "event: message_start", """data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"usage":{"input_tokens":1,"output_tokens":1}}}""", "", "event: content_block_start", """data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}""", "", "event: content_block_delta", """data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}"""); var thrown = await Record.ExceptionAsync(() => DrainAsync( new AnthropicProvider(Factory("anthropic", "claude-opus-4-8"), Serving(sse, "text/event-stream")))); thrown.Should().BeOfType( "a stream that ended before the model said why it stopped is a cut answer, not a finished one"); } // ── Providers without a stream of their own ── /// Implements only the plain call; streaming comes from the interface's default. private sealed class PlainOnlyProvider(LlmResponse response) : ILlmProvider { public string ProviderId => "plain"; public string ModelId => "plain-model"; public Task CompleteAsync(LlmRequest request, CancellationToken ct = default) => Task.FromResult(response); } [Fact] public async Task DefaultStream_CarriesTheAnswer() { var answer = new LlmResponse { Content = [new LlmTextBlock("done")], StopReason = LlmStopReason.EndTurn, Usage = new LlmUsage(3, 2), RawStopReason = "stop", ProviderResponseId = "r-1" }; var chunks = await DrainAsync(new PlainOnlyProvider(answer)); chunks[^1].Response.Should().BeSameAs(answer, "a provider that cannot stream still hands the engine its answer"); } } Path: redb-route/tests/redb.Route.Tests.Llm/README.md 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/README.md ---- # redb.Route.Tests.Llm Integration tests for the **redb.Route.Llm** connector. Two suites live here: | Suite | What it proves | Network | | --- | --- | --- | | `LlmComponentTests`, `LlmEndpointTests`, `LlmProducerTests`, `LlmIntegrationTests`, `LlmServiceCollectionExtensionsTests`, `LlmBuilderTests`, `LlmConnectionFactoryTests`, `LlmEndpointOptionsTests`, `StubProviderTests` | Wiring, options, service registration, end-to-end with a scripted `FakeProvider` | None | | `LiveProviderTests` | The connector talks to **real free-tier LLM endpoints** (Groq, Mistral, Cerebras, Gemini, OpenRouter) | Yes (env keys) | | `DslShowcase/*Tests` | The DSL **as a human would read it** — `From → To → Tools` — against real providers | Yes (env keys) | The first set runs anywhere. The other two are **gated by environment variables** and silently skipped when keys are missing — so a clean checkout still passes `dotnet test`. --- ## Why DslShowcase exists `redb.Route.Llm` is a Camel-style ESB connector. Its whole pitch is: > "An LLM call is one more `To(...)` in your route. A tool is one more `From(...)`." `DslShowcase/` is meant to be **read like documentation**. Each test is the smallest live shape that proves a single DSL claim. If you want to know how the connector is used in practice, open these files first — they are deliberately short, with comments aimed at a human reader, not a CI log. | File | DSL shape | Provider | | --- | --- | --- | | `BasicChatTests.cs` | `From("direct:chat") → To("llm://...") → To("mock:result")` | Groq, Gemini, Mistral | | `InlineLlmTests.cs` | `From("direct:chat") → .Llm("name", b => b...) → To("mock:result")` | Groq, Mistral | | `ToolRouteTests.cs` | A `RouteBuilder` mounted with `.AsLlmTool(...)` is auto-discovered by the agent loop | Groq | | `HttpFetchToolTests.cs` | The pre-built `HttpFetchTool` from `redb.Route.Llm.Tools` plugs into a route with one line | Scripted | | `ChainedLlmTests.cs` | Two `To("llm://...")` hops in a row carry the body forward, no glue code | Groq | | `RegistryDrivenPromptTests.cs` | `?systemPromptRef=#name` resolves through `IPromptTemplateRegistry` / `IRouteContext` | Scripted | | `ClaudeChatTests.cs` | Same DSL shapes against Anthropic Claude via the official OpenAI-compat endpoint — chat, tool-use, two-hop chain | **Anthropic Claude (Haiku 4.5 + Sonnet 4.6)** | `HttpFetchToolTests` deliberately uses a scripted `FakeProvider`. The point of that test is the **DSL + tool wiring + real HTTP fetch**, not whether a 7B free-tier model copies a long URL byte-for-byte. Live tool-use behavior is covered by `ToolRouteTests`. --- ## Running the tests ```bash # Local-only (no network, no env keys needed): dotnet test --filter "Category!=LiveLlm" # Live tests against any provider whose key is set: dotnet test --filter "Category=LiveLlm" # Just the DSL showcase: dotnet test --filter "FullyQualifiedName~DslShowcase" # A single live test: dotnet test --filter "FullyQualifiedName=redb.Route.Tests.Llm.DslShowcase.BasicChatTests.Groq_From_To_Mock_DeliversAnswer" ``` All live tests are tagged `[Trait("Category", "LiveLlm")]` and run inside the `LiveLlmSerial` xUnit collection so we don't hammer free tiers from parallel workers. --- ## Environment variables Live tests use `[EnvFact("REDB_LLM__KEY")]` — they are **skipped** (not failed) when the matching variable is unset. The variables are: | Variable | Used by | Free-tier reliability | | --- | --- | --- | | `REDB_LLM_ANT_API03_KEY` | **Anthropic Claude** (Haiku 4.5 + Sonnet 4.6 via the official OpenAI-compat endpoint) | **Highest** — used for strict assertions, including literal-token replies | | `REDB_LLM_GROQ_KEY` | Groq (Llama 3.3 70B) | High — used for strict assertions | | `REDB_LLM_MISTRAL_KEY` | Mistral (`mistral-small-latest`) | Decent — used for "any reply" assertions | | `REDB_LLM_CEREBRAS_KEY` | Cerebras | Decent for chat, slow for tools | | `REDB_LLM_GEMINI_KEY` | Google Gemini (`gemini-2.0-flash`) | Variable — daily / per-minute quotas | | `REDB_LLM_OPENROUTER_KEY` | OpenRouter (free models) | Variable — depends on upstream | | `REDB_LLM_GITHUB_TOKEN` | GitHub Models | Optional | You can set these in the shell, or drop a `.env.local` file at `redb.Tsak/publish/keys/.env.local` — `TestHelpers/EnvLoader.cs` walks up from `AppContext.BaseDirectory` and loads any `KEY=VALUE` lines it finds without overwriting existing variables. --- ## Philosophy: what "live" means We are *not* claiming every free tier is production-grade. We *are* claiming the connector works in principle against all of them. So: - For **Anthropic Claude (Haiku 4.5 + Sonnet 4.6)** we use **strict assertions**. Claude is the most reliable closed-source model we have access to — it reliably follows "reply with the literal token X" instructions, calls the right tool with the right args, and produces French-shaped output on translate hops. The full `ClaudeChatTests` suite passes every run. - For **Groq + Llama 3.3 70B** we use **strict assertions** ("the model must produce the literal token `pong`"). Groq is the most reliable free tier we have access to. - For **Mistral / Cerebras** we assert that *some* non-empty reply comes back. Their small free models phrase things differently each call. - For **Gemini / OpenRouter** we accept that these will sometimes 429. A failure here is a free-tier quota artefact, not a connector regression. When a free-tier provider fails, look at the error body before assuming the connector is broken — `429`, daily quota, or transient rate-limits are common, and the test will pass on retry. --- ## What the helpers do | Helper | Role | | --- | --- | | `LiveLlmHost` | Hand-rolled wiring of `RouteContext` + `LlmComponent` + `AgentEngine` + `IProducerTemplate` + `IToolDescriptorRegistry`, mirroring what `services.AddRedbRouteLlm()` would do. Lets a test stay close to a Camel-style example. | | `EchoToolRoute` | A `RouteBuilder` that mounts `direct:tool-{name}` with `.AsLlmTool(name)` and captures every input the agent passes — used to assert "the model called the tool with these args". | | `LocalHttpServer` | Tiny in-process `HttpListener` server bound to a free localhost port. Configurable response/status, captures request paths. Used by `HttpFetchToolTests`. | | `FakeProvider` | Scriptable `ILlmProvider`. `EnqueueText`, `EnqueueToolUse`, exposes `CallCount` and `CapturedRequests`. Network-free. | | `EnvLoader` | `[ModuleInitializer]` that loads `.env.local` once per process, never overwriting set variables. | | `LiveLlmCollection` | xUnit `CollectionDefinition` with `DisableParallelization = true`, so live tests don't race against shared free-tier quotas. | | `EnvFactAttribute` | `FactAttribute` that sets `Skip` when the named env var is missing. | --- ## Adding a new live test 1. Pick the smallest DSL shape that proves the new behavior. 2. Use `LiveLlmHost.Build()` and `.AddFactory(name, factory)` — do not invent your own DI bootstrap. 3. Tag the test: ```csharp [Trait("Category", "LiveLlm")] [Collection("LiveLlmSerial")] ``` 4. Gate on the right env var with `[EnvFact("REDB_LLM__KEY")]`. 5. Pick the assertion strictness that matches the provider's reliability — see the table above. 6. Read the test out loud. If it sounds like prose, ship it. If it reads like wiring, simplify. Path: redb-route/tests/redb.Route.Tests.Llm/ReplayProviderThinkingTests.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/ReplayProviderThinkingTests.cs ---- using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm; /// /// Wave 16.2 (debt from 16.1): a thinking block survives the replay fixture. The snapshot has a slot /// for the thought, its signature and a redacted payload on both sides — a recorded block /// without them came back as Type = "unknown" and vanished, so an eval replay of a tool loop /// silently lost the reasoning the provider is supposed to get back. /// public sealed class ReplayProviderThinkingTests { [Fact] public async Task ThinkingBlock_SurvivesReplaySnapshot() { var fixture = Path.Combine(Path.GetTempPath(), $"redb-replay-{Guid.NewGuid():N}.json"); try { // The request side: the shape a second iteration of a tool loop sends — the assistant turn // that carries the reasoning, then the tool result. var request = new LlmRequest { Messages = [ LlmMessage.User("status of order 42?"), new LlmMessage { Role = "assistant", Content = [ new LlmThinkingBlock("previous reasoning", "sig-prev"), new LlmToolUseBlock("tu_1", "order_lookup", """{"orderId":"42"}""") ] }, new LlmMessage { Role = "user", Content = [new LlmToolResultBlock("tu_1", """{"status":"shipped"}""")] } ] }; var inner = new FakeProvider().Enqueue(new LlmResponse { Content = [new LlmThinkingBlock("recorded reasoning", "sig-9"), new LlmTextBlock("shipped")], StopReason = LlmStopReason.EndTurn, Usage = new LlmUsage(3, 4) }); var recorder = new ReplayProvider(fixture, ReplayMode.Record, inner); var recorded = await recorder.CompleteAsync(request); recorded.Content.OfType().Should().ContainSingle(); recorder.EntryCount.Should().Be(1); var snapshot = await File.ReadAllTextAsync(fixture); snapshot.Should().Contain("sig-prev", "the request snapshot keeps the signature that makes the block replayable"); snapshot.Should().Contain("sig-9", "the response snapshot keeps it too"); snapshot.Should().Contain("thinking", "the block is recorded under its own kind, not as \"unknown\""); var replayed = await new ReplayProvider(fixture, ReplayMode.Replay).CompleteAsync(request); var block = replayed.Content.OfType().Should().ContainSingle( "a block recorded without its fields comes back as \"unknown\" and is dropped").Subject; block.Text.Should().Be("recorded reasoning"); block.Signature.Should().Be("sig-9"); } finally { if (File.Exists(fixture)) File.Delete(fixture); } } } Path: redb-route/tests/redb.Route.Tests.Llm/RequestTimeoutTests.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/RequestTimeoutTests.cs ---- using System.Diagnostics; using System.Net; using System.Net.Http.Headers; using System.Text; namespace redb.Route.Tests.Llm; /// /// limits the whole call: waiting for the response AND reading it, /// on every provider, whatever client sends it. It used to be the client's HttpClient.Timeout, which with /// ResponseHeadersRead stops at the headers: a server that answered with headers at once and then held the /// body (DeepSeek does) was never limited, and a client passed in by the caller was never limited by the factory at /// all. A streamed call is limited the same way, the stream included; /// limits a stream's silence, counting only the waits on the provider. /// public sealed class RequestTimeoutTests { private static readonly TimeSpan Limit = TimeSpan.FromSeconds(1); /// Longer than any test waits: a server that never finishes. private static readonly TimeSpan Never = TimeSpan.FromSeconds(30); /// A test that would hang without the limit fails here instead. private static readonly TimeSpan Guard = TimeSpan.FromSeconds(10); private static LlmConnectionFactory Factory(string provider, string model, int timeoutMs = 1000, int? idleMs = null) => new() { Name = "slow", Provider = provider, ModelId = model, ApiKey = "sk-test", RequestTimeoutMs = timeoutMs, StreamIdleTimeoutMs = idleMs, }; /// The caller's client, without a timeout of its own: only the factory's limit can end the call. private static HttpClient Client(HttpMessageHandler handler) => new(handler) { Timeout = Timeout.InfiniteTimeSpan }; private static LlmRequest Request() => new() { Messages = [LlmMessage.User("hi")] }; /// Answers with headers at once and holds the body back. private sealed class SlowBodyHandler(string body, TimeSpan bodyDelay, string mediaType = "application/json") : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) { var content = new StreamContent(new DelayedStream(Encoding.UTF8.GetBytes(body), bodyDelay)); content.Headers.ContentType = new MediaTypeHeaderValue(mediaType); return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = content }); } } /// Does not answer at all until the delay passes. private sealed class SlowHeadersHandler(TimeSpan delay) : HttpMessageHandler { protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) { await Task.Delay(delay, ct); return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{}") }; } } /// A body whose first read waits for the delay; the reader's token can end the wait. private sealed class DelayedStream(byte[] data, TimeSpan delay) : Stream { private int _position; private bool _waited; public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) { if (!_waited) { await Task.Delay(delay, cancellationToken); _waited = true; } var count = Math.Min(buffer.Length, data.Length - _position); data.AsMemory(_position, count).CopyTo(buffer); _position += count; return count; } public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); // The OpenAI stream loop asks StreamReader.EndOfStream, which reads synchronously. public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult(); public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => false; public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public override void Flush() { } public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); } private static void ShouldBeTheFactoryLimit( Exception? thrown, string providerId, Stopwatch elapsed, string because, LlmTimeoutKind kind = LlmTimeoutKind.Call, TimeSpan? limit = null) { var timeout = thrown.Should().BeOfType(because).Subject; timeout.ProviderId.Should().Be(providerId); timeout.FactoryName.Should().Be("slow", "the message must say whose limit ran out"); timeout.Kind.Should().Be(kind); timeout.Limit.Should().Be(limit ?? Limit); timeout.Message.Should().Contain(kind == LlmTimeoutKind.Call ? "RequestTimeoutMs" : "StreamIdleTimeoutMs", "the message names the option to raise"); elapsed.Elapsed.Should().BeLessThan(Guard); } /// Answers at once with headers, then writes the lines one by one with a pause before each but the first. private sealed class TrickleHandler(IReadOnlyList lines, TimeSpan interval, TimeSpan silenceAfter) : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) { var content = new StreamContent(new TrickleStream(lines, interval, silenceAfter)); content.Headers.ContentType = new MediaTypeHeaderValue("text/event-stream"); return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = content }); } } /// A body that releases one line per interval, then keeps silent for silenceAfter before it ends. private sealed class TrickleStream(IReadOnlyList lines, TimeSpan interval, TimeSpan silenceAfter) : Stream { private int _next; private byte[] _current = []; private int _offset; public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) { if (_offset == _current.Length) { if (_next == lines.Count) { if (silenceAfter > TimeSpan.Zero) await Task.Delay(silenceAfter, cancellationToken); return 0; } if (_next > 0) await Task.Delay(interval, cancellationToken); _current = Encoding.UTF8.GetBytes(lines[_next++] + "\n"); _offset = 0; } var count = Math.Min(buffer.Length, _current.Length - _offset); _current.AsMemory(_offset, count).CopyTo(buffer); _offset += count; return count; } public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult(); public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => false; public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public override void Flush() { } public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); } private const string OpenAiPiece = "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"x\"}}]}"; private const string OpenAiFinish = "data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}"; /// An OpenAI-compatible stream of text pieces that ends as a model finishes. private static List OpenAiLines(int pieces, string piece = OpenAiPiece) { var lines = new List(); for (var i = 0; i < pieces; i++) lines.AddRange([piece, ""]); lines.AddRange([OpenAiFinish, "", "data: [DONE]"]); return lines; } private static async Task DrainAsync(ILlmProvider provider, TimeSpan pauseBetweenPieces = default) { var chunks = 0; await foreach (var _ in provider.StreamAsync(Request())) { chunks++; if (pauseBetweenPieces > TimeSpan.Zero) await Task.Delay(pauseBetweenPieces); } return chunks; } [Fact] public async Task OpenAi_BodyThatDoesNotArrive_IsCutAtTheFactoryLimit() { var provider = new OpenAiProvider(Factory("deepseek", "deepseek-flash"), Client(new SlowBodyHandler("""{"choices":[{"message":{"role":"assistant","content":"done"}}]}""", Never))); var sw = Stopwatch.StartNew(); var thrown = await Record.ExceptionAsync(() => provider.CompleteAsync(Request()).WaitAsync(Guard)); ShouldBeTheFactoryLimit(thrown, "deepseek", sw, "the headers came at once and the body never did: the limit covers reading the answer, not only waiting for it"); } [Fact] public async Task OpenAi_HeadersThatDoNotArrive_AreCutAtTheFactoryLimit() { var provider = new OpenAiProvider(Factory("deepseek", "deepseek-flash"), Client(new SlowHeadersHandler(Never))); var sw = Stopwatch.StartNew(); var thrown = await Record.ExceptionAsync(() => provider.CompleteAsync(Request()).WaitAsync(Guard)); ShouldBeTheFactoryLimit(thrown, "deepseek", sw, "the factory's limit holds for a client passed in by the caller, not only for the package's own"); } [Fact] public async Task Anthropic_BodyThatDoesNotArrive_IsCutAtTheFactoryLimit() { var provider = new AnthropicProvider(Factory("anthropic", "claude-opus-4-8"), Client(new SlowBodyHandler("""{"content":[{"type":"text","text":"done"}],"stop_reason":"end_turn"}""", Never))); var sw = Stopwatch.StartNew(); var thrown = await Record.ExceptionAsync(() => provider.CompleteAsync(Request()).WaitAsync(Guard)); ShouldBeTheFactoryLimit(thrown, "anthropic", sw, "every provider keeps the same contract"); } [Fact] public async Task Transcription_BodyThatDoesNotArrive_IsCutAtTheFactoryLimit() { var provider = new OpenAiTranscriptionProvider(Factory("openai", "whisper-1"), Client(new SlowBodyHandler("""{"text":"hi"}""", Never))); var sw = Stopwatch.StartNew(); var thrown = await Record.ExceptionAsync(() => provider .TranscribeAsync(new TranscriptionRequest(new byte[] { 0x4F, 0x67, 0x67, 0x53 }, "voice.oga")) .WaitAsync(Guard)); ShouldBeTheFactoryLimit(thrown, "openai", sw, "a long recording is limited the same way as a chat call"); } [Fact] public async Task Embeddings_BodyThatDoesNotArrive_AreCutAtTheFactoryLimit() { var provider = new OpenAiEmbeddingProvider(Factory("openai", "text-embedding-3-small"), Client(new SlowBodyHandler("""{"data":[{"embedding":[0.1]}]}""", Never))); var sw = Stopwatch.StartNew(); var thrown = await Record.ExceptionAsync(() => provider.EmbedAsync(["hi"]).WaitAsync(Guard)); ShouldBeTheFactoryLimit(thrown, "openai", sw, "every provider keeps the same contract"); } [Fact] public async Task Stream_ResponseThatDoesNotStart_IsCutAtTheFactoryLimit() { var provider = new OpenAiProvider(Factory("deepseek", "deepseek-flash"), Client(new SlowHeadersHandler(Never))); async Task Drain() { await foreach (var _ in provider.StreamAsync(Request())) { } } var sw = Stopwatch.StartNew(); var thrown = await Record.ExceptionAsync(() => Drain().WaitAsync(Guard)); ShouldBeTheFactoryLimit(thrown, "deepseek", sw, "a stream that never starts is limited like any call"); } [Fact] public async Task Stream_LongerThanTheLimit_IsCut() { // Pieces keep arriving, a quarter-second apart, for three seconds: the stream is alive, and still the call // outlasts RequestTimeoutMs, which covers the whole call, streamed or not. var provider = new OpenAiProvider(Factory("deepseek", "deepseek-flash"), Client(new TrickleHandler(OpenAiLines(12), TimeSpan.FromMilliseconds(125), TimeSpan.Zero))); var sw = Stopwatch.StartNew(); var thrown = await Record.ExceptionAsync(() => DrainAsync(provider).WaitAsync(Guard)); ShouldBeTheFactoryLimit(thrown, "deepseek", sw, "RequestTimeoutMs limits the whole call, the stream included"); } [Fact] public async Task Anthropic_Stream_LongerThanTheLimit_IsCut() { var lines = new List { "event: message_start", """data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"usage":{"input_tokens":1,"output_tokens":1}}}""", "" }; for (var i = 0; i < 12; i++) lines.AddRange(["event: ping", """data: {"type":"ping"}""", ""]); lines.AddRange([ "event: message_delta", """data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}""", "", "event: message_stop", """data: {"type":"message_stop"}"""]); var provider = new AnthropicProvider(Factory("anthropic", "claude-opus-4-8"), Client(new TrickleHandler(lines, TimeSpan.FromMilliseconds(80), TimeSpan.Zero))); var sw = Stopwatch.StartNew(); var thrown = await Record.ExceptionAsync(() => DrainAsync(provider).WaitAsync(Guard)); ShouldBeTheFactoryLimit(thrown, "anthropic", sw, "every provider limits its stream the same way"); } [Fact] public async Task Stream_SilentLongerThanTheIdleLimit_IsCut() { var idle = TimeSpan.FromMilliseconds(400); var provider = new OpenAiProvider(Factory("deepseek", "deepseek-flash", timeoutMs: 60_000, idleMs: 400), Client(new TrickleHandler([OpenAiPiece, ""], TimeSpan.Zero, Never))); var sw = Stopwatch.StartNew(); var thrown = await Record.ExceptionAsync(() => DrainAsync(provider).WaitAsync(Guard)); ShouldBeTheFactoryLimit(thrown, "deepseek", sw, "one piece came and then nothing: a stream silent past StreamIdleTimeoutMs is stuck", LlmTimeoutKind.StreamIdle, idle); } [Fact] public async Task Stream_KeepAliveComments_HoldOffTheIdleLimit() { // Nothing but keep-alive comments for 2 s, with a 1 s silence limit: the provider is there, only slow. A comment // every 100 ms leaves ten times the gap before the limit (row 67: at 200 ms against 600 ms a loaded release // stand stretched one gap past the limit); the 2 s in total still exceed it, so the comments are what hold it off. var lines = new List(); for (var i = 0; i < 20; i++) lines.Add(": keep-alive"); lines.AddRange(OpenAiLines(1)); var provider = new OpenAiProvider(Factory("deepseek", "deepseek-flash", timeoutMs: 60_000, idleMs: 1_000), Client(new TrickleHandler(lines, TimeSpan.FromMilliseconds(100), TimeSpan.Zero))); var chunks = await DrainAsync(provider).WaitAsync(Guard); chunks.Should().Be(2, "one text piece and the last chunk: the comments count as the provider being there"); } [Fact] public async Task Stream_SlowReader_IsNotSilence() { // The provider sends everything at once; the reader takes 300 ms over each piece. The silence limit counts // the waits on the provider, not the reader's own time. var provider = new OpenAiProvider(Factory("deepseek", "deepseek-flash", timeoutMs: 60_000, idleMs: 200), Client(new TrickleHandler(OpenAiLines(3), TimeSpan.Zero, TimeSpan.Zero))); var chunks = await DrainAsync(provider, pauseBetweenPieces: TimeSpan.FromMilliseconds(300)).WaitAsync(Guard); chunks.Should().Be(4); } [Fact] public void StreamIdleLimit_IsOffByDefault_AndPositiveWhenSet() { new LlmConnectionFactory().StreamIdleTimeoutMs.Should().BeNull( "some reasoning models stream nothing for minutes before their first token"); var act = () => new LlmConnectionFactory { StreamIdleTimeoutMs = 0 }; act.Should().Throw("zero is not \"off\": off is unset"); } [Fact] public async Task CallerCancellation_StaysACancellation() { var provider = new OpenAiProvider(Factory("deepseek", "deepseek-flash", timeoutMs: 60_000), Client(new SlowHeadersHandler(Never))); using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200)); var thrown = await Record.ExceptionAsync(() => provider.CompleteAsync(Request(), cts.Token).WaitAsync(Guard)); thrown.Should().BeAssignableTo( "a caller that stopped the call must not be told the model was too slow"); } } Path: redb-route/tests/redb.Route.Tests.Llm/Storage/ConversationIsolationTests.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/ConversationIsolationTests.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Providers; using redb.Route.Llm.Storage.Redb; using redb.Route.Llm.Storage.Redb.Schemas; namespace redb.Route.Tests.Llm.Storage; /// /// Cross-conversation isolation for , against a /// live Postgres Pro database. /// /// Every test here carries a negative control: the conversation that must /// NOT leak is written last, so it is the freshest row in the schema. That /// is precisely the shape the original suite lacked — its transcripts were always /// the newest rows in the database, so a "freshest leaf anywhere" query returned /// the right answer by accident and the tests stayed green while conversations /// leaked into each other. /// /// [Collection("StoragePro")] public sealed class ConversationIsolationTests { private readonly StorageProFixture _fx; public ConversationIsolationTests(StorageProFixture fx) => _fx = fx; private static ConversationMessageMeta Meta(int iter, DateTime? at = null) => new() { CreatedAtUtc = at ?? DateTime.UtcNow, Iteration = iter, Usage = new LlmUsage(10, 5) }; private static string NewConversationId() => $"c-{Guid.NewGuid():N}"; private async Task RootIdOfAsync(string conversationId) { var root = await _fx.Redb.Query() .WhereRedb(x => x.ValueString == conversationId) .FirstOrDefaultAsync(); root.Should().NotBeNull($"conversation '{conversationId}' should have a root by now"); return root!.id; } [Fact] public async Task LoadPath_EmptyConversation_DoesNotSeeAnotherTranscript() { var store = new RedbConversationStore(_fx.RouteContext); var quiet = NewConversationId(); var busy = NewConversationId(); // The quiet conversation exists but never gets a message. (await store.LoadPathAsync(quiet)).Should().BeEmpty(); // Negative control: the other conversation is written afterwards, so its // rows are the newest in the whole schema. var t0 = DateTime.UtcNow; var m1 = await store.AppendAsync(busy, null, LlmMessage.User("private question"), Meta(0, t0)); await store.AppendAsync(busy, m1, LlmMessage.Assistant("private answer"), Meta(1, t0.AddSeconds(1))); (await store.LoadPathAsync(quiet)).Should().BeEmpty( "a conversation with no messages has an empty transcript, no matter what else is in the database"); } [Fact] public async Task LoadPath_ReturnsOnlyOwnMessages_WhenAnotherConversationIsNewer() { var store = new RedbConversationStore(_fx.RouteContext); var mine = NewConversationId(); var theirs = NewConversationId(); var t0 = DateTime.UtcNow; var m1 = await store.AppendAsync(mine, null, LlmMessage.User("mine 1"), Meta(0, t0)); var m2 = await store.AppendAsync(mine, m1, LlmMessage.Assistant("mine 2"), Meta(1, t0.AddSeconds(1))); // Negative control again: written later, so globally freshest. var o1 = await store.AppendAsync(theirs, null, LlmMessage.User("theirs 1"), Meta(0, t0.AddSeconds(2))); await store.AppendAsync(theirs, o1, LlmMessage.Assistant("theirs 2"), Meta(1, t0.AddSeconds(3))); var path = await store.LoadPathAsync(mine); // Exact set, not Contain(...): a leak shows up as extra rows, and an // assertion that only checks for presence cannot see it. path.Select(x => x.Id).Should().BeEquivalentTo([m1, m2], opts => opts.WithStrictOrdering()); path.Select(x => x.ConversationId).Should().AllBe(mine); } [Fact] public async Task LoadPath_LeafFromAnotherConversation_ReturnsEmpty() { var store = new RedbConversationStore(_fx.RouteContext); var mine = NewConversationId(); var theirs = NewConversationId(); await store.AppendAsync(mine, null, LlmMessage.User("mine"), Meta(0)); var foreignLeaf = await store.AppendAsync(theirs, null, LlmMessage.User("theirs"), Meta(0)); // Message ids are opaque GUIDs handed to callers; a caller that branches by // id must not be able to read another conversation through one. var path = await store.LoadPathAsync(mine, foreignLeaf); path.Should().BeEmpty(); } [Fact] public async Task Append_ParentFromAnotherConversation_Throws() { var store = new RedbConversationStore(_fx.RouteContext); var mine = NewConversationId(); var theirs = NewConversationId(); await store.AppendAsync(mine, null, LlmMessage.User("mine"), Meta(0)); var foreignParent = await store.AppendAsync(theirs, null, LlmMessage.User("theirs"), Meta(0)); // Must fail loudly: a silent write would attach this message into the other // conversation's tree, and no later read can undo that. var act = async () => await store.AppendAsync( mine, foreignParent, LlmMessage.Assistant("leaked"), Meta(1)); await act.Should().ThrowAsync(); // And the foreign conversation must be untouched. var theirPath = await store.LoadPathAsync(theirs); theirPath.Should().ContainSingle().Which.Id.Should().Be(foreignParent); } [Fact] public async Task LoadPath_OnAlreadyCorruptedTree_ReadsByFkAndSkipsForeignRoot() { // Reproduces data written *before* the fix: the conversation FK // (value_long) says "mine", while the physical parent is another // conversation's root. The FK was always stamped correctly, so a // FK-scoped read still recovers the right transcript — and the foreign // ConversationProps root must not slip in as a role-less message // (which the provider would reject with a 400 that looks like a model bug). var store = new RedbConversationStore(_fx.RouteContext); var mine = NewConversationId(); var theirs = NewConversationId(); await store.AppendAsync(mine, null, LlmMessage.User("anchor"), Meta(0)); await store.AppendAsync(theirs, null, LlmMessage.User("theirs"), Meta(0)); var myRootId = await RootIdOfAsync(mine); var theirRootId = await RootIdOfAsync(theirs); var theirRoot = await _fx.Redb.LoadAsync(theirRootId); var orphan = new TreeRedbObject { value_string = Guid.NewGuid().ToString("N"), value_long = myRootId, // FK: mine Props = new MessageProps { Role = "assistant", Iteration = 1, CreatedAtUtc = DateTimeOffset.UtcNow, Content = [] } }; await _fx.Redb.CreateChildAsync(orphan, theirRoot!); // parent: theirs var path = await store.LoadPathAsync(mine); path.Should().NotBeEmpty(); path.Select(x => x.Message.Role).Should().NotContain(string.Empty, "the foreign conversation root is not a message and must never reach the provider"); path.Last().Id.Should().Be(orphan.value_string); } } Path: redb-route/tests/redb.Route.Tests.Llm/Storage/KnowledgeStoreSearchTextTests.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/KnowledgeStoreSearchTextTests.cs ---- using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Storage.Redb; namespace redb.Route.Tests.Llm.Storage; /// /// — keyword (substring) retrieval. /// The in-memory suite runs everywhere (no DB); the redb suite proves the /// server-side case-insensitive LIKE push-down against Postgres Pro. /// public sealed class InMemoryKnowledgeStoreSearchTextTests { private static KnowledgeChunk Chunk(string id, string text, string? collection = null, string? meta = null) => new() { Id = id, Text = text, Collection = collection, MetadataJson = meta, Embedding = new float[] { 0f } }; private static async Task SeedAsync(params KnowledgeChunk[] chunks) { IKnowledgeStore store = new InMemoryKnowledgeStore(); // UpsertManyAsync is a default interface member await store.UpsertManyAsync(chunks); return store; } [Fact] public async Task FindsSubstring_CaseInsensitive() { var store = await SeedAsync( Chunk("1", "Apples grow on trees."), Chunk("2", "Bananas are yellow."), Chunk("3", "Cherries are red.")); var hits = await store.SearchTextAsync("APPLE", topK: 5); hits.Should().ContainSingle(); hits[0].Chunk.Id.Should().Be("1"); } [Fact] public async Task RanksByOccurrenceCount() { var store = await SeedAsync( Chunk("once", "The fox ran away."), Chunk("many", "fox, fox and another fox.")); var hits = await store.SearchTextAsync("fox", topK: 5); hits.Select(h => h.Chunk.Id).Should().Equal("many", "once"); hits[0].Score.Should().BeGreaterThan(hits[1].Score); } [Fact] public async Task CollectionFilter_IsolatesResults() { var store = await SeedAsync( Chunk("a", "a shared keyword here", collection: "alpha"), Chunk("b", "a shared keyword here", collection: "beta")); var hits = await store.SearchTextAsync("keyword", topK: 5, collection: "beta"); hits.Should().ContainSingle(); hits[0].Chunk.Id.Should().Be("b"); } [Fact] public async Task EmptyQuery_ReturnsEmpty() { var store = await SeedAsync(Chunk("1", "any text")); (await store.SearchTextAsync(" ", topK: 5)).Should().BeEmpty(); } [Fact] public async Task NoMatch_ReturnsEmpty() { var store = await SeedAsync(Chunk("1", "apple and banana")); (await store.SearchTextAsync("zebra", topK: 5)).Should().BeEmpty(); } } /// Integration: against Postgres Pro. [Collection("StoragePro")] public sealed class RedbKnowledgeStoreSearchTextTests { private readonly StorageProFixture _fx; public RedbKnowledgeStoreSearchTextTests(StorageProFixture fx) => _fx = fx; private static KnowledgeChunk Chunk(string id, string text, string? collection = null, string? meta = null) => new() { Id = id, Text = text, Collection = collection, MetadataJson = meta, Embedding = new float[] { 0.1f, 0.2f } }; // Seed via single UpsertAsync, not UpsertManyAsync: the bulk path has a // pre-existing redb-parser limitation (string[].Contains binds to the // MemoryExtensions span overload, which WhereRedb does not translate). private static async Task SeedAsync(IKnowledgeStore store, params KnowledgeChunk[] chunks) { foreach (var c in chunks) await store.UpsertAsync(c); } [Fact] public async Task ServerSideLike_FindsAndRanks_CaseInsensitive() { var store = new RedbKnowledgeStore(_fx.RouteContext); var coll = $"k-{Guid.NewGuid():N}"; await SeedAsync(store, Chunk($"{coll}:1", "Apple pie is tasty.", coll), Chunk($"{coll}:2", "apple, Apple, and APPLE again.", coll), Chunk($"{coll}:3", "Only bananas here.", coll)); var hits = await store.SearchTextAsync("apple", topK: 5, collection: coll); hits.Should().HaveCount(2); // ILIKE matches Apple / APPLE too hits[0].Chunk.Id.Should().Be($"{coll}:2"); // 3 occurrences rank first hits[0].Score.Should().BeGreaterThan(hits[1].Score); } [Fact] public async Task NonAscii_StoredUtf8_IsSearchable() { // Proves the note envelope is written as UTF-8 (relaxed JSON escaping), // not \uXXXX — otherwise a non-ASCII query never matches the LIKE. var store = new RedbKnowledgeStore(_fx.RouteContext); var coll = $"k-{Guid.NewGuid():N}"; await SeedAsync(store, Chunk($"{coll}:1", "A cosy café in Zürich.", coll), Chunk($"{coll}:2", "A plain office downtown.", coll)); var hits = await store.SearchTextAsync("café", topK: 5, collection: coll); hits.Should().ContainSingle(); hits[0].Chunk.Id.Should().Be($"{coll}:1"); } [Fact] public async Task EnvelopeOnlyMatch_IsDropped() { // The query hits the metadata (part of the {text,meta} envelope the LIKE // sees) but NOT the decoded text → the in-process re-score must drop it. var store = new RedbKnowledgeStore(_fx.RouteContext); var coll = $"k-{Guid.NewGuid():N}"; await SeedAsync(store, Chunk($"{coll}:text", "The keyword lives in the text.", coll), Chunk($"{coll}:meta", "Nothing relevant in this body.", coll, meta: "{\"tag\":\"keyword\"}")); var hits = await store.SearchTextAsync("keyword", topK: 5, collection: coll); hits.Should().ContainSingle(); hits[0].Chunk.Id.Should().Be($"{coll}:text"); } [Fact] public async Task NoMatch_ReturnsEmpty() { var store = new RedbKnowledgeStore(_fx.RouteContext); var coll = $"k-{Guid.NewGuid():N}"; await SeedAsync(store, Chunk($"{coll}:1", "apple and banana", coll)); (await store.SearchTextAsync("zebra", topK: 5, collection: coll)).Should().BeEmpty(); } [Fact] public async Task UpsertMany_BulkPath_InsertsAndUpdates() { // Exercises the whole bulk path that used to be broken end-to-end: // 1) existing-key lookup keys.Contains(o.ValueString) → IN clause // (redb-parser fix for the MemoryExtensions.Contains span overload), // 2) ComputeHash() on a loaded property-less row (Props=null) → no NRE // (RedbHash null guard), // 3) no false "unchanged" skip → the changed text is actually persisted. var store = new RedbKnowledgeStore(_fx.RouteContext); var coll = $"k-{Guid.NewGuid():N}"; await store.UpsertManyAsync(new[] { Chunk($"{coll}:a", "alpha shared text", coll), Chunk($"{coll}:b", "beta shared text", coll), }); // Re-upsert: :a changes text (existing key), :c is new. await store.UpsertManyAsync(new[] { Chunk($"{coll}:a", "alpha shared UPDATED text", coll), Chunk($"{coll}:c", "gamma shared text", coll), }); (await store.SearchTextAsync("shared", topK: 10, collection: coll)).Should().HaveCount(3); var updated = await store.SearchTextAsync("UPDATED", topK: 5, collection: coll); updated.Should().ContainSingle(); updated[0].Chunk.Id.Should().Be($"{coll}:a"); // the update was persisted, not skipped } } Path: redb-route/tests/redb.Route.Tests.Llm/Storage/NamedRedbFixture.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/NamedRedbFixture.cs ---- using System.Data.Common; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Npgsql; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Pro.Extensions; using redb.MSSql.Pro.Extensions; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Route.Llm.Storage.Redb.Schemas; using redb.SQLite.Pro.Extensions; namespace redb.Route.Tests.Llm.Storage; /// /// A second redb Pro instance in a database of its own, next to the default one of : the /// "agent memory" database of a host that keeps the agent's data apart from its business data. Registered on a route /// context under with , so ?redb= and a registration name can pick it. /// The same provider as the default instance (REDB_PROVIDER); the database is created when it is missing. On a /// server its name is the default database's with (redb gives redb_agent_memory), so a /// run that points the default connection string at a database of its own gets a named database of its own too. /// public sealed class NamedRedbFixture : IAsyncLifetime { /// The name the instance is registered under. public const string Name = "agent-memory"; /// Appended to the default database's name for the named instance's database on a server. public const string Suffix = "_agent_memory"; private const string SqliteFile = "redb_llm_agent_memory.db"; private ServiceProvider? _services; /// The named instance. public IRedbService Redb { get; private set; } = null!; private static string Provider => Environment.GetEnvironmentVariable("REDB_PROVIDER")?.ToLowerInvariant() is { Length: > 0 } p ? p : "sqlite"; /// public async Task InitializeAsync() { var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); var services = new ServiceCollection(); services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); switch (Provider) { case "postgres": { var cs = new NpgsqlConnectionStringBuilder( global::redb.Route.Tests.Shared.TestDatabases.Postgres(config.GetConnectionString("Postgres")!)); cs.Database += Suffix; await EnsurePostgresDatabaseAsync(cs); services.AddRedbPro(o => o.UsePostgres(cs.ConnectionString).Configure(Settings)); break; } case "mssql": { var cs = new SqlConnectionStringBuilder( global::redb.Route.Tests.Shared.TestDatabases.MsSql(config.GetConnectionString("MsSql")!)); cs.InitialCatalog += Suffix; await EnsureMsSqlDatabaseAsync(cs); services.AddRedbPro(o => o.UseMsSql(cs.ConnectionString).Configure(Settings)); break; } default: services.AddRedbPro(o => o.UseSqlite($"Data Source={SqliteFile}").Configure(Settings)); break; } _services = services.BuildServiceProvider(); Redb = _services.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); } private static void Settings(RedbServiceConfiguration c) { c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; c.EnablePropsCache = false; } /// Registers the instance on under . public void AttachTo(IRouteContext context) => context.RegisterRedbService(Name, Redb); private static async Task EnsurePostgresDatabaseAsync(NpgsqlConnectionStringBuilder target) { var database = target.Database!; var admin = new NpgsqlConnectionStringBuilder(target.ConnectionString) { Database = "postgres" }; await using var connection = new NpgsqlConnection(admin.ConnectionString); await connection.OpenAsync(); await using var exists = new NpgsqlCommand("SELECT 1 FROM pg_database WHERE datname = @n", connection); exists.Parameters.AddWithValue("n", database); if (await exists.ExecuteScalarAsync() is null) { await using var create = new NpgsqlCommand($"CREATE DATABASE \"{database}\"", connection); await create.ExecuteNonQueryAsync(); } } private static async Task EnsureMsSqlDatabaseAsync(SqlConnectionStringBuilder target) { var database = target.InitialCatalog; var admin = new SqlConnectionStringBuilder(target.ConnectionString) { InitialCatalog = "master" }; await using var connection = new SqlConnection(admin.ConnectionString); await connection.OpenAsync(); await using var create = new SqlCommand($"IF DB_ID(N'{database}') IS NULL CREATE DATABASE [{database}]", connection); await create.ExecuteNonQueryAsync(); } /// public async Task DisposeAsync() { if (_services is not null) await _services.DisposeAsync(); } } 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}"""); } } Path: redb-route/tests/redb.Route.Tests.Llm/Storage/NoExchangeConcurrencyTests.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/NoExchangeConcurrencyTests.cs ---- using NSubstitute; using redb.Route.Abstractions; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Providers; using redb.Route.Llm.Storage.Redb; namespace redb.Route.Tests.Llm.Storage; /// /// Every redb store AddRedbLlmStorage registers, called concurrently without an exchange: each call opens a /// scope of its own, so none of them shares the context's single instance (which refuses a second command at once). /// [Collection("StoragePro")] public sealed class NoExchangeConcurrencyTests { private const int Parallel = 8; private readonly StorageProFixture _fx; public NoExchangeConcurrencyTests(StorageProFixture fx) => _fx = fx; private static async Task AllAtOnce(Func> call) { using var start = new ManualResetEventSlim(false); var tasks = Enumerable.Range(0, Parallel).Select(i => Task.Run(async () => { start.Wait(); return await call(i); })).ToList(); start.Set(); return await Task.WhenAll(tasks); } [Fact] public async Task ApprovalStore() { var store = new RedbApprovalStore(_fx.RouteContext); var prefix = $"appr-{Guid.NewGuid():N}"; ApprovalRequest Request(int i) => new() { ConversationId = $"{prefix}-c{i}", ToolUseId = "tu-1", InputJson = "{}", Exchange = Substitute.For(), Tool = new LlmToolCapability { Name = "delete_user", Description = "test tool", InputSchema = "{}" } }; await AllAtOnce(async i => { await store.RecordAsync(Request(i), ApprovalDecision.Approve($"{prefix}-{i}")); return i; }); var found = await AllAtOnce(i => store.FindAsync($"{prefix}-{i}")); found.Should().OnlyContain(r => r != null && r.Approved); } [Fact] public async Task BatchStore() { var store = new RedbBatchStore(_fx.RouteContext); var prefix = $"batch-{Guid.NewGuid():N}"; await AllAtOnce(async i => { await store.RegisterAsync(new BatchJobRecord { BatchId = $"{prefix}-{i}", ProviderId = "anthropic", Status = "submitted" }); return i; }); var found = await AllAtOnce(i => store.GetAsync($"{prefix}-{i}")); found.Should().OnlyContain(r => r != null && r.Status == "submitted"); } [Fact] public async Task ConversationStore() { var store = new RedbConversationStore(_fx.RouteContext); var prefix = $"conv-{Guid.NewGuid():N}"; await AllAtOnce(i => store.AppendAsync($"{prefix}-{i}", null, LlmMessage.User($"q{i}"), new ConversationMessageMeta { CreatedAtUtc = DateTime.UtcNow, Iteration = 0, Usage = new LlmUsage(1, 1) })); var paths = await AllAtOnce(i => store.LoadPathAsync($"{prefix}-{i}")); paths.Should().OnlyContain(p => p.Count == 1); } [Fact] public async Task KnowledgeStore() { var store = new RedbKnowledgeStore(_fx.RouteContext); var collection = $"kn-{Guid.NewGuid():N}"; await AllAtOnce(async i => { await store.UpsertAsync(new KnowledgeChunk { Id = $"{collection}-{i}", Text = $"chunk {i}", Embedding = new[] { 1f, i }, Collection = collection }); return i; }); var hits = await AllAtOnce(_ => store.SearchAsync(new[] { 1f, 0f }, topK: Parallel, collection)); hits.Should().OnlyContain(h => h.Count == Parallel); } [Fact] public async Task PromptTemplateRegistry() { var store = new RedbPromptTemplateRegistry(_fx.RouteContext); var prefix = $"tpl-{Guid.NewGuid():N}"; await AllAtOnce(async i => { await store.SetAsync(new PromptTemplate { Name = $"{prefix}-{i}", Version = "1.0", Body = $"b{i}" }); return i; }); var found = await AllAtOnce(i => store.GetAsync($"{prefix}-{i}")); found.Select(t => t?.Body).Should().Equal(Enumerable.Range(0, Parallel).Select(i => $"b{i}")); } [Fact] public async Task ToolResultCache() { var store = new RedbToolResultCache(_fx.RouteContext); var prefix = $"cache-{Guid.NewGuid():N}"; await AllAtOnce(async i => { await store.SetAsync($"{prefix}-{i}", $$"""{"v":{{i}}}"""); return i; }); var found = await AllAtOnce(async i => await store.GetAsync($"{prefix}-{i}")); found.Should().Equal(Enumerable.Range(0, Parallel).Select(i => $$"""{"v":{{i}}}""")); } } Path: redb-route/tests/redb.Route.Tests.Llm/Storage/RedbApprovalStoreTests.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/RedbApprovalStoreTests.cs ---- using redb.Route.Abstractions; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Storage.Redb; namespace redb.Route.Tests.Llm.Storage; /// Integration tests for . [Collection("StoragePro")] public sealed class RedbApprovalStoreTests { private readonly StorageProFixture _fx; public RedbApprovalStoreTests(StorageProFixture fx) => _fx = fx; private static ApprovalRequest MakeRequest(string convId, string toolUseId, string toolName = "delete_user") => new() { ConversationId = convId, ToolUseId = toolUseId, InputJson = """{"id":42}""", Exchange = Substitute.For(), Tool = new LlmToolCapability { Name = toolName, Description = "test tool", InputSchema = "{}" } }; [Fact] public async Task Record_Then_Find_Approved() { var store = new RedbApprovalStore(_fx.RouteContext); var convId = $"c-{Guid.NewGuid():N}"; var approvalId = $"a-{Guid.NewGuid():N}"; var req = MakeRequest(convId, "tu-1"); await store.RecordAsync(req, ApprovalDecision.Approve(approvalId)); var rec = await store.FindAsync(approvalId); rec.Should().NotBeNull(); rec!.Approved.Should().BeTrue(); rec.ConversationId.Should().Be(convId); rec.ToolName.Should().Be("delete_user"); rec.InputJson.Should().Be("""{"id":42}"""); } [Fact] public async Task Record_Denied_PreservesReason() { var store = new RedbApprovalStore(_fx.RouteContext); var approvalId = $"a-{Guid.NewGuid():N}"; var req = MakeRequest($"c-{Guid.NewGuid():N}", "tu-2"); var decision = new ApprovalDecision { Approved = false, ApprovalId = approvalId, Reason = "policy violation" }; await store.RecordAsync(req, decision); var rec = await store.FindAsync(approvalId); rec.Should().NotBeNull(); rec!.Approved.Should().BeFalse(); rec.Reason.Should().Be("policy violation"); } [Fact] public async Task Find_Unknown_ReturnsNull() { var store = new RedbApprovalStore(_fx.RouteContext); (await store.FindAsync("does-not-exist")).Should().BeNull(); } } Path: redb-route/tests/redb.Route.Tests.Llm/Storage/RedbAuditObserverFailureTests.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/RedbAuditObserverFailureTests.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine.Observability; using redb.Route.Llm.Storage.Redb; namespace redb.Route.Tests.Llm.Storage; /// /// A failed audit write never breaks the run, and it does not vanish either: the row that was not written /// is an audit gap, and an operator has to be able to find it in the log. /// public sealed class RedbAuditObserverFailureTests { /// Keeps every log entry, with its level, message and exception. private sealed class ListLoggerFactory : ILoggerFactory { private readonly List<(LogLevel Level, string Message, Exception? Exception)> _entries = new(); public IReadOnlyList<(LogLevel Level, string Message, Exception? Exception)> Entries { get { lock (_entries) return _entries.ToArray(); } } public ILogger CreateLogger(string categoryName) => new ListLogger(this); public void AddProvider(ILoggerProvider provider) { } public void Dispose() { } private sealed class ListLogger(ListLoggerFactory owner) : ILogger { public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => true; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { lock (owner._entries) owner._entries.Add((logLevel, formatter(state, exception), exception)); } } } [Fact] public async Task SaveFailure_IsLogged_AndTheRunGoesOn() { var loggers = new ListLoggerFactory(); var context = new RouteContext(); // No IRedbService is registered, so the save fails the way a lost connection would. context.AddService(typeof(ILoggerFactory), loggers); var observer = new RedbAuditObserver(context); var invocation = new AgentToolInvocationContext { Run = new AgentRunContext { ConversationId = "c-1", FactoryName = "test", ProviderId = "test", ModelId = "test-model", ExchangeId = "x-1" }, Tool = new LlmToolCapability { Name = "order_lookup", Description = "t", InputSchema = "{}" }, InputJson = """{"orderId":"42"}""", OutputJson = """{"status":"shipped"}""", ToolUseId = "tu-1", Duration = TimeSpan.FromMilliseconds(5) }; var act = () => observer.OnToolInvokedAsync(invocation); await act.Should().NotThrowAsync("audit problems never break a run"); var entry = loggers.Entries.Should().ContainSingle(e => e.Level >= LogLevel.Warning, "the row that was not written is an audit gap an operator must be able to find").Subject; entry.Exception.Should().NotBeNull("the cause of the lost row travels with the entry"); entry.Message.Should().Contain("order_lookup").And.Contain("tu-1"); } } Path: redb-route/tests/redb.Route.Tests.Llm/Storage/RedbAuditObserverTests.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/RedbAuditObserverTests.cs ---- using redb.Core; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine.Observability; using redb.Route.Llm.Providers; using redb.Route.Llm.Storage.Redb; using redb.Route.Llm.Storage.Redb.Schemas; namespace redb.Route.Tests.Llm.Storage; /// /// Integration tests for . Persists one /// row per OnToolInvokedAsync call with /// outcome classification (success / error / denied / skipped). /// [Collection("StoragePro")] public sealed class RedbAuditObserverTests { private readonly StorageProFixture _fx; public RedbAuditObserverTests(StorageProFixture fx) => _fx = fx; private static AgentToolInvocationContext MakeCtx( string convId, string toolName, string toolUseId, string? output = """{"ok":true}""", bool skipped = false, string? skipReason = null, Exception? ex = null) => new() { Run = new AgentRunContext { ConversationId = convId, FactoryName = "test", ProviderId = "test", ModelId = "test-model", ExchangeId = $"x-{Guid.NewGuid():N}" }, Tool = new LlmToolCapability { Name = toolName, Description = "t", InputSchema = "{}" }, InputJson = """{"in":1}""", OutputJson = output, ToolUseId = toolUseId, Duration = TimeSpan.FromMilliseconds(42), Skipped = skipped, SkipReason = skipReason, Exception = ex }; private async Task> LoadAuditForConvAsync(string convId) { var rows = await _fx.Redb.Query() .Where(p => p.ConversationId == convId) .ToListAsync(); return rows.Select(r => r.Props).ToList(); } [Fact] public async Task OnToolInvoked_Success_PersistsRow() { var obs = new RedbAuditObserver(_fx.RouteContext); var convId = $"c-{Guid.NewGuid():N}"; await obs.OnToolInvokedAsync(MakeCtx(convId, "http_fetch", "tu-1")); var rows = await LoadAuditForConvAsync(convId); rows.Should().HaveCount(1); rows[0].ConversationId.Should().Be(convId); rows[0].ToolName.Should().Be("http_fetch"); rows[0].ToolUseId.Should().Be("tu-1"); rows[0].Outcome.Should().Be("success"); rows[0].DurationMs.Should().Be(42); rows[0].OutputJson.Should().Be("""{"ok":true}"""); rows[0].ErrorMessage.Should().BeNull(); } [Fact] public async Task OnToolInvoked_Exception_PersistsErrorOutcome() { var obs = new RedbAuditObserver(_fx.RouteContext); var convId = $"c-{Guid.NewGuid():N}"; await obs.OnToolInvokedAsync(MakeCtx( convId, "buggy", "tu-2", output: null, ex: new InvalidOperationException("boom"))); var rows = await LoadAuditForConvAsync(convId); rows.Should().HaveCount(1); rows[0].Outcome.Should().Be("error"); rows[0].ErrorMessage.Should().Be("boom"); } [Fact] public async Task OnToolInvoked_DeniedSkip_ClassifiesAsDenied() { var obs = new RedbAuditObserver(_fx.RouteContext); var convId = $"c-{Guid.NewGuid():N}"; await obs.OnToolInvokedAsync(MakeCtx( convId, "delete_user", "tu-3", skipped: true, skipReason: "approval denied: not allowed")); var rows = await LoadAuditForConvAsync(convId); rows.Should().HaveCount(1); rows[0].Outcome.Should().Be("denied"); rows[0].SkipReason.Should().Contain("denied"); } } Path: redb-route/tests/redb.Route.Tests.Llm/Storage/RedbConversationStoreTests.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/RedbConversationStoreTests.cs ---- using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Providers; using redb.Route.Llm.Storage.Redb; namespace redb.Route.Tests.Llm.Storage; /// /// Integration tests for backed by a live /// Postgres Pro database. Validates Append + LoadPath + LoadTree round-trip, /// branching (parent/child), and TreeQuery-based latest-leaf resolution. /// [Collection("StoragePro")] public sealed class RedbConversationStoreTests { private readonly StorageProFixture _fx; public RedbConversationStoreTests(StorageProFixture fx) => _fx = fx; private static ConversationMessageMeta Meta(int iter, DateTime? at = null) => new() { CreatedAtUtc = at ?? DateTime.UtcNow, Iteration = iter, Usage = new LlmUsage(10, 5) }; [Fact] public async Task Append_LoadPath_LoadTree_LinearConversation() { var store = new RedbConversationStore(_fx.RouteContext); var convId = $"c-{Guid.NewGuid():N}"; var t0 = DateTime.UtcNow; var m1 = await store.AppendAsync(convId, null, LlmMessage.User("hi"), Meta(0, t0)); var m2 = await store.AppendAsync(convId, m1, LlmMessage.Assistant("hello!"), Meta(1, t0.AddSeconds(1))); var m3 = await store.AppendAsync(convId, m2, LlmMessage.User("how are you?"), Meta(2, t0.AddSeconds(2))); var tree = await store.LoadTreeAsync(convId); tree.Should().HaveCount(3); tree.Select(x => x.Message.Role).Should().BeEquivalentTo(["user", "assistant", "user"]); var path = await store.LoadPathAsync(convId); path.Should().HaveCount(3); path.Last().Id.Should().Be(m3); path.First().Id.Should().Be(m1); } [Fact] public async Task LoadPath_Branching_ResolvesCorrectLeaf() { var store = new RedbConversationStore(_fx.RouteContext); var convId = $"c-{Guid.NewGuid():N}"; var t0 = DateTime.UtcNow; var root = await store.AppendAsync(convId, null, LlmMessage.User("Q"), Meta(0, t0)); var a = await store.AppendAsync(convId, root, LlmMessage.Assistant("A1"), Meta(1, t0.AddSeconds(1))); var b = await store.AppendAsync(convId, root, LlmMessage.Assistant("A2"), Meta(1, t0.AddSeconds(2))); var pathA = await store.LoadPathAsync(convId, a); pathA.Select(x => x.Id).Should().BeEquivalentTo([root, a], opts => opts.WithStrictOrdering()); var pathB = await store.LoadPathAsync(convId, b); pathB.Select(x => x.Id).Should().BeEquivalentTo([root, b], opts => opts.WithStrictOrdering()); } [Fact] public async Task LoadPath_NullLeaf_PicksLatestLeafByCreatedAt() { var store = new RedbConversationStore(_fx.RouteContext); var convId = $"c-{Guid.NewGuid():N}"; var t0 = DateTime.UtcNow; var root = await store.AppendAsync(convId, null, LlmMessage.User("Q"), Meta(0, t0)); var older = await store.AppendAsync(convId, root, LlmMessage.Assistant("old"), Meta(1, t0.AddSeconds(1))); var newer = await store.AppendAsync(convId, root, LlmMessage.Assistant("new"), Meta(1, t0.AddSeconds(5))); var path = await store.LoadPathAsync(convId); path.Last().Id.Should().Be(newer); } [Fact] public async Task UserId_AuditTags_RoundTripThroughRedb() { var store = new RedbConversationStore(_fx.RouteContext); var convId = $"c-{Guid.NewGuid():N}"; var meta = new ConversationMessageMeta { CreatedAtUtc = DateTime.UtcNow, Iteration = 0, Usage = new LlmUsage(10, 5), UserId = "alice@example.com", AuditTags = new Dictionary(StringComparer.Ordinal) { ["tier"] = "gold", ["bucket"] = "A", ["region"] = "eu-west" }, FactoryName = "haiku", BaseUrl = "https://api.anthropic.com/", ProviderResponseId = "msg_round_trip_01", LatencyMs = 1234, ApiKeyFingerprint = "0123456789abcdef", RetryCount = 4 }; var id = await store.AppendAsync(convId, null, LlmMessage.User("hi"), meta); var tree = await store.LoadTreeAsync(convId); var row = tree.Should().ContainSingle(r => r.Id == id).Subject; row.Meta.UserId.Should().Be("alice@example.com"); row.Meta.AuditTags.Should().NotBeNull(); row.Meta.AuditTags!["tier"].Should().Be("gold"); row.Meta.AuditTags!["bucket"].Should().Be("A"); row.Meta.AuditTags!["region"].Should().Be("eu-west"); row.Meta.FactoryName.Should().Be("haiku"); row.Meta.BaseUrl.Should().Be("https://api.anthropic.com/"); row.Meta.ProviderResponseId.Should().Be("msg_round_trip_01"); row.Meta.LatencyMs.Should().Be(1234); row.Meta.ApiKeyFingerprint.Should().Be("0123456789abcdef"); row.Meta.RetryCount.Should().Be(4); } [Fact] public async Task AuditTags_QueryableViaDictionaryIndexer() { // Proves the REDB Pro Dictionary-on-Props LINQ-to-SQL path works for our schema: // server-side filter via `m => m.AuditTags["tier"] == "gold"` — no client-side scan. var store = new RedbConversationStore(_fx.RouteContext); var convId = $"c-{Guid.NewGuid():N}"; await store.AppendAsync(convId, null, LlmMessage.User("Q"), new ConversationMessageMeta { CreatedAtUtc = DateTime.UtcNow, Usage = LlmUsage.Empty, AuditTags = new Dictionary(StringComparer.Ordinal) { ["tier"] = "gold" } }); await store.AppendAsync(convId, null, LlmMessage.User("Q"), new ConversationMessageMeta { CreatedAtUtc = DateTime.UtcNow.AddSeconds(1), Usage = LlmUsage.Empty, AuditTags = new Dictionary(StringComparer.Ordinal) { ["tier"] = "silver" } }); var goldRows = await _fx.Redb .Query() .Where(m => m.AuditTags!["tier"] == "gold") .ToListAsync(); goldRows.Should().NotBeEmpty(); goldRows.Should().OnlyContain(r => r.Props.AuditTags!["tier"] == "gold"); } /// /// The cache counters of a turn survive the store: a cached prefix read back as zero would make every stored turn /// look like a full-price prompt to an audit or a cost report built on the history (issue #11, second half). /// [Fact] public async Task Append_LoadPath_KeepsTheCacheCounters() { var store = new RedbConversationStore(_fx.RouteContext); var convId = $"c-{Guid.NewGuid():N}"; var usage = new LlmUsage(InputTokens: 63, OutputTokens: 11, CacheCreationInputTokens: 5, CacheReadInputTokens: 172032); var user = await store.AppendAsync(convId, null, LlmMessage.User("hi"), Meta(0)); await store.AppendAsync(convId, user, LlmMessage.Assistant("hello"), new ConversationMessageMeta { CreatedAtUtc = DateTime.UtcNow.AddSeconds(1), Iteration = 1, Usage = usage }); var path = await store.LoadPathAsync(convId); path.Last().Meta.Usage.Should().Be(usage, "the whole usage of the turn comes back, cache counters included"); } } Path: redb-route/tests/redb.Route.Tests.Llm/Storage/RedbCostBudgetStoreTests.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/RedbCostBudgetStoreTests.cs ---- using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Storage.Redb; namespace redb.Route.Tests.Llm.Storage; /// Integration tests for . [Collection("StoragePro")] public sealed class RedbCostBudgetStoreTests { private readonly StorageProFixture _fx; public RedbCostBudgetStoreTests(StorageProFixture fx) => _fx = fx; [Fact] public async Task GetUsage_Empty_ReturnsZero() { var store = new RedbCostBudgetStore(_fx.RouteContext); var usage = await store.GetUsageAsync($"c-{Guid.NewGuid():N}"); usage.Should().Be(AgentUsage.Zero); } [Fact] public async Task Add_Accumulates_AcrossCalls() { var store = new RedbCostBudgetStore(_fx.RouteContext); var convId = $"c-{Guid.NewGuid():N}"; var u1 = await store.AddAsync(convId, new AgentUsage(100, 50, 0.01m)); u1.InputTokens.Should().Be(100); u1.OutputTokens.Should().Be(50); u1.CostUsd.Should().Be(0.01m); var u2 = await store.AddAsync(convId, new AgentUsage(30, 20, 0.005m)); u2.InputTokens.Should().Be(130); u2.OutputTokens.Should().Be(70); u2.CostUsd.Should().Be(0.015m); var read = await store.GetUsageAsync(convId); read.InputTokens.Should().Be(130); read.OutputTokens.Should().Be(70); read.CostUsd.Should().Be(0.015m); } [Fact] public async Task Reset_RemovesAccumulator() { var store = new RedbCostBudgetStore(_fx.RouteContext); var convId = $"c-{Guid.NewGuid():N}"; await store.AddAsync(convId, new AgentUsage(10, 5, 0.001m)); (await store.GetUsageAsync(convId)).InputTokens.Should().Be(10); await store.ResetAsync(convId); (await store.GetUsageAsync(convId)).Should().Be(AgentUsage.Zero); } [Fact] public async Task Add_PerConversation_Isolated() { var store = new RedbCostBudgetStore(_fx.RouteContext); var c1 = $"c-{Guid.NewGuid():N}"; var c2 = $"c-{Guid.NewGuid():N}"; await store.AddAsync(c1, new AgentUsage(10, 0, 0m)); await store.AddAsync(c2, new AgentUsage(99, 0, 0m)); (await store.GetUsageAsync(c1)).InputTokens.Should().Be(10); (await store.GetUsageAsync(c2)).InputTokens.Should().Be(99); } } Path: redb-route/tests/redb.Route.Tests.Llm/Storage/RedbGovernanceStorageTests.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/RedbGovernanceStorageTests.cs ---- using redb.Core.Models.Entities; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Storage.Redb; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.RedbCore; using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.Storage; /// /// redb-integration level of the phase-15 acceptance (plan §7.1): the same claims the unit tests prove /// against doubles, checked against a real database through the real stores — Persist reaches /// , a cross-run budget reaches , and audit /// reasons reach . /// /// Rows are scoped to this test by unique payloads / conversation ids / tool names: the collection /// fixture shares one database with the rest of the Storage suite and cleans up once per run. /// /// [Collection("StoragePro")] public sealed class RedbGovernanceStorageTests { private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}"""; private const string Input = """{"q":"x"}"""; private readonly StorageProFixture _fx; public RedbGovernanceStorageTests(StorageProFixture fx) => _fx = fx; // Rows are located with server-side predicates, the way the stores themselves query: the collection // fixture shares one database with the rest of the Storage suite, so pulling a table whole would read // rows this test never touched — and grow slower with every run. // // All three helpers use the OBJECT-side filter (WhereRedb): it narrows _objects and touches nothing // else. A props-typed predicate (Where) is server-side too, but it resolves through the values table, // where the condition sits above GROUP BY unless the PVT prefilter cuts the scan first. // The fixture turns that prefilter on for every Pro provider, so on this // path a mixed chain would get its value-side work narrowed too; the base-only form stays the cheapest, // which is why these helpers use it. // The tool name rides a base field on purpose: for the audit row it is the row name, for the cache the // key inside value_string, which keeps the cheap path available to dashboards too. private Task>> ReadCacheRowsAsync(string toolName) => _fx.Redb.Query() .WhereRedb(o => o.ValueString != null && o.ValueString.Contains(toolName)) .ToListAsync(); private async Task ReadBudgetAsync(string conversationId) { var key = RedbUniqueKey.Normalize(conversationId); var row = await _fx.Redb.Query() .WhereRedb(o => o.ValueUnique == key) .FirstOrDefaultAsync(); row.Should().NotBeNull("the enforcer records usage per conversation"); return row!.Props; } private async Task> ReadAuditAsync(string toolName) => await _fx.Redb.Query() // One object-side predicate only: it narrows _objects and touches nothing else. A props-typed // predicate would resolve through the values table, and with the PVT prefilter off (the shipped // default; Pro only, on all three providers) nothing cuts the set before that work. See the block comment. .WhereRedb(o => o.Name != null && o.Name.Contains(toolName)) .Select(a => a.Props) .ToListAsync(); [Fact] public async Task PersistCachingTool_WritesItsOutputIntoTheCacheScheme() { // The cache stores the DISPATCHED output, which the engine serializes as a JSON string — the row is // found by its unique tool name and then checked for the marker the reply carried. var toolName = $"persist_{Guid.NewGuid():N}"[..20]; var marker = Guid.NewGuid().ToString("N"); var provider = new FakeProvider() .EnqueueToolUse(toolName, Input, "tu_1") .EnqueueText("done"); var tool = new EchoToolRoute(toolName, "Look up a fact.", Schema, $$"""{"answer":"{{marker}}"}""", caching: ToolCachingPolicy.Persist); await using var host = LiveLlmHost.Build( toolCache: new RedbToolResultCache(_fx.RouteContext), redb: _fx.Redb) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools(toolName).MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool."); tool.CapturedInputs.Should().HaveCount(1); var rows = await ReadCacheRowsAsync(toolName); rows.Should().ContainSingle("a Persist tool's output lands in ToolCacheProps"); rows[0].Props.OutputJson.Should().Contain(marker, "the stored value is the output the tool actually produced"); } [Fact] public async Task MemoizeCachingTool_WritesNothingIntoTheCacheScheme() { var toolName = $"memo_{Guid.NewGuid():N}"[..20]; var reply = $"{{\"answer\":\"{Guid.NewGuid():N}\"}}"; var provider = new FakeProvider() .EnqueueToolUse(toolName, Input, "tu_1") .EnqueueToolUse(toolName, Input, "tu_2") .EnqueueText("done"); var tool = new EchoToolRoute(toolName, "Look up a fact.", Schema, reply, caching: ToolCachingPolicy.Memoize); await using var host = LiveLlmHost.Build( toolCache: new RedbToolResultCache(_fx.RouteContext), redb: _fx.Redb) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools(toolName).MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool twice."); tool.CapturedInputs.Should().HaveCount(1, "the second call is answered from the run-scoped memo"); (await ReadCacheRowsAsync(toolName)).Should().BeEmpty( "Memoize is served in process: the cache scheme stays untouched (decisions #5-C / #11-B)"); } [Fact] public async Task Budget_AccumulatesInCostBudgetProps_AndStopsTheNextRun() { var conversationId = $"budget-{Guid.NewGuid():N}"; var enforcer = new StoreBudgetEnforcer(new RedbCostBudgetStore(_fx.RouteContext)); var headers = new Dictionary { [LlmHeaders.ConversationId] = conversationId }; // Run 1: one iteration costs 500 input tokens against a 100-token ceiling. The post-check stops // the loop — after the usage has been recorded. var firstProvider = new FakeProvider().EnqueueText("first answer", tokensIn: 500, tokensOut: 5); await using (var host = LiveLlmHost.Build(budget: enforcer, redb: _fx.Redb) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = firstProvider })) { await host.StartAsync(r => r.From("direct:agent") .To(LlmDsl.Factory("demo").ConversationFromHeader().Budget(inputTokens: 100).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "hello", headers); } firstProvider.CallCount.Should().Be(1); (await ReadBudgetAsync(conversationId)).InputTokens.Should().Be(500, "the run's usage is accumulated per conversation in CostBudgetProps"); // Run 2, same conversation, nothing scripted: a provider call would be visible in CallCount. var secondProvider = new FakeProvider(); await using (var host = LiveLlmHost.Build(budget: enforcer, redb: _fx.Redb) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = secondProvider })) { await host.StartAsync(r => r.From("direct:agent") .To(LlmDsl.Factory("demo").ConversationFromHeader().Budget(inputTokens: 100).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "hello again", headers); } secondProvider.CallCount.Should().Be(0, "the ceiling is checked against the conversation's accumulated usage, so the run stops before spending"); (await ReadBudgetAsync(conversationId)).InputTokens.Should().Be(500, "a run stopped by the pre-check adds nothing"); } [Fact] public async Task AuditRow_RecordsTheClaimsDenial() { var toolName = $"denied_{Guid.NewGuid():N}"[..20]; var provider = new FakeProvider() .EnqueueToolUse(toolName, Input, "tu_1") .EnqueueText("done"); var tool = new EchoToolRoute(toolName, "Look up a fact.", Schema, """{"answer":"42"}""", requiredClaims: ["orders:read"]); // The exchange carries no principal, so the claims requirement cannot be verified — and the // denial must be visible in the audit rows, not only in the run's result. await using var host = LiveLlmHost.Build( observer: new RedbAuditObserver(_fx.RouteContext), claimsSource: new ExchangePrincipalClaimsSource(), redb: _fx.Redb) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools(toolName).MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool."); tool.CapturedInputs.Should().BeEmpty(); var rows = await ReadAuditAsync(toolName); rows.Should().ContainSingle("a denied call is an auditable event"); rows[0].Outcome.Should().Be("skipped"); rows[0].SkipReason.Should().StartWith(ToolSkipReasons.ClaimsMissing, "the audit row carries the machine-readable reason, including which claims were missing"); } [Fact] public async Task AuditRows_RecordASuccessAndACacheHit() { var toolName = $"cached_{Guid.NewGuid():N}"[..20]; var provider = new FakeProvider() .EnqueueToolUse(toolName, Input, "tu_1") .EnqueueToolUse(toolName, Input, "tu_2") .EnqueueText("done"); var tool = new EchoToolRoute(toolName, "Look up a fact.", Schema, """{"answer":"42"}""", caching: ToolCachingPolicy.Memoize); await using var host = LiveLlmHost.Build( observer: new RedbAuditObserver(_fx.RouteContext), redb: _fx.Redb) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").Tools(toolName).MaxIterations(4).AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "Call the tool twice."); var rows = await ReadAuditAsync(toolName); rows.Should().HaveCount(2, "both calls are audited: the executed one and the cache hit"); rows.Should().Contain(r => r.Outcome == "success"); rows.Should().Contain(r => r.Outcome == "skipped" && r.SkipReason == ToolSkipReasons.CacheHit); } /// /// The third skip reason, audited. The idempotency store itself is a double here (the test drives a replay through it), but the row under test — the /// one the audit observer writes — is real. /// [Fact] public async Task AuditRow_RecordsAnIdempotencyHit() { var toolName = $"mut_{Guid.NewGuid():N}"[..20]; var conversationId = $"idem-{Guid.NewGuid():N}"; var provider = new FakeProvider() .EnqueueToolUse(toolName, Input, "tu_replay") .EnqueueText("done") .EnqueueToolUse(toolName, Input, "tu_replay") .EnqueueText("done"); var tool = new EchoToolRoute(toolName, "Mutate something.", Schema, """{"ok":true}""", sideEffect: ToolSideEffect.Mutating); await using var host = LiveLlmHost.Build( observer: new RedbAuditObserver(_fx.RouteContext), idempotency: new SpyIdempotencyStore(), redb: _fx.Redb) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From("direct:agent") .To(LlmDsl.Factory("demo").ConversationFromHeader().Tools(toolName).MaxIterations(4).AsUri()) .To("mock:done")); var headers = new Dictionary { [LlmHeaders.ConversationId] = conversationId }; await host.SendAsync("direct:agent", "Mutate.", headers); await host.SendAsync("direct:agent", "Mutate.", headers); var rows = await ReadAuditAsync(toolName); rows.Should().Contain(r => r.Outcome == "skipped" && r.SkipReason == ToolSkipReasons.IdempotencyHit, "the replay the idempotency store answered is audited under its own reason"); } } Path: redb-route/tests/redb.Route.Tests.Llm/Storage/RedbScopePerCallTests.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/RedbScopePerCallTests.cs ---- using System.Collections.Concurrent; using System.Reflection; using System.Runtime.ExceptionServices; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Observability; using redb.Route.Llm.Storage.Redb; using redb.Route.Llm.Storage.Redb.Schemas; namespace redb.Route.Tests.Llm.Storage; /// /// The budget and the audit observer run without an exchange, and many agent runs call them at once. Each call /// opens a redb scope of its own and releases it, so concurrent runs never share one instance and one connection /// (a shared connection refuses the second of two simultaneous commands). /// [Collection("StoragePro")] public sealed class RedbScopePerCallTests { private readonly StorageProFixture _fx; public RedbScopePerCallTests(StorageProFixture fx) => _fx = fx; /// A scope handed out by : releases the real one once and remembers it did. public sealed class TrackedScope(RedbScope real) : IServiceScope, IAsyncDisposable { private int _released; public bool Released => Volatile.Read(ref _released) == 1; public IServiceProvider ServiceProvider => real.ServiceProvider!; public void Dispose() { if (Interlocked.Exchange(ref _released, 1) == 0) real.Dispose(); } public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _released, 1) == 0) await real.DisposeAsync(); } } /// /// Stands in for the host's redb service: every call passes through to the real service, and every scope opened /// from it is recorded with the service it handed out. /// public class ScopeRecordingRedb : DispatchProxy { private readonly ConcurrentQueue<(IRedbService Service, TrackedScope Scope)> _opened = new(); private IRedbService _inner = null!; public (IRedbService Service, TrackedScope Scope)[] Opened => _opened.ToArray(); public static (IRedbService Proxy, ScopeRecordingRedb Recorder) Over(IRedbService inner) { var proxy = Create(); var recorder = (ScopeRecordingRedb)(object)proxy; recorder._inner = inner; return (proxy, recorder); } protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) { if (targetMethod!.Name == nameof(IRedbScopeSource.CreateScope)) { var real = _inner.CreateScope(); var tracked = new TrackedScope(real); _opened.Enqueue((real.Service, tracked)); return new RedbScope(real.Service, tracked); } try { return targetMethod.Invoke(_inner, args); } catch (TargetInvocationException ex) when (ex.InnerException is not null) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw; } } } private (RouteContext Context, ScopeRecordingRedb Recorder) HostWithRecordingRedb() { var (proxy, recorder) = ScopeRecordingRedb.Over(_fx.Redb); var context = new RouteContext(); context.AddService(typeof(IRedbService), proxy); return (context, recorder); } private static void EachCallOwnedItsScope((IRedbService Service, TrackedScope Scope)[] opened, int calls) { opened.Should().HaveCount(calls, "every call without an exchange opens a scope of its own"); opened.Select(o => o.Service).Distinct().Should().HaveCount(calls, "concurrent callers never share a service"); opened.Should().OnlyContain(o => o.Scope.Released, "each call releases the scope it opened"); } [Fact] public async Task Budget_WithoutExchange_EachCallOpensAndReleasesItsOwnScope() { var (context, recorder) = HostWithRecordingRedb(); var enforcer = new StoreBudgetEnforcer(new RedbCostBudgetStore(context)); var budget = new AgentBudget(MaxInputTokens: 1_000_000, MaxOutputTokens: 1_000_000, MaxCostUsd: 0m); var convId = $"c-{Guid.NewGuid():N}"; // Two runs of one conversation check the budget at the same time: readers, safe on every provider. await Task.WhenAll( enforcer.PreCheckAsync(convId, budget, AgentUsage.Zero).AsTask(), enforcer.PreCheckAsync(convId, budget, AgentUsage.Zero).AsTask()); EachCallOwnedItsScope(recorder.Opened, calls: 2); // The write path goes through its own scope too. await enforcer.RecordAndCheckAsync(convId, budget, new AgentUsage(3, 4, 0m), new AgentUsage(3, 4, 0m)); EachCallOwnedItsScope(recorder.Opened, calls: 3); } private static AgentToolInvocationContext Invocation(string convId, string toolUseId) => new() { Run = new AgentRunContext { ConversationId = convId, FactoryName = "test", ProviderId = "test", ModelId = "test-model", ExchangeId = $"x-{Guid.NewGuid():N}" }, Tool = new LlmToolCapability { Name = "order_lookup", Description = "t", InputSchema = "{}" }, InputJson = """{"orderId":"42"}""", OutputJson = """{"status":"shipped"}""", ToolUseId = toolUseId, Duration = TimeSpan.FromMilliseconds(5) }; [Fact] public async Task Audit_EachInvocationOpensAndReleasesItsOwnScope() { var (context, recorder) = HostWithRecordingRedb(); var observer = new RedbAuditObserver(context); var convId = $"c-{Guid.NewGuid():N}"; // Two runs record a tool call at the same time. SQLite has one writer, and two writers racing in a test // deadlock on the busy handler, so there the calls run one after the other; every call still owns a scope. if (_fx.Provider == "sqlite") { await observer.OnToolInvokedAsync(Invocation(convId, "tu-1")); await observer.OnToolInvokedAsync(Invocation(convId, "tu-2")); } else { await Task.WhenAll( observer.OnToolInvokedAsync(Invocation(convId, "tu-1")), observer.OnToolInvokedAsync(Invocation(convId, "tu-2"))); } EachCallOwnedItsScope(recorder.Opened, calls: 2); var rows = await _fx.Redb.Query() .Where(p => p.ConversationId == convId) .ToListAsync(); rows.Should().HaveCount(2, "both audit rows are written through their own scopes"); } } 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); } } Path: redb-route/tests/redb.Route.Tests.Llm/Storage/StorageProFixture.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/StorageProFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Pro.Extensions; using redb.MSSql.Pro.Extensions; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Storage.Redb.Schemas; using redb.SQLite.Pro.Extensions; namespace redb.Route.Tests.Llm.Storage; /// /// Provider-substituted Pro fixture for the redb.Route.Llm storage integration tests: one /// fixture, one set of test classes, the provider slid underneath by REDB_PROVIDER /// (sqlite — default, since it needs no stand and is where the dialect's own planner guards /// matter — or postgres / mssql), following the redb.Tests.Integration matrix convention. /// Uses the Pro free tier (1024 queries, no JWT license required). /// /// Cleanup is scoped to the LLM schemes only — never DELETE FROM _objects, /// which would nuke unrelated data shared with other test runs against the same DB. /// We enumerate rows of each LLM *Props scheme through the redb query API /// and remove them via the bulk DeleteAsync(ids) primitive (which cascades /// to _values and _tree). /// /// public sealed class StorageProFixture : IAsyncLifetime { public IRedbService Redb { get; private set; } = null!; public ServiceProvider ServiceProvider { get; private set; } = null!; public IServiceScopeFactory ScopeFactory => ServiceProvider.GetRequiredService(); /// /// Real with the fixture's /// registered as the default unnamed instance. Stores resolve it via /// context.GetRedbService(name, exchange) — when name is empty /// (the test path), the extension falls back to context.GetService<IRedbService>() /// which returns the fixture's redb. No per-exchange scoping is needed for /// these unit tests — they call store methods with exchange: null. /// public IRouteContext RouteContext { get; private set; } = null!; /// Which backend this run rides on: sqlite (default), postgres or mssql. public string Provider { get; } = Environment.GetEnvironmentVariable("REDB_PROVIDER")?.ToLowerInvariant() is { Length: > 0 } p ? p : "sqlite"; private static string RequireConnectionString(IConfiguration config, string name) => config.GetConnectionString(name) ?? throw new InvalidOperationException($"ConnectionStrings:{name} missing in appsettings.json"); public async Task InitializeAsync() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var services = new ServiceCollection(); services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); services.AddRedbPro(options => { // The provider is slid underneath, not copy-pasted around: the same test classes run // against whichever backend the environment names. var builder = Provider switch { "mssql" => options.UseMsSql(global::redb.Route.Tests.Shared.TestDatabases.MsSql(RequireConnectionString(config, "MsSql"))), "postgres" => options.UsePostgres(global::redb.Route.Tests.Shared.TestDatabases.Postgres(RequireConnectionString(config, "Postgres"))), // SQLite needs no stand: the file lives next to the test assembly. Full provider parity // with the other two, so the same claims are checked on it rather than assumed. "sqlite" => options.UseSqlite(RequireConnectionString(config, "Sqlite")), _ => throw new InvalidOperationException( $"REDB_PROVIDER '{Provider}' is not one of: postgres, mssql, sqlite.") }; builder.Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; c.SkipHashValidationOnCacheCheck = false; c.EnablePropsCache = false; // PVT prefilter: a cutting step that narrows the value-side scan before the aggregation. // It is in all three Pro providers, so it is on here for all // three — SQLite included, whose dialect guards the planner itself (SqlitePrefilterGuards). c.EnablePvtPrefilter = true; }); // Free tier: 1024 queries — no .WithLicense() needed. }); ServiceProvider = services.BuildServiceProvider(); Redb = ServiceProvider.GetRequiredService(); RouteContext = new RouteContext(); RouteContext.SetServiceProvider(ServiceProvider); RouteContext.AddService(typeof(IRedbService), Redb); try { await Redb.InitializeAsync(ensureCreated: true); } catch { await Redb.InitializeAsync(); } await SyncSchemes(); await Cleanup(); } private async Task SyncSchemes() { await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); } /// /// Removes only LLM-scheme rows; never touches unrelated objects. /// DeleteWithPurgeAsync cascades automatically — soft-delete on a /// conversation root pulls every descendant under /// the same trash container, so we only enumerate the roots / flat tables. /// public async Task Cleanup() { var ids = new List(); ids.AddRange((await Redb.Query().ToListAsync()).Select(o => o.id)); ids.AddRange((await Redb.Query().ToListAsync()).Select(o => o.id)); ids.AddRange((await Redb.Query().ToListAsync()).Select(o => o.id)); ids.AddRange((await Redb.Query().ToListAsync()).Select(o => o.id)); ids.AddRange((await Redb.Query().ToListAsync()).Select(o => o.id)); ids.AddRange((await Redb.Query().ToListAsync()).Select(o => o.id)); if (ids.Count > 0) await Redb.DeleteWithPurgeAsync(ids); } public async Task DisposeAsync() { RouteContext?.Dispose(); if (ServiceProvider is IAsyncDisposable ad) await ad.DisposeAsync(); else ServiceProvider?.Dispose(); } } [CollectionDefinition("StoragePro")] public sealed class StorageProCollection : ICollectionFixture { } Path: redb-route/tests/redb.Route.Tests.Llm/Storage/ThinkingBlockStorageTests.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/ThinkingBlockStorageTests.cs ---- using System.Net; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Storage.Redb; using redb.Route.Llm.Storage.Redb.Schemas; namespace redb.Route.Tests.Llm.Storage; /// /// Wave 16.2: the thinking block gets a place in the redb schema, so a signed block survives /// save -> load — and a branch off the node it sits on — and comes back to the provider exactly as /// it went in. /// /// The thought lives in a field of its own, with the signature and the redacted payload beside it; /// belongs to the text kind. /// /// [Collection("StoragePro")] public sealed class ThinkingBlockStorageTests { private const string Thought = "the order table is the source of truth, check it first"; private const string Signature = "sig-9f3c-4a17-b0e2-8d55"; private const string Model = "claude-sonnet-4-6"; private readonly StorageProFixture _fx; public ThinkingBlockStorageTests(StorageProFixture fx) => _fx = fx; private static LlmMessage Ask() => LlmMessage.User("status of order 42?"); /// The assistant turn as the provider issued it: the signed reasoning and the answer. private static LlmMessage Answer() => new() { Role = "assistant", Content = [ new LlmThinkingBlock(Thought, Signature), new LlmTextBlock("shipped") ] }; private static ConversationMessageMeta Meta(string convId, string? providerId = "anthropic", int iteration = 1) => new() { CreatedAtUtc = DateTime.UtcNow, Iteration = iteration, ProviderId = providerId, ModelId = Model, Usage = new LlmUsage(10, 5), // A server-side handle on this conversation's rows, so a raw read below cannot pick up // another test class's data (the dictionary-indexer query the store tests already use). AuditTags = new Dictionary(StringComparer.Ordinal) { ["conv"] = convId } }; /// Appends the prompt and the answer; returns the conversation id and the answer node id. private static async Task<(string ConversationId, string AnswerId)> ConversationAsync( RedbConversationStore store, LlmMessage? answer = null) { var convId = $"c-{Guid.NewGuid():N}"; var promptId = await store.AppendAsync(convId, null, Ask(), Meta(convId, providerId: null, iteration: 0)); var answerId = await store.AppendAsync(convId, promptId, answer ?? Answer(), Meta(convId)); return (convId, answerId); } /// Reads the stored rows of one conversation — the schema itself, not the store's mapping. private Task>> RowsAsync(string convId) => _fx.Redb.Query() .Where(m => m.AuditTags!["conv"] == convId) .ToListAsync(); [Fact] public async Task Store_ThinkingBlock_TextIsNull() { var store = new RedbConversationStore(_fx.RouteContext); var (convId, _) = await ConversationAsync(store); var rows = await RowsAsync(convId); var block = rows .SelectMany(r => r.Props.Content) .Should().ContainSingle(b => b.Kind == "thinking").Subject; block.ThinkingText.Should().Be(Thought); block.Signature.Should().Be(Signature); block.Text.Should().BeNull("Text belongs to the text kind; the thought has a field of its own"); } [Fact] public async Task RedactedThinking_SurvivesRoundTrip() { const string Payload = "ErUBCkYIBRgCIkA5Zm9wYXF1ZS1lbmNyeXB0ZWQtYmxvYg=="; var redacted = new LlmMessage { Role = "assistant", Content = [ new LlmThinkingBlock(string.Empty, RedactedData: Payload), new LlmTextBlock("shipped") ] }; var store = new RedbConversationStore(_fx.RouteContext); var (convId, _) = await ConversationAsync(store, redacted); var block = (await store.LoadPathAsync(convId))[^1].Message.Content .OfType().Should().ContainSingle().Subject; block.IsRedacted.Should().BeTrue(); block.RedactedData.Should().Be(Payload, "the payload is what travels back — it is not readable data"); block.Text.Should().BeEmpty(); block.Signature.Should().BeNull("a redacted block carries no text to authenticate"); } [Fact] public async Task Branch_FromThinkingNode_KeepsBlock() { var store = new RedbConversationStore(_fx.RouteContext); var convId = $"c-{Guid.NewGuid():N}"; var promptId = await store.AppendAsync(convId, null, Ask(), Meta(convId, providerId: null, iteration: 0)); var thinkingNode = await store.AppendAsync(convId, promptId, Answer(), Meta(convId)); var regenerate = await store.AppendAsync(convId, thinkingNode, LlmMessage.Assistant("still shipped"), Meta(convId)); var followUp = await store.AppendAsync(convId, thinkingNode, LlmMessage.User("and order 43?"), Meta(convId, providerId: null, iteration: 2)); // Both branches hang off the node that carries the reasoning, and the block belongs to that // node — so it is on every path that runs through it. foreach (var leaf in new[] { regenerate, followUp }) { var path = await store.LoadPathAsync(convId, leaf); var node = path.Should().ContainSingle(n => n.Id == thinkingNode).Subject; node.Message.Content.OfType().Should().ContainSingle() .Which.Signature.Should().Be(Signature); } } [Fact] public async Task SchemaSync_ThinkingFields_AreAdded() { // Syncing again over an existing schema neither throws nor rewrites anything. await _fx.Redb.SyncSchemeAsync(); await _fx.Redb.SyncSchemeAsync(); var store = new RedbConversationStore(_fx.RouteContext); var (convId, _) = await ConversationAsync(store); var rows = await RowsAsync(convId); var assistant = rows.Should().ContainSingle(r => r.Props.Role == "assistant").Subject; assistant.Props.Content.Single(b => b.Kind == "thinking").ThinkingText.Should().Be(Thought); // A row that carries no thinking — the shape every row had before this wave — reads back // unchanged: the new fields are simply null there. var prompt = rows.Should().ContainSingle(r => r.Props.Role == "user").Subject; var promptBlock = prompt.Props.Content.Should().ContainSingle().Subject; promptBlock.Kind.Should().Be("text"); promptBlock.Text.Should().Be("status of order 42?"); promptBlock.ThinkingText.Should().BeNull(); promptBlock.Signature.Should().BeNull(); promptBlock.RedactedData.Should().BeNull(); } /// Captures the raw request body the provider puts on the wire. private sealed class BodyCapturingHandler : HttpMessageHandler { public string? LastRawBody { get; private set; } protected override async Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { LastRawBody = await request.Content!.ReadAsStringAsync(cancellationToken); return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent( """ {"id":"msg_1","content":[{"type":"text","text":"ok"}], "stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}} """) }; } } private static async Task WireBodyAsync(params LlmMessage[] messages) { var handler = new BodyCapturingHandler(); var provider = new AnthropicProvider( new LlmConnectionFactory { Provider = "anthropic", ModelId = Model, ApiKey = "test-key" }, new HttpClient(handler)); await provider.CompleteAsync(new LlmRequest { Messages = messages }); return handler.LastRawBody!; } [Fact] public async Task Conversation_WithThinking_ReplayedRequest_IsByteIdentical() { // What the second iteration of a tool loop sends: the prompt plus the assistant turn that // carries the reasoning. var inRun = await WireBodyAsync(Ask(), Answer()); // The same turn now comes back from the store, and the request is rebuilt from it. var store = new RedbConversationStore(_fx.RouteContext); var (convId, _) = await ConversationAsync(store); var loaded = await store.LoadPathAsync(convId); var replayed = await WireBodyAsync(loaded.Select(n => n.Message).ToArray()); inRun.Should().Contain("\"type\":\"thinking\""); inRun.Should().Contain(Signature); replayed.Should().Be(inRun, "a block that comes back short of a byte is a 400 waiting to happen — the signature covers the text"); } } Path: redb-route/tests/redb.Route.Tests.Llm/Storage/UniqueLookupTests.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/UniqueLookupTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Providers; using redb.Route.Llm.Storage.Redb; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.RedbCore; namespace redb.Route.Tests.Llm.Storage; /// /// Lookups read the unique key, not value_string, without a data migration. Every write carries /// ValueUnique = RedbUniqueKey.Normalize(key); the reads used to search /// value_string — an unindexed scan on MSSQL, and a different column than the one the /// barrier converges on. /// /// Two behaviors per store, both through the public API. A: a row whose unique key matches /// but whose value_string diverged (what the loser of a race adopts) must be FOUND — red on /// the old lookups. B: a legacy row carrying the key only in value_string, no unique /// value, is deliberately INVISIBLE — the owner declined every form of migration, including lazy /// adoption, so this pins the accepted consequence rather than an accident. The conversation store /// has only B: its create-barrier converges the A case to the same outcome either way. /// /// [Collection("StoragePro")] public sealed class UniqueLookupTests { private readonly StorageProFixture _fx; public UniqueLookupTests(StorageProFixture fx) => _fx = fx; // ── Approval ── [Fact] public async Task Approval_IsFoundByItsUniqueKey_WhenValueStringDiverged() { var id = $"ul-appr-{Guid.NewGuid():N}"; await _fx.Redb.SaveAsync(new RedbObject { value_string = $"diverged-{id}", ValueUnique = id, Props = new ApprovalProps { ToolName = "t", InputJson = "{}", DecidedAtUtc = DateTimeOffset.UtcNow } }); var found = await new RedbApprovalStore(_fx.RouteContext).FindAsync(id); found.Should().NotBeNull("the unique key is the truth the write barrier converges on"); } [Fact] public async Task Approval_LegacyRowWithoutUniqueKey_IsInvisible() { var id = $"ul-appr-legacy-{Guid.NewGuid():N}"; await _fx.Redb.SaveAsync(new RedbObject { value_string = id, Props = new ApprovalProps { ToolName = "t", InputJson = "{}", DecidedAtUtc = DateTimeOffset.UtcNow } }); var found = await new RedbApprovalStore(_fx.RouteContext).FindAsync(id); found.Should().BeNull("no migration in any form is the owner's decision, this pins it"); } // ── Batch ── [Fact] public async Task Batch_IsFoundByItsUniqueKey_WhenValueStringDiverged() { var id = $"ul-batch-{Guid.NewGuid():N}"; await _fx.Redb.SaveAsync(new RedbObject { value_string = $"diverged-{id}", ValueUnique = id, Props = new LlmBatchProps { ProviderId = "anthropic", Status = "submitted", SubmittedAtUtc = DateTimeOffset.UtcNow } }); var found = await new RedbBatchStore(_fx.RouteContext).GetAsync(id); found.Should().NotBeNull(); } [Fact] public async Task Batch_LegacyRowWithoutUniqueKey_IsInvisible() { var id = $"ul-batch-legacy-{Guid.NewGuid():N}"; await _fx.Redb.SaveAsync(new RedbObject { value_string = id, Props = new LlmBatchProps { ProviderId = "anthropic", Status = "submitted", SubmittedAtUtc = DateTimeOffset.UtcNow } }); (await new RedbBatchStore(_fx.RouteContext).GetAsync(id)).Should().BeNull(); } // ── EvalRun ── [Fact] public async Task EvalRun_IsFoundByItsUniqueKey_WhenValueStringDiverged() { var id = $"ul-eval-{Guid.NewGuid():N}"; await _fx.Redb.SaveAsync(new RedbObject { value_string = $"diverged-{id}", ValueUnique = id, Props = new EvalRunProps { RunId = id, Scenario = "s", AgentFingerprint = "fp", CreatedAtUtc = DateTimeOffset.UtcNow } }); (await new RedbEvalRunStore(_fx.RouteContext).GetAsync(id)).Should().NotBeNull(); } [Fact] public async Task EvalRun_LegacyRowWithoutUniqueKey_IsInvisible() { var id = $"ul-eval-legacy-{Guid.NewGuid():N}"; await _fx.Redb.SaveAsync(new RedbObject { value_string = id, Props = new EvalRunProps { RunId = id, Scenario = "s", AgentFingerprint = "fp", CreatedAtUtc = DateTimeOffset.UtcNow } }); (await new RedbEvalRunStore(_fx.RouteContext).GetAsync(id)).Should().BeNull(); } // ── Prompt templates ── [Fact] public async Task Template_IsFoundByItsUniqueKey_WhenValueStringDiverged() { var name = $"ul-tpl-{Guid.NewGuid():N}"; var key = $"{name}@1.0"; await _fx.Redb.SaveAsync(new RedbObject { value_string = $"diverged-{key}", ValueUnique = key, Props = new PromptTemplateProps { Name = name, Version = "1.0", Body = "B", CreatedAtUtc = DateTimeOffset.UtcNow } }); var found = await new RedbPromptTemplateRegistry(_fx.RouteContext).GetAsync(name, "1.0"); found.Should().NotBeNull(); } [Fact] public async Task Template_LegacyRowWithoutUniqueKey_IsInvisible() { var name = $"ul-tpl-legacy-{Guid.NewGuid():N}"; var key = $"{name}@1.0"; await _fx.Redb.SaveAsync(new RedbObject { value_string = key, Props = new PromptTemplateProps { Name = name, Version = "1.0", Body = "B", CreatedAtUtc = DateTimeOffset.UtcNow } }); (await new RedbPromptTemplateRegistry(_fx.RouteContext).GetAsync(name, "1.0")).Should().BeNull(); } // ── Tool result cache ── [Fact] public async Task Cache_IsFoundByItsUniqueKey_WhenValueStringDiverged() { var key = $"ul-cache-{Guid.NewGuid():N}"; await _fx.Redb.SaveAsync(new RedbObject { value_string = $"diverged-{key}", ValueUnique = key, Props = new ToolCacheProps { OutputJson = """{"v":"x"}""", CreatedAtUtc = DateTimeOffset.UtcNow } }); var hit = await new RedbToolResultCache(_fx.RouteContext).GetAsync(key); hit.Should().Be("""{"v":"x"}"""); } [Fact] public async Task Cache_LegacyRowWithoutUniqueKey_IsInvisible() { var key = $"ul-cache-legacy-{Guid.NewGuid():N}"; await _fx.Redb.SaveAsync(new RedbObject { value_string = key, Props = new ToolCacheProps { OutputJson = """{"v":"x"}""", CreatedAtUtc = DateTimeOffset.UtcNow } }); (await new RedbToolResultCache(_fx.RouteContext).GetAsync(key)).Should().BeNull(); } [Fact] public async Task Cache_LookupNormalizesTheKey_LikeTheWriteDoes() { // A key over the storage limit is truncated+hashed by RedbUniqueKey on write; the lookup // must run the same normalization or long keys written by the store become unfindable. var longKey = $"ul-cache-long-{Guid.NewGuid():N}-" + new string('x', 600); await _fx.Redb.SaveAsync(new RedbObject { value_string = "diverged-long", ValueUnique = RedbUniqueKey.Normalize(longKey), Props = new ToolCacheProps { OutputJson = """{"v":"long"}""", CreatedAtUtc = DateTimeOffset.UtcNow } }); var hit = await new RedbToolResultCache(_fx.RouteContext).GetAsync(longKey); hit.Should().Be("""{"v":"long"}"""); } // ── Knowledge ── [Fact] public async Task Knowledge_DeleteReachesTheRow_ByItsUniqueKey() { var chunkId = $"ul-know-{Guid.NewGuid():N}"; await _fx.Redb.SaveAsync(new RedbObject { value_string = $"diverged-{chunkId}", ValueUnique = chunkId, note = """{"text":"old"}""" }); await new RedbKnowledgeStore(_fx.RouteContext).DeleteAsync(chunkId); var left = await _fx.Redb.Query() .WhereRedb(o => o.ValueUnique == chunkId).ToListAsync(); left.Should().BeEmpty("delete must find the row the write barrier owns"); } [Fact] public async Task Knowledge_LegacyRowWithoutUniqueKey_IsInvisibleToDelete() { var chunkId = $"ul-know-legacy-{Guid.NewGuid():N}"; await _fx.Redb.SaveAsync(new RedbObject { value_string = chunkId, note = """{"text":"old"}""" }); await new RedbKnowledgeStore(_fx.RouteContext).DeleteAsync(chunkId); var left = await _fx.Redb.Query() .WhereRedb(o => o.ValueString == chunkId).ToListAsync(); left.Should().HaveCount(1, "the legacy row stays as it lay — no migration, no adoption"); } // ── Cost budget ── [Fact] public async Task Budget_IsReadByItsUniqueKey_WhenValueStringDiverged() { var convId = $"ul-budget-{Guid.NewGuid():N}"; await _fx.Redb.SaveAsync(new RedbObject { value_string = $"diverged-{convId}", ValueUnique = convId, Props = new CostBudgetProps { InputTokens = 7, OutputTokens = 3, CostUsd = 0.01m, UpdatedAtUtc = DateTimeOffset.UtcNow } }); var usage = await new RedbCostBudgetStore(_fx.RouteContext).GetUsageAsync(convId); usage.InputTokens.Should().Be(7); usage.OutputTokens.Should().Be(3); } [Fact] public async Task Budget_LegacyRowWithoutUniqueKey_ReadsAsZero() { var convId = $"ul-budget-legacy-{Guid.NewGuid():N}"; await _fx.Redb.SaveAsync(new RedbObject { value_string = convId, Props = new CostBudgetProps { InputTokens = 9, OutputTokens = 9, CostUsd = 0.09m, UpdatedAtUtc = DateTimeOffset.UtcNow } }); var usage = await new RedbCostBudgetStore(_fx.RouteContext).GetUsageAsync(convId); usage.InputTokens.Should().Be(0, "legacy budget rows are accepted as lost — owner decision"); } // ── Tool idempotency ── [Fact] public async Task Idempotency_CompletedRowIsAHit_ByItsUniqueKey() { var convId = $"ul-idem-{Guid.NewGuid():N}"; const string toolUseId = "tu-1"; var key = $"llm-tool:{convId}:{toolUseId}"; await _fx.Redb.SaveAsync(new RedbObject { value_string = $"diverged-{key}", ValueUnique = key, Props = new ToolIdempotencyProps { OutputJson = """{"v":"done"}""", CreatedAtUtc = DateTimeOffset.UtcNow } }); var store = new RedbToolIdempotencyStore(_fx.RouteContext); (await store.TryReserveAsync(convId, toolUseId)).IsNew.Should().BeTrue(); var reservation = await store.TryReserveAsync(convId, toolUseId); reservation.IsNew.Should().BeFalse(); reservation.CachedOutputJson.Should().Be("""{"v":"done"}""", "the completed row owns the unique key and must be seen"); } [Fact] public async Task Idempotency_LegacyCompletedRow_IsInvisible() { var convId = $"ul-idem-legacy-{Guid.NewGuid():N}"; const string toolUseId = "tu-1"; var key = $"llm-tool:{convId}:{toolUseId}"; await _fx.Redb.SaveAsync(new RedbObject { value_string = key, Props = new ToolIdempotencyProps { OutputJson = """{"v":"done"}""", CreatedAtUtc = DateTimeOffset.UtcNow } }); var reservation = await new RedbToolIdempotencyStore(_fx.RouteContext).TryReserveAsync(convId, toolUseId); reservation.IsNew.Should().BeTrue("the legacy row has no unique key and is deliberately unseen"); } // ── Conversation root (B only: the create-barrier converges the A case either way) ── [Fact] public async Task ConversationRoot_LegacyRowWithoutUniqueKey_GetsAFreshRootBesideIt() { var convId = $"ul-conv-legacy-{Guid.NewGuid():N}"; await _fx.Redb.SaveAsync(new RedbObject { value_string = convId, Props = new ConversationProps { Status = "active", StartedAtUtc = DateTimeOffset.UtcNow, LastActivityAtUtc = DateTimeOffset.UtcNow } }); await new RedbConversationStore(_fx.RouteContext) .AppendAsync(convId, null, LlmMessage.User("hi"), new ConversationMessageMeta { CreatedAtUtc = DateTime.UtcNow, Iteration = 0, Usage = new LlmUsage(1, 1) }); var byUnique = await _fx.Redb.Query() .WhereRedb(o => o.ValueUnique == convId).ToListAsync(); var byString = await _fx.Redb.Query() .WhereRedb(o => o.ValueString == convId).ToListAsync(); byUnique.Should().HaveCount(1, "the append minted a proper unique-keyed root"); // Two rows carry the raw key in value_string now: the untouched legacy root and the fresh // root (which writes both columns). The legacy one is recognisable by its empty unique. byString.Should().HaveCount(2, "the legacy root stays as it lay, unadopted, beside the fresh one"); var legacy = byString.Single(o => string.IsNullOrEmpty(o.value_unique)); byUnique[0].id.Should().NotBe(legacy.id, "no lazy adoption: the legacy root is not the one the store now works under"); } // ── Key-case collation: a real, live cross-provider divergence, pinned ── [Fact] public async Task KeyCase_CharacterizesTheProviderCollation() { // Checked live on the stend: MSSQL's _value_unique is SQL_Latin1_General_CP1_CI_AS, so // keys differing only by case are ONE key there — they find each other and collide on the // unique index. Postgres compares byte-wise, so they are TWO keys. Neither side is wrong; // what would be wrong is not knowing. This test documents the divergence per provider so a // schema change on either side (a COLLATE on the column, say) shows up here first. var stem = $"ul-case-{Guid.NewGuid():N}"; var cache = new RedbToolResultCache(_fx.RouteContext); await cache.SetAsync(stem + "-KEY", """{"v":"upper"}"""); var crossRead = await cache.GetAsync(stem + "-key"); await cache.SetAsync(stem + "-key", """{"v":"lower"}"""); var upperAfter = await cache.GetAsync(stem + "-KEY"); if (_fx.Provider == "mssql") { crossRead.Should().Be("""{"v":"upper"}""", "CI collation: the lower-case probe finds the upper-case row"); upperAfter.Should().Be("""{"v":"lower"}""", "CI collation: the second set lands on the same single row"); } else { crossRead.Should().BeNull("byte-wise comparison: case-differing keys are distinct"); upperAfter.Should().Be("""{"v":"upper"}""", "the lower-case set created its own row and left this one alone"); } } } Path: redb-route/tests/redb.Route.Tests.Llm/Storage/UniqueRaceBarrierTests.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/UniqueRaceBarrierTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Llm.Abstractions.Tools; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Storage; using redb.Route.Llm.Providers; using redb.Route.Llm.Storage.Redb; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.RedbCore.Extensions; namespace redb.Route.Tests.Llm.Storage; /// /// Race barriers of the redb-backed LLM stores: every business key also rides in /// _objects._value_unique, so concurrent creators of one key converge on a /// single row instead of splitting it. /// /// Deterministic tests replay the TOCTOU window synthetically: a "winner" row is /// pre-created holding the unique key under a DIFFERENT value_string, so the /// store's lookup misses it and the insert hits the unique index — exactly what the /// loser of a real race sees. Parallel tests then drive real races. All keys here /// are short, so the stored unique key equals the raw key verbatim. /// /// [Collection("StoragePro")] public sealed class UniqueRaceBarrierTests { private readonly StorageProFixture _fx; public UniqueRaceBarrierTests(StorageProFixture fx) => _fx = fx; // ── helpers ───────────────────────────────────────────────────── /// All rows of the scheme reachable by the key — via value_string or the unique key. private async Task> KeyRowIdsAsync(string key) where TProps : class, new() { var byString = await _fx.Redb.Query().WhereRedb(o => o.ValueString == key).ToListAsync(); var byUnique = await _fx.Redb.Query().WhereRedb(o => o.ValueUnique == key).ToListAsync(); return byString.Select(o => o.id).Concat(byUnique.Select(o => o.id)).Distinct().ToList(); } /// /// Runs an action against a store wired to its own DI scope — parallel callers must /// not share one (one connection per context). /// private async Task WithScopedContextAsync(Func action) { using var scope = _fx.ScopeFactory.CreateScope(); var ctx = new RouteContext(); ctx.SetServiceProvider(scope.ServiceProvider); ctx.AddService(typeof(IRedbService), scope.ServiceProvider.GetRequiredService()); await action(ctx); } private static ConversationMessageMeta Meta(int iter) => new() { CreatedAtUtc = DateTime.UtcNow, Iteration = iter, Usage = new LlmUsage(10, 5) }; // ── deterministic TOCTOU replays ──────────────────────────────── [Fact] public async Task ConversationRoot_CreateRace_LoserAdoptsWinnerRoot() { var convId = $"race-conv-{Guid.NewGuid():N}"; var winner = new RedbObject { value_string = $"winner-{convId}", ValueUnique = convId, Props = new ConversationProps { Status = "active", StartedAtUtc = DateTimeOffset.UtcNow, LastActivityAtUtc = DateTimeOffset.UtcNow } }; var winnerId = await _fx.Redb.SaveAsync(winner); var store = new RedbConversationStore(_fx.RouteContext); await store.AppendAsync(convId, null, LlmMessage.User("hi"), Meta(0)); (await KeyRowIdsAsync(convId)).Should().Equal([winnerId], "the loser of the root-creation race must adopt the winner's root, not mint a second one"); var messages = await _fx.Redb.Query() .WhereRedb(o => o.ValueLong == winnerId) .ToListAsync(); messages.Should().ContainSingle("the appended message must land under the winner's root"); } [Fact] public async Task CostBudget_FirstWriteRace_IncrementsWinnerRow() { var convId = $"race-budget-{Guid.NewGuid():N}"; var winner = new RedbObject { value_string = $"winner-{convId}", ValueUnique = convId, Props = new CostBudgetProps { InputTokens = 1, OutputTokens = 1, CostUsd = 0.001m, UpdatedAtUtc = DateTimeOffset.UtcNow } }; var winnerId = await _fx.Redb.SaveAsync(winner); var store = new RedbCostBudgetStore(_fx.RouteContext); var updated = await store.AddAsync(convId, new AgentUsage(100, 50, 0.01m)); updated.InputTokens.Should().Be(101, "the loser must increment the winner's row, not start a second budget"); updated.OutputTokens.Should().Be(51); updated.CostUsd.Should().Be(0.011m); (await KeyRowIdsAsync(convId)).Should().Equal([winnerId]); } [Fact] public async Task PromptTemplate_RegisterRace_FirstWins() { var name = $"race-tpl-{Guid.NewGuid():N}"; var key = $"{name}@1.0"; var winner = new RedbObject { value_string = $"winner-{key}", ValueUnique = key, Props = new PromptTemplateProps { Name = name, Version = "1.0", Body = "WINNER", CreatedAtUtc = DateTimeOffset.UtcNow } }; var winnerId = await _fx.Redb.SaveAsync(winner); var store = new RedbPromptTemplateRegistry(_fx.RouteContext); await store.SetAsync(new PromptTemplate { Name = name, Version = "1.0", Body = "LOSER" }); var ids = await KeyRowIdsAsync(key); ids.Should().Equal([winnerId], "a version is immutable provenance — the loser's body is dropped"); var row = await _fx.Redb.LoadAsync(winnerId); row!.Props.Body.Should().Be("WINNER"); } [Fact] public async Task ToolCache_SetRace_WritesOntoWinnerRow() { var key = $"race-cache-{Guid.NewGuid():N}"; var winner = new RedbObject { value_string = $"winner-{key}", ValueUnique = key, Props = new ToolCacheProps { OutputJson = """{"v":"old"}""", CreatedAtUtc = DateTimeOffset.UtcNow } }; var winnerId = await _fx.Redb.SaveAsync(winner); var store = new RedbToolResultCache(_fx.RouteContext); await store.SetAsync(key, """{"v":"new"}"""); (await KeyRowIdsAsync(key)).Should().Equal([winnerId]); var row = await _fx.Redb.LoadAsync(winnerId); row!.Props.OutputJson.Should().Be("""{"v":"new"}""", "a cache Set is last-writer-wins onto the single row"); } [Fact] public async Task Knowledge_UpsertRace_WritesOntoWinnerRow() { var chunkId = $"race-chunk-{Guid.NewGuid():N}"; var winner = new RedbObject { value_string = $"winner-{chunkId}", ValueUnique = chunkId, note = """{"text":"old"}""", Props = new KnowledgeChunkProps() }; var winnerId = await _fx.Redb.SaveAsync(winner); var store = new RedbKnowledgeStore(_fx.RouteContext); await store.UpsertAsync(new KnowledgeChunk { Id = chunkId, Text = "new text", Embedding = new[] { 1f, 0f } }); (await KeyRowIdsAsync(chunkId)).Should().Equal([winnerId], "an upsert is last-writer-wins onto the winner's row, never a duplicate chunk"); var row = await _fx.Redb.LoadAsync(winnerId); row!.note.Should().Contain("new text"); } [Fact] public async Task Knowledge_UpsertManyRace_RetriesOntoWinnerRow() { var freshId = $"race-bulk-a-{Guid.NewGuid():N}"; var collidedId = $"race-bulk-b-{Guid.NewGuid():N}"; var winner = new RedbObject { value_string = $"winner-{collidedId}", ValueUnique = collidedId, note = """{"text":"old"}""", Props = new KnowledgeChunkProps() }; var winnerId = await _fx.Redb.SaveAsync(winner); var store = new RedbKnowledgeStore(_fx.RouteContext); await store.UpsertManyAsync( [ new KnowledgeChunk { Id = freshId, Text = "fresh", Embedding = new[] { 1f, 0f } }, new KnowledgeChunk { Id = collidedId, Text = "collided", Embedding = new[] { 0f, 1f } } ]); (await KeyRowIdsAsync(freshId)).Should().ContainSingle(); (await KeyRowIdsAsync(collidedId)).Should().Equal([winnerId], "the bulk retry must resolve the collided id onto the winner's row"); var row = await _fx.Redb.LoadAsync(winnerId); row!.note.Should().Contain("collided"); } [Fact] public async Task Batch_RegisterRace_WritesOntoWinnerRow() { var batchId = $"race-batch-{Guid.NewGuid():N}"; var winner = new RedbObject { value_string = $"winner-{batchId}", ValueUnique = batchId, Props = new LlmBatchProps { ProviderId = "anthropic", Status = "submitted", SubmittedAtUtc = DateTimeOffset.UtcNow } }; var winnerId = await _fx.Redb.SaveAsync(winner); var store = new RedbBatchStore(_fx.RouteContext); await store.RegisterAsync(new BatchJobRecord { BatchId = batchId, ProviderId = "anthropic", Status = "running" }); (await KeyRowIdsAsync(batchId)).Should().Equal([winnerId]); var row = await _fx.Redb.LoadAsync(winnerId); row!.Props.Status.Should().Be("running", "the loser re-registers onto the winner's row"); } [Fact] public async Task EvalRun_SaveRace_WritesOntoWinnerRow() { var runId = $"race-eval-{Guid.NewGuid():N}"; var winner = new RedbObject { value_string = $"winner-{runId}", ValueUnique = runId, Props = new EvalRunProps { RunId = runId, Scenario = "s", AgentFingerprint = "old", CreatedAtUtc = DateTimeOffset.UtcNow } }; var winnerId = await _fx.Redb.SaveAsync(winner); var store = new RedbEvalRunStore(_fx.RouteContext); await store.SaveAsync(new EvalRunRecord { RunId = runId, Scenario = "s", AgentFingerprint = "new" }); (await KeyRowIdsAsync(runId)).Should().Equal([winnerId]); var row = await _fx.Redb.LoadAsync(winnerId); row!.Props.AgentFingerprint.Should().Be("new"); } [Fact] public async Task ToolIdempotency_CompleteRace_WritesOntoWinnerRow() { var convId = $"race-idem-{Guid.NewGuid():N}"; const string toolUseId = "tu-1"; var key = $"llm-tool:{convId}:{toolUseId}"; var winner = new RedbObject { value_string = $"winner-{key}", ValueUnique = key, Props = new ToolIdempotencyProps { OutputJson = """{"v":"old"}""", CreatedAtUtc = DateTimeOffset.UtcNow } }; var winnerId = await _fx.Redb.SaveAsync(winner); var store = new RedbToolIdempotencyStore(_fx.RouteContext); await store.CompleteAsync(convId, toolUseId, """{"v":"new"}"""); (await KeyRowIdsAsync(key)).Should().Equal([winnerId]); var row = await _fx.Redb.LoadAsync(winnerId); row!.Props.OutputJson.Should().Be("""{"v":"new"}"""); } [Fact] public async Task Approval_DuplicateRecord_FirstWins() { var approvalId = $"race-appr-{Guid.NewGuid():N}"; var request = new ApprovalRequest { ConversationId = $"c-{Guid.NewGuid():N}", ToolUseId = "tu-1", InputJson = """{"id":42}""", Exchange = Substitute.For(), Tool = new LlmToolCapability { Name = "delete_user", Description = "test tool", InputSchema = "{}" } }; var store = new RedbApprovalStore(_fx.RouteContext); await store.RecordAsync(request, ApprovalDecision.Approve(approvalId)); await store.RecordAsync(request, new ApprovalDecision { Approved = false, ApprovalId = approvalId, Reason = "dup" }); (await KeyRowIdsAsync(approvalId)).Should().ContainSingle( "one approval id resolves to exactly one recorded decision — first wins"); var found = await store.FindAsync(approvalId); found!.Approved.Should().BeTrue("the first recorded decision stands"); } // ── real parallel races ───────────────────────────────────────── [Fact] public async Task ConversationRoot_ParallelAppends_ConvergeOnSingleRoot() { var convId = $"race-par-conv-{Guid.NewGuid():N}"; await Task.WhenAll(Enumerable.Range(0, 8).Select(i => WithScopedContextAsync(async ctx => { var store = new RedbConversationStore(ctx); await store.AppendAsync(convId, null, LlmMessage.User($"m{i}"), Meta(i)); }))); var roots = await _fx.Redb.Query() .WhereRedb(o => o.ValueString == convId) .ToListAsync(); roots.Should().ContainSingle("all concurrent appends must converge on one conversation root"); var messages = await _fx.Redb.Query() .WhereRedb(o => o.ValueLong == roots[0].id) .ToListAsync(); messages.Should().HaveCount(8, "no message may land under a split-brain root"); var store = new RedbConversationStore(_fx.RouteContext); (await store.LoadTreeAsync(convId)).Should().HaveCount(8); } [Fact] public async Task CostBudget_ParallelFirstWrites_SingleRowFullSum() { var convId = $"race-par-budget-{Guid.NewGuid():N}"; await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => WithScopedContextAsync(async ctx => { var store = new RedbCostBudgetStore(ctx); await store.AddAsync(convId, new AgentUsage(10, 5, 0.001m)); }))); (await KeyRowIdsAsync(convId)).Should().ContainSingle( "concurrent first writes must not split the budget across rows"); var usage = await new RedbCostBudgetStore(_fx.RouteContext).GetUsageAsync(convId); usage.InputTokens.Should().Be(80, "every increment must survive — no lost updates"); usage.OutputTokens.Should().Be(40); usage.CostUsd.Should().Be(0.008m); } [Fact] public async Task ToolCache_ParallelSets_SingleRow() { var key = $"race-par-cache-{Guid.NewGuid():N}"; await Task.WhenAll(Enumerable.Range(0, 8).Select(i => WithScopedContextAsync(async ctx => { var store = new RedbToolResultCache(ctx); await store.SetAsync(key, $$"""{"v":{{i}}}"""); }))); (await KeyRowIdsAsync(key)).Should().ContainSingle(); var value = await new RedbToolResultCache(_fx.RouteContext).GetAsync(key); value.Should().MatchRegex("""^\{"v":[0-7]\}$""", "the surviving value is one writer's payload, intact"); } // ── review wave: duplicate ids inside ONE bulk call ───────────── [Fact] public async Task Knowledge_UpsertMany_DuplicateIdsInOneCall_LastWins() { var chunkId = $"dup-chunk-{Guid.NewGuid():N}"; var store = new RedbKnowledgeStore(_fx.RouteContext); await store.UpsertManyAsync( [ new KnowledgeChunk { Id = chunkId, Text = "first", Embedding = new[] { 1f, 0f } }, new KnowledgeChunk { Id = chunkId, Text = "second", Embedding = new[] { 0f, 1f } } ]); var rows = await _fx.Redb.Query() .WhereRedb(o => o.ValueString == chunkId) .ToListAsync(); rows.Should().ContainSingle("a duplicated id within one call must collapse to one row, not crash the batch"); rows[0].note.Should().Contain("second", "the last entry wins deterministically"); } [Fact] public async Task Batch_RegisterMany_DuplicateIdsInOneCall_LastWins() { var batchId = $"dup-batch-{Guid.NewGuid():N}"; var store = new RedbBatchStore(_fx.RouteContext); await store.RegisterManyAsync( [ new BatchJobRecord { BatchId = batchId, ProviderId = "anthropic", Status = "submitted" }, new BatchJobRecord { BatchId = batchId, ProviderId = "anthropic", Status = "running" } ]); var rows = await _fx.Redb.Query() .WhereRedb(o => o.ValueString == batchId) .ToListAsync(); rows.Should().ContainSingle(); rows[0].Props.Status.Should().Be("running", "the last entry wins deterministically"); } [Fact] public async Task EvalRun_SaveMany_DuplicateIdsInOneCall_LastWins() { var runId = $"dup-eval-{Guid.NewGuid():N}"; var store = new RedbEvalRunStore(_fx.RouteContext); await store.SaveManyAsync( [ new EvalRunRecord { RunId = runId, Scenario = "s", AgentFingerprint = "first" }, new EvalRunRecord { RunId = runId, Scenario = "s", AgentFingerprint = "second" } ]); var rows = await _fx.Redb.Query() .WhereRedb(o => o.ValueString == runId) .ToListAsync(); rows.Should().ContainSingle(); rows[0].Props.AgentFingerprint.Should().Be("second", "the last entry wins deterministically"); } // ── review wave: barrier recovery inside a caller-owned transaction ── [Fact] public async Task ToolCache_SetRace_InsideCallerTransaction_RecoversAndTransactionSurvives() { // Pins the core's contract: a save under a caller's transaction runs under a SAVEPOINT, so the loser's // unique violation no longer aborts that transaction (25P02 on PostgreSQL before // the core fix) — the catch resolves the winner and later writes in the SAME // transaction still commit. This is what makes the barrier legal in .Transacted() // routes. The shape is that of a .Transacted() route: an ambient TransactionScope and a // store call on the route's exchange, so the call joins the caller's transaction. var key = $"race-tx-{Guid.NewGuid():N}"; var sentinelKey = $"race-tx-sentinel-{Guid.NewGuid():N}"; var winner = new RedbObject { value_string = $"winner-{key}", ValueUnique = key, Props = new ToolCacheProps { OutputJson = """{"v":"old"}""", CreatedAtUtc = DateTimeOffset.UtcNow } }; var winnerId = await _fx.Redb.SaveAsync(winner); await using (var exchange = new Exchange(new Message(), _fx.ScopeFactory)) { using (var tx = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeAsyncFlowOption.Enabled)) { var store = new RedbToolResultCache(_fx.RouteContext); await store.SetAsync(key, """{"v":"new"}""", exchange: exchange); // The transaction must still be alive after the recovered violation. await _fx.RouteContext.GetRedbService(string.Empty, exchange).SaveAsync(new RedbObject { value_string = sentinelKey, ValueUnique = sentinelKey, Props = new ToolCacheProps { OutputJson = """{"v":"sentinel"}""", CreatedAtUtc = DateTimeOffset.UtcNow } }); tx.Complete(); } } (await KeyRowIdsAsync(key)).Should().Equal([winnerId]); var row = await _fx.Redb.LoadAsync(winnerId); row!.Props.OutputJson.Should().Be("""{"v":"new"}""", "the loser recovered onto the winner inside the caller's transaction"); (await KeyRowIdsAsync(sentinelKey)).Should().ContainSingle( "a write issued after the recovered violation must have committed — the transaction survived"); } [Fact] public async Task AStoreCallWithoutAnExchange_InsideARedbTransactionOfTheSharedInstance_IsNotPartOfIt() { // The rule of every store AddRedbLlmStorage registers: without an exchange a call works on a connection // of its own, so it does not join a transaction opened with ExecuteAtomicAsync on the context's shared // IRedbService, and a rollback of that transaction leaves the call's write in place. // SQLite has one writer: the call's own connection waits for the caller's write lock and fails after the // busy timeout, so on SQLite the rule is the same but this shape cannot be run; the Postgres and SQL Server // runs pin it. if (_fx.Provider == "sqlite") return; var key = $"own-conn-{Guid.NewGuid():N}"; var store = new RedbToolResultCache(_fx.RouteContext); var act = () => _fx.Redb.Context.ExecuteAtomicAsync(async () => { await store.SetAsync(key, """{"v":"outside"}"""); throw new InvalidOperationException("the caller rolls back"); }); await act.Should().ThrowAsync(); (await store.GetAsync(key)).Should().Be("""{"v":"outside"}""", "the call ran on its own connection and committed there; the caller's rollback does not reach it"); } // ── review wave: terminal status survives a raced re-register ── [Fact] public async Task Batch_RegisterRace_DoesNotDowngradeTerminalStatus() { var batchId = $"race-term-{Guid.NewGuid():N}"; var completedAt = DateTimeOffset.UtcNow; var winner = new RedbObject { value_string = $"winner-{batchId}", ValueUnique = batchId, Props = new LlmBatchProps { ProviderId = "anthropic", Status = "completed", SubmittedAtUtc = completedAt.AddMinutes(-1), CompletedAtUtc = completedAt } }; var winnerId = await _fx.Redb.SaveAsync(winner); // A redelivered submit races the webhook's completion and loses the insert: // its re-register must NOT drag the finished batch back to "submitted". var store = new RedbBatchStore(_fx.RouteContext); await store.RegisterAsync(new BatchJobRecord { BatchId = batchId, ProviderId = "anthropic", Status = "submitted" }); var row = await _fx.Redb.LoadAsync(winnerId); row!.Props.Status.Should().Be("completed", "a terminal status is never regressed by a raced re-register"); row.Props.CompletedAtUtc.Should().NotBeNull(); } } Path: redb-route/tests/redb.Route.Tests.Llm/StreamCallsTests.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/StreamCallsTests.cs ---- using System.Runtime.CompilerServices; using System.Transactions; using redb.Route.Llm.Engine.Observability; using redb.Route.Tests.Llm.TestHelpers; namespace redb.Route.Tests.Llm; /// /// stream=calls: the agent engine makes every model call as a stream inside the route. The pieces go to the /// observer as the model writes them; the loop goes on with the whole answer the stream assembled, so tools, the /// conversation, the budget and the route's transaction work exactly as without streaming, and the connection /// carries data the whole time. stream=true no longer means anything and is refused with the two modes named. /// public sealed class StreamCallsTests { private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}"""; private const string Input = """{"q":"x"}"""; private const string Reply = """{"answer":"42"}"""; /// Records the pieces the engine hands on. private sealed class DeltaRecorder : IAgentObserver { public List Deltas { get; } = []; public Task OnRunStartedAsync(AgentRunContext context, CancellationToken ct = default) => Task.CompletedTask; public Task OnIterationCompletedAsync(AgentIterationContext context, CancellationToken ct = default) => Task.CompletedTask; public Task OnToolInvokedAsync(AgentToolInvocationContext context, CancellationToken ct = default) => Task.CompletedTask; public Task OnRunCompletedAsync(AgentRunCompletedContext context, CancellationToken ct = default) => Task.CompletedTask; public Task OnDeltaAsync(AgentDeltaContext context, CancellationToken ct = default) { Deltas.Add(context); return Task.CompletedTask; } } private static FakeProvider ToolThenAnswer() => new FakeProvider() .EnqueueToolUse("lookup", Input, "tu_1") .EnqueueText("The answer is 42."); private static LlmConnectionFactory Factory(ILlmProvider provider) => new() { Provider = "stub", PrebuiltProvider = provider }; /// Runs one turn through direct:agent → llm://demo → mock:done; returns the answer. private static async Task<(object? Answer, EchoToolRoute Tool)> RunAsync( ILlmProvider provider, string options, IAgentObserver? observer = null, bool transacted = false, Func? reply = null) { var tool = new EchoToolRoute("lookup", "Look up a fact.", Schema, reply ?? (_ => Reply)); await using var host = LiveLlmHost.Build(observer).AddFactory("demo", Factory(provider)); var uri = $"llm://demo?tools=lookup&maxIterations=4{options}"; await host.StartAsync(tool, r => { var from = r.From("direct:agent"); if (transacted) from.Transacted().To(uri).To("mock:done"); else from.To(uri).To("mock:done"); }); await host.SendAsync("direct:agent", "What is the answer?"); return (host.Mock("mock:done").ReceivedExchanges.Single().In.Body, tool); } [Fact] public async Task StreamCalls_TheEngineStreamsEveryModelCall() { var provider = new StreamingFakeProvider(ToolThenAnswer()); var (answer, tool) = await RunAsync(provider, "&stream=calls"); provider.StreamCalls.Should().Be(2, "both model calls of the tool loop are streamed"); provider.PlainCalls.Should().Be(0); tool.CapturedInputs.Should().ContainSingle("the tool runs in the loop as without streaming"); answer.Should().Be("The answer is 42.", "Out.Body is the whole final answer, as without streaming"); } [Fact] public async Task StreamCalls_SendsTheSameConversationAsAPlainRun() { var plainScript = ToolThenAnswer(); var streamedScript = ToolThenAnswer(); var (plainAnswer, _) = await RunAsync(plainScript, ""); var (streamedAnswer, _) = await RunAsync(new StreamingFakeProvider(streamedScript), "&stream=calls"); streamedScript.SentMessages.Should().BeEquivalentTo(plainScript.SentMessages, o => o.WithStrictOrdering(), "the model sees the same transcript on every call, tool results included"); streamedAnswer.Should().Be(plainAnswer); } [Fact] public async Task StreamCalls_TheObserverGetsThePiecesAsTheyCome() { var script = new FakeProvider().Enqueue(new LlmResponse { Content = [new LlmThinkingBlock("Let me look it up."), new LlmTextBlock("The answer is 42.")], StopReason = LlmStopReason.EndTurn }); var recorder = new DeltaRecorder(); await RunAsync(new StreamingFakeProvider(script), "&stream=calls", recorder); recorder.Deltas.Should().OnlyContain(d => d.Iteration == 1 && d.Run.ExchangeId != null); string.Concat(recorder.Deltas.Where(d => d.Kind == AgentDeltaKind.Thinking).Select(d => d.Text)) .Should().Be("Let me look it up.", "thinking is a piece of its own kind"); string.Concat(recorder.Deltas.Where(d => d.Kind == AgentDeltaKind.Text).Select(d => d.Text)) .Should().Be("The answer is 42."); recorder.Deltas.Count(d => d.Kind == AgentDeltaKind.Text).Should().BeGreaterThan(1, "the text came in pieces"); } [Fact] public async Task StreamCalls_InsideTransacted_TheToolRunsInTheRouteTransaction() { var provider = new StreamingFakeProvider(ToolThenAnswer()); bool? toolSawTransaction = null; await RunAsync(provider, "&stream=calls", transacted: true, reply: _ => { toolSawTransaction = Transaction.Current is not null; return Reply; }); provider.StreamCalls.Should().Be(2, "or this test proves nothing about streaming"); toolSawTransaction.Should().BeTrue( "the streamed run happens inside the route, so its tools join the route's transaction as without streaming"); } /// A provider whose stream never hands over the assembled answer. private sealed class NoAnswerProvider : ILlmProvider { public string ProviderId => "no-answer"; public string ModelId => "no-answer-model"; public Task CompleteAsync(LlmRequest request, CancellationToken ct = default) => throw new NotSupportedException(); public async IAsyncEnumerable StreamAsync( LlmRequest request, [EnumeratorCancellation] CancellationToken ct = default) { await Task.Yield(); yield return new LlmStreamChunk([new LlmTextBlock("partial")], LlmStopReason.EndTurn, LlmUsage.Empty); } } [Fact] public async Task StreamCalls_AStreamWithoutTheAssembledAnswer_Fails() { var thrown = await Record.ExceptionAsync(() => RunAsync(new NoAnswerProvider(), "&stream=calls")); thrown.Should().NotBeNull("pieces alone are not an answer the loop, the store and the tools can go on with"); thrown!.ToString().Should().Contain("no-answer", "the message names the provider that broke the contract"); } [Theory] [InlineData("true")] [InlineData("fast")] public async Task Stream_WithoutAMode_IsRefused(string value) { var provider = new StreamingFakeProvider(new FakeProvider().EnqueueText("never asked for")); var thrown = await Record.ExceptionAsync(() => RunAsync(provider, $"&stream={value}")); thrown.Should().NotBeNull($"'stream={value}' names no streaming mode, and ignoring it would silently not stream"); thrown!.ToString().Should().Contain("stream=calls").And.Contain("stream=body", "the message names both modes"); provider.StreamCalls.Should().Be(0); provider.PlainCalls.Should().Be(0); } } Path: redb-route/tests/redb.Route.Tests.Llm/StubProviderTests.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/StubProviderTests.cs ---- namespace redb.Route.Tests.Llm; public sealed class StubProviderTests { private static StubProvider Create(string modelId = "stub-model") => new(new LlmConnectionFactory { ModelId = modelId }); [Fact] public void ProviderId_IsStub() { Create().ProviderId.Should().Be("stub"); } [Fact] public void ModelId_ReflectsFactory() { Create("xyz-7b").ModelId.Should().Be("xyz-7b"); } [Fact] public async Task Complete_EchoesLastUserMessage() { var p = Create(); var resp = await p.CompleteAsync(new LlmRequest { Messages = [LlmMessage.User("hello")] }); resp.StopReason.Should().Be(LlmStopReason.EndTurn); resp.Content.Should().HaveCount(1); resp.Content[0].Should().BeOfType() .Which.Text.Should().Be("[stub] hello"); } [Fact] public async Task Complete_FixedReply_OverridesEcho() { var p = new StubProvider(new LlmConnectionFactory()) { FixedReply = "constant" }; var resp = await p.CompleteAsync(new LlmRequest { Messages = [LlmMessage.User("ignored")] }); ((LlmTextBlock)resp.Content[0]).Text.Should().Be("constant"); } [Fact] public async Task Complete_ReportsUsage() { var p = Create(); var resp = await p.CompleteAsync(new LlmRequest { Messages = [LlmMessage.User("aaaaaaaa")] // 8 chars / 4 = 2 tokens }); resp.Usage.InputTokens.Should().BeGreaterThan(0); resp.Usage.OutputTokens.Should().BeGreaterThan(0); } [Fact] public async Task Complete_EmptyTranscript_ReturnsPlaceholder() { var p = Create(); var resp = await p.CompleteAsync(new LlmRequest()); ((LlmTextBlock)resp.Content[0]).Text.Should().Contain("(no user message)"); } [Fact] public async Task Complete_HonoursCancellation() { var p = Create(); var cts = new CancellationTokenSource(); cts.Cancel(); var act = () => p.CompleteAsync(new LlmRequest(), cts.Token); await act.Should().ThrowAsync(); } } Path: redb-route/tests/redb.Route.Tests.Llm/TestHelpers/EchoToolRoute.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/TestHelpers/EchoToolRoute.cs ---- using redb.Route.Configuration; using redb.Route.Llm.Extensions; namespace redb.Route.Tests.Llm.TestHelpers; /// /// Test helper that mounts a direct: route with .AsLlmTool(...). /// The route's processor captures every input passed by the agent engine and /// returns a fixed JSON reply, letting tests assert that: /// /// The model called the tool (input list non-empty). /// The model passed the right arguments (input contains expected keys). /// The agent surfaced the tool result back to the model (final reply mentions the payload). /// /// /// The descriptor lands in via the DSL, /// so the agent picks it up by name from ?tools=... or /// . /// /// public sealed class EchoToolRoute : RouteBuilder { private readonly string _toolName; private readonly string _description; private readonly string _inputSchema; private readonly Func _replyFactory; private readonly ToolSideEffect _sideEffect; private readonly ToolCachingPolicy _caching; private readonly IReadOnlyList _requiredClaims; private readonly List _capturedInputs = new(); private readonly List> _capturedHeaders = new(); private readonly List> _capturedProperties = new(); private readonly List _capturedServiceProviders = new(); private readonly List _capturedRouteIds = new(); /// Inputs (raw JSON) the agent has passed to this tool, in call order. public IReadOnlyList CapturedInputs => _capturedInputs; /// Header snapshot of every tool exchange, in call order. public IReadOnlyList> CapturedHeaders => _capturedHeaders; /// Exchange-property snapshot of every tool exchange, in call order. public IReadOnlyList> CapturedProperties => _capturedProperties; /// DI scope provider seen by every tool exchange — reference-compared against the agent exchange's. public IReadOnlyList CapturedServiceProviders => _capturedServiceProviders; /// Route id seen by every tool exchange, in call order. public IReadOnlyList CapturedRouteIds => _capturedRouteIds; /// The endpoint URI the descriptor dispatches to (direct:tool-{name}). public string EndpointUri => $"direct:tool-{_toolName}"; /// /// Creates a tool route that returns for every call, with the /// same optional safety metadata as the delegate overload. /// public EchoToolRoute(string toolName, string description, string inputSchema, string replyJson, ToolSideEffect sideEffect = ToolSideEffect.ReadOnly, ToolCachingPolicy caching = ToolCachingPolicy.None, params string[] requiredClaims) : this(toolName, description, inputSchema, _ => replyJson, sideEffect, caching, requiredClaims) { } /// /// Creates a tool route whose reply depends on the input JSON. The trailing optional /// parameters declare the tool's safety metadata — governance tests use them to express /// claim requirements, side-effect class and caching policy without a second helper type. /// /// Tool name exposed to the model. /// Human-readable description. /// JSON Schema for the input arguments. /// Builds the reply JSON from the raw input JSON. /// Side-effect class (default ). /// Caching policy (default ). /// Claims the calling principal must carry (default: none). public EchoToolRoute(string toolName, string description, string inputSchema, Func replyFactory, ToolSideEffect sideEffect = ToolSideEffect.ReadOnly, ToolCachingPolicy caching = ToolCachingPolicy.None, params string[] requiredClaims) { _toolName = toolName; _description = description; _inputSchema = inputSchema; _replyFactory = replyFactory; _sideEffect = sideEffect; _caching = caching; _requiredClaims = requiredClaims ?? []; } /// protected override void Configure() { var tool = From(EndpointUri) .AsLlmTool(_toolName) .Description(_description) .Input(_inputSchema) .SideEffect(_sideEffect) .Cost(ToolCostClass.Cheap); if (_caching != ToolCachingPolicy.None) tool = tool.Caching(_caching); foreach (var claim in _requiredClaims) tool = tool.RequireClaim(claim); tool.Then() .Process(e => { var input = e.In.Body switch { string s => s, null => "{}", var x => x.ToString() ?? "{}" }; lock (_capturedInputs) { _capturedInputs.Add(input); _capturedHeaders.Add(new Dictionary(e.In.Headers, StringComparer.OrdinalIgnoreCase)); _capturedProperties.Add(new Dictionary(e.Properties, StringComparer.OrdinalIgnoreCase)); _capturedServiceProviders.Add(e.ServiceProvider); _capturedRouteIds.Add(e.RouteId); } e.Out ??= e.In.Clone(); e.Out.Body = _replyFactory(input); e.Out.Headers["Content-Type"] = "application/json"; }); } } Path: redb-route/tests/redb.Route.Tests.Llm/TestHelpers/EnvFactAttribute.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/TestHelpers/EnvFactAttribute.cs ---- using Xunit.Sdk; namespace redb.Route.Tests.Llm.TestHelpers; /// /// xUnit fact attribute that skips the test when the named environment variable is /// missing or empty. Used to gate live LLM provider tests so CI runs stay green /// without secrets while local runs with the variable set hit the real API. /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] [XunitTestCaseDiscoverer("Xunit.Sdk.FactDiscoverer", "xunit.execution.{Platform}")] public sealed class EnvFactAttribute : FactAttribute { /// Creates an env-gated fact. /// Required environment variable. If unset/empty the test is skipped. /// Additional variables that must also be present. public EnvFactAttribute(string envVar, params string[] extraEnvVars) { var missing = new List(); if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(envVar))) missing.Add(envVar); foreach (var v in extraEnvVars) if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(v))) missing.Add(v); if (missing.Count > 0) Skip = $"Live LLM test skipped — set env vars: {string.Join(", ", missing)}."; } } Path: redb-route/tests/redb.Route.Tests.Llm/TestHelpers/EnvLoader.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/TestHelpers/EnvLoader.cs ---- using System.IO; using System.Runtime.CompilerServices; namespace redb.Route.Tests.Llm.TestHelpers; /// /// Loads .env.local from the well-known publish folder /// (redb.Tsak/publish/keys/.env.local) into /// before any test runs. Existing environment variables are NEVER overwritten — /// this is purely a developer convenience so a contributor with the file in /// place can run the live suite without exporting variables manually. /// /// Missing file = silent no-op. CI runs (without keys) skip every [EnvFact] /// in the suite. /// /// internal static class EnvLoader { [ModuleInitializer] internal static void Load() { // The repo layout is: // /redb.Route/tests/redb.Route.Tests.Llm/bin/Debug/netX.0/... // /redb.Tsak/publish/keys/.env.local // Climb until we hit a directory containing both subtrees. var dir = AppContext.BaseDirectory; while (!string.IsNullOrEmpty(dir)) { var candidate = Path.Combine(dir, "redb.Tsak", "publish", "keys", ".env.local"); if (File.Exists(candidate)) { Apply(candidate); return; } dir = Directory.GetParent(dir)?.FullName; } } private static void Apply(string path) { foreach (var rawLine in File.ReadAllLines(path)) { var line = rawLine.Trim(); if (line.Length == 0 || line.StartsWith('#')) continue; var eq = line.IndexOf('='); if (eq <= 0) continue; var key = line[..eq].Trim(); var value = line[(eq + 1)..].Trim().Trim('"'); // Never clobber a value already in the environment. if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(key))) continue; Environment.SetEnvironmentVariable(key, value); } } } Path: redb-route/tests/redb.Route.Tests.Llm/TestHelpers/FakeProvider.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/TestHelpers/FakeProvider.cs ---- namespace redb.Route.Tests.Llm.TestHelpers; /// /// Scriptable provider for engine/producer tests. Returns a queued /// per call. When the queue empties, defaults to a final /// EndTurn echoing "(no script)". /// public sealed class FakeProvider : ILlmProvider { private readonly Queue _scripted = new(); public string ProviderId => "fake"; public string ModelId { get; init; } = "fake-model"; public List CapturedRequests { get; } = new(); /// /// The messages of each call as the provider saw them. holds the /// request objects themselves, and the engine keeps appending to the transcript a request points /// at, so reading those after a run shows the grown list rather than what was sent. /// public List> SentMessages { get; } = new(); public int CallCount { get; private set; } public Func? OnCall { get; set; } public Exception? ThrowOnCall { get; set; } public FakeProvider Enqueue(LlmResponse response) { _scripted.Enqueue(response); return this; } public FakeProvider EnqueueText(string text, LlmStopReason stop = LlmStopReason.EndTurn, int tokensIn = 1, int tokensOut = 1) { return Enqueue(new LlmResponse { Content = [new LlmTextBlock(text)], StopReason = stop, Usage = new LlmUsage(tokensIn, tokensOut) }); } public FakeProvider EnqueueToolUse(string toolName, string inputJson, string toolUseId = "tu_1", int tokensIn = 1, int tokensOut = 1) { return Enqueue(new LlmResponse { Content = [new LlmToolUseBlock(toolUseId, toolName, inputJson)], StopReason = LlmStopReason.ToolUse, Usage = new LlmUsage(tokensIn, tokensOut) }); } public async Task CompleteAsync(LlmRequest request, CancellationToken ct = default) { CallCount++; CapturedRequests.Add(request); SentMessages.Add(request.Messages.ToList()); if (OnCall is not null) await OnCall(request, ct).ConfigureAwait(false); if (ThrowOnCall is not null) throw ThrowOnCall; if (_scripted.TryDequeue(out var scripted)) return scripted; return new LlmResponse { Content = [new LlmTextBlock("(no script)")], StopReason = LlmStopReason.EndTurn, Usage = LlmUsage.Empty }; } } Path: redb-route/tests/redb.Route.Tests.Llm/TestHelpers/FlatCostCalculator.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/TestHelpers/FlatCostCalculator.cs ---- using redb.Route.Llm.Engine.Governance; namespace redb.Route.Tests.Llm.TestHelpers; /// /// Deterministic pricing double: every call costs the same, regardless of tokens. Enough to prove the /// engine prices iterations and enforces a cost ceiling; a per-token table would only test the table. /// public sealed class FlatCostCalculator : ICostCalculator { private readonly decimal _costPerCall; /// Creates a calculator charging USD for every response. public FlatCostCalculator(decimal costPerCall) { _costPerCall = costPerCall; } /// Number of times the engine asked for a price. public int Estimates { get; private set; } /// public decimal? Estimate(LlmUsage usage, LlmConnectionFactory factory) { Estimates++; return _costPerCall; } } Path: redb-route/tests/redb.Route.Tests.Llm/TestHelpers/LiveLlmCollection.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/TestHelpers/LiveLlmCollection.cs ---- namespace redb.Route.Tests.Llm.TestHelpers; /// /// Shared collection definition that disables intra-class parallelism for live /// LLM tests. Free-tier endpoints (Gemini 15 RPM, Groq tier-1, OpenRouter /// shared upstream) burn out fast under parallel load — serializing the whole /// suite costs a few seconds and saves us from flaky 429 cascades. /// [CollectionDefinition("LiveLlmSerial", DisableParallelization = true)] public sealed class LiveLlmCollection { } Path: redb-route/tests/redb.Route.Tests.Llm/TestHelpers/LiveLlmHost.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/TestHelpers/LiveLlmHost.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Route.Components; using redb.Route.Configuration; using redb.Route.Http; using redb.Route.Llm.Extensions; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Observability; using redb.Route.Llm.Engine.Storage; namespace redb.Route.Tests.Llm.TestHelpers; /// /// Minimal hand-rolled wiring for live DSL tests. Avoids the /// RouteHostedService bootstrap (which requires a host) so the test /// body stays close to a Camel-style example a human can read top-down: /// build, register factory, declare routes, hit direct:, assert. /// /// All public registrations match what services.AddRedbRoute().AddRedbRouteLlm() /// would do in a real host. The single difference is that we drive /// ourselves. /// /// public sealed class LiveLlmHost : IAsyncDisposable { /// The shared route context. public RouteContext Context { get; } /// The producer template — used by the agent engine to dispatch tool routes. public IProducerTemplate ProducerTemplate { get; } /// The agent engine wired with the producer template. public IAgentEngine Engine { get; } /// The tool registry shared by every LLM endpoint and inline .Llm() step. public IToolDescriptorRegistry ToolRegistry { get; } private readonly SharedHttpServerManager? _httpManager; private LiveLlmHost(RouteContext ctx, IProducerTemplate pt, IAgentEngine engine, IToolDescriptorRegistry toolRegistry, SharedHttpServerManager? httpManager = null) { Context = ctx; ProducerTemplate = pt; Engine = engine; ToolRegistry = toolRegistry; _httpManager = httpManager; } /// Builds a host with the LLM component, agent engine and tool registry pre-wired. /// Optional observer — defaults to . Tests pass a spy /// when they need to assert on tool invocations the model performed. /// Optional idempotency store — governance tests pass a spy to assert reservations. /// Optional budget enforcer — defaults to the no-op one. /// Optional approval gate — defaults to (today's shipped default). /// Optional redaction filter — defaults to the no-op one. /// Optional conversation store — pass to inspect persisted metadata. /// Optional claims source. Absent means a claim-declaring tool cannot be built at all (fail closed). /// Optional cross-run cache store, consulted for ToolCachingPolicy.Persist tools. /// Optional price list. Absent means "this deployment cannot price a call". /// /// Optional redb instance registered in the host's container. Needed by integration tests: the redb-backed /// stores resolve their service from the exchange's DI scope, so without it they would look for a redb the /// host does not have. /// /// /// When true the engine is resolved from the container built by AddRedbRouteLlm() instead of being /// hand-wired. That is the path every real host takes, and the only one that proves the package wires its /// own governance seams. /// /// /// Optional HTTP hosting options. With set, the host also carries an /// HttpComponent, so a route can start at http:127.0.0.1:{port}/… — the only way to prove /// that a caller identified by the transport reaches the engine's governance without a test hook. /// /// Port for the HTTP entry point; required together with . /// Engine options of the route context; tracing tests turn EnableTelemetry off. public static LiveLlmHost Build( IAgentObserver? observer = null, IToolIdempotencyStore? idempotency = null, IBudgetEnforcer? budget = null, IApprovalGate? approval = null, IRedactionFilter? redaction = null, IConversationStore? conversation = null, IToolClaimsSource? claimsSource = null, IToolCacheStore? toolCache = null, ICostCalculator? costCalculator = null, IRedbService? redb = null, bool engineFromDi = false, HttpHostingOptions? httpHosting = null, int? httpPort = null, RouteEngineOptions? options = null) { // Closure trick: register IRouteContext as a factory that returns the // context we are about to construct. This lets the inline `.Llm(...)` // step resolve IRouteContext from exchange.ServiceProvider at runtime. RouteContext ctx = null!; var services = new ServiceCollection(); services.AddSingleton(_ => ctx); if (redb is not null) services.AddSingleton(redb); if (engineFromDi) services.AddRedbRouteLlm(); var sp = services.BuildServiceProvider(); ctx = new RouteContext(sp, contextId: "llm-test-ctx", options: options); ctx.AddComponent(new LlmComponent()); // Optional HTTP entry point: the transport identifies the caller and puts the principal on the // exchange, exactly as a real deployment does — no test-side hook touches the properties. SharedHttpServerManager? httpManager = null; if (httpPort is { } port) { httpManager = new SharedHttpServerManager(httpHosting); ctx.AddComponent(new HttpComponent { ServerManager = httpManager }); } // One registry must serve the route DSL and the endpoint that projects the tools. With the engine // coming from DI, the LLM extension already registered one — using the host's own instance as well // would give the DSL and the endpoint different registries, and the model would see no tools at all. var toolRegistry = engineFromDi ? sp.GetRequiredService() : new ToolDescriptorRegistry(); ctx.AddService(typeof(IToolDescriptorRegistry), toolRegistry); // The claims source must be visible to the route context, not only to the engine: the DSL // refuses to build a claim-declaring tool when no source is registered (fail closed). if (claimsSource is not null) ctx.AddService(typeof(IToolClaimsSource), claimsSource); var pt = new ProducerTemplate(ctx); ctx.AddService(typeof(IProducerTemplate), pt); var engine = engineFromDi ? sp.GetRequiredService() : new AgentEngine( logger: null, producerTemplate: pt, observer: observer ?? new NoopAgentObserver(), budget: budget ?? new NoopBudgetEnforcer(), approval: approval ?? new AutoApproveGate(), redaction: redaction ?? new NoopRedactionFilter(), shadow: new NoopShadowRunner(), conversation: conversation, idempotency: idempotency, approvalStore: null, claimsSource: claimsSource, toolCache: toolCache, costCalculator: costCalculator); // A real host gets its engine from the container; putting it in the context locator as well would // mask whether the endpoint can find what the package registered — the very gap these tests exist for. if (!engineFromDi) ctx.AddService(typeof(IAgentEngine), engine); return new LiveLlmHost(ctx, pt, engine, toolRegistry, httpManager); } /// Registers a connection factory keyed by . public LiveLlmHost AddFactory(string name, LlmConnectionFactory factory) { factory.Name = name; Context.AddToRegistry(name, factory); return this; } /// /// Declares routes inline and starts the context. The producer template is /// started as part of this call so subsequent tool dispatches just work. /// public async Task StartAsync(Action configure) { Context.AddRoutes(configure); await Context.Start().ConfigureAwait(false); ((ProducerTemplate)ProducerTemplate).Start(); return this; } /// /// Mounts a (e.g. an ) /// and starts the context. Use this overload when the builder owns the route /// so its descriptor lands in the registry via .AsLlmTool. /// public async Task StartAsync(RouteBuilder routes, Action? extraInline = null) { Context.AddRoutes(routes); if (extraInline is not null) Context.AddRoutes(extraInline); await Context.Start().ConfigureAwait(false); ((ProducerTemplate)ProducerTemplate).Start(); return this; } /// Sends one message into and returns the resulting exchange. /// Endpoint to send to. /// Message body. /// Optional inbound headers. /// /// Optional hook running on the exchange before it enters the route. Used by tests that need state a /// real transport would have produced — the caller's principal in the exchange properties, for /// instance. /// public async Task SendAsync(string endpointUri, string body, IDictionary? headers = null, Action? configure = null) { var endpoint = Context.GetEndpoint(endpointUri); var producer = endpoint.CreateProducer(); await producer.Start().ConfigureAwait(false); var msg = new Message(body); if (headers is not null) foreach (var kv in headers) msg.Headers[kv.Key] = kv.Value; // Construct the exchange with a per-call DI scope so inline .Llm() // can resolve IRouteContext from exchange.ServiceProvider. var scopeFactory = endpoint.ScopeFactory; var ex = Exchange.Create(msg, scopeFactory); configure?.Invoke(ex); await producer.Process(ex).ConfigureAwait(false); return ex; } /// Convenience cast for the mock sink so tests can read its received exchanges. public MockEndpoint Mock(string uri) => (MockEndpoint)Context.GetEndpoint(uri); /// public async ValueTask DisposeAsync() { await Context.DisposeAsync().ConfigureAwait(false); if (ProducerTemplate is IDisposable d) d.Dispose(); if (_httpManager is not null) await _httpManager.DisposeAsync().ConfigureAwait(false); } } Path: redb-route/tests/redb.Route.Tests.Llm/TestHelpers/LocalHttpServer.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/TestHelpers/LocalHttpServer.cs ---- using System.Net; using System.Text; namespace redb.Route.Tests.Llm.TestHelpers; /// /// Tiny in-process HTTP server backed by . Listens /// on a free localhost port chosen at start time, replies to any request with /// the body / headers configured by the test, and records every request URL /// for assertion. Used as a deterministic target for /// tests so we don't depend on /// the public internet. /// /// HttpListener requires http.sys permission on Windows; binding to /// 127.0.0.1 on a high port works without elevation. /// /// public sealed class LocalHttpServer : IDisposable { private readonly HttpListener _listener; private readonly CancellationTokenSource _cts = new(); private readonly Task _loop; private readonly List _requestPaths = new(); /// Base URL the server listens on (e.g. http://127.0.0.1:34567/). public string BaseUrl { get; } /// Host portion of (e.g. 127.0.0.1). public string Host => "127.0.0.1"; /// Body returned for every request (defaults to a small JSON document). public string ResponseBody { get; set; } = """{"ok":true,"answer":"42"}"""; /// Content-Type for replies. public string ContentType { get; set; } = "application/json"; /// Status code for replies. public int StatusCode { get; set; } = 200; /// Snapshot of request URL paths (with query) the server has received. public IReadOnlyList RequestPaths { get { lock (_requestPaths) return _requestPaths.ToArray(); } } /// Starts a server on a free localhost port. public LocalHttpServer() { var port = PickFreePort(); BaseUrl = $"http://127.0.0.1:{port}/"; _listener = new HttpListener(); _listener.Prefixes.Add(BaseUrl); _listener.Start(); _loop = Task.Run(LoopAsync); } private async Task LoopAsync() { while (!_cts.IsCancellationRequested) { HttpListenerContext ctx; try { ctx = await _listener.GetContextAsync().ConfigureAwait(false); } catch { return; } lock (_requestPaths) _requestPaths.Add(ctx.Request.Url?.PathAndQuery ?? ""); ctx.Response.StatusCode = StatusCode; ctx.Response.ContentType = ContentType; var bytes = Encoding.UTF8.GetBytes(ResponseBody); ctx.Response.ContentLength64 = bytes.LongLength; await ctx.Response.OutputStream.WriteAsync(bytes).ConfigureAwait(false); ctx.Response.Close(); } } private static int PickFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); /// public void Dispose() { _cts.Cancel(); try { _listener.Stop(); } catch { /* already stopped */ } try { _loop.Wait(TimeSpan.FromSeconds(2)); } catch { /* ignore */ } _listener.Close(); _cts.Dispose(); } } Path: redb-route/tests/redb.Route.Tests.Llm/TestHelpers/SpyStores.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/TestHelpers/SpyStores.cs ---- using System.Collections.Concurrent; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Storage; namespace redb.Route.Tests.Llm.TestHelpers; /// /// Idempotency-store spy for governance tests. Records every reservation, completion and /// release so a test can assert whether the engine consulted the store at all — /// which is the observable difference behind the SideEffect gate. /// /// Unlike the shipped in-memory store this one does not use an /// IIdempotentRepository: the tests care about the engine's calls, not about dedup /// implementation, and a plain dictionary keeps the double free of infrastructure. /// /// public sealed class SpyIdempotencyStore : IToolIdempotencyStore { private readonly ConcurrentDictionary _outputs = new(StringComparer.Ordinal); private readonly List _reservations = new(); private readonly List _completions = new(); private readonly List _releases = new(); private readonly object _gate = new(); /// Keys the engine tried to reserve, in order ({conversationId}:{toolUseId}). public IReadOnlyList Reservations { get { lock (_gate) return _reservations.ToArray(); } } /// Keys the engine completed after a successful dispatch. public IReadOnlyList Completions { get { lock (_gate) return _completions.ToArray(); } } /// Keys the engine released after a failed dispatch. public IReadOnlyList Releases { get { lock (_gate) return _releases.ToArray(); } } /// public Task TryReserveAsync( string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default) { var key = Key(conversationId, toolUseId); lock (_gate) _reservations.Add(key); return Task.FromResult(_outputs.TryGetValue(key, out var cached) ? ToolIdempotencyReservation.Hit(cached) : ToolIdempotencyReservation.NewReservation); } /// public Task CompleteAsync( string conversationId, string toolUseId, string outputJson, IExchange? exchange = null, CancellationToken ct = default) { var key = Key(conversationId, toolUseId); lock (_gate) _completions.Add(key); _outputs[key] = outputJson; return Task.CompletedTask; } /// public Task ReleaseAsync( string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default) { var key = Key(conversationId, toolUseId); lock (_gate) _releases.Add(key); return Task.CompletedTask; } private static string Key(string conversationId, string toolUseId) => $"{conversationId}:{toolUseId}"; } /// /// Tool-cache spy. Records reads and writes so a test can assert the engine consulted the /// cache (wave 3 wires it; before that, the counts stay at zero — which is itself the finding). /// public sealed class SpyToolCacheStore : IToolCacheStore { private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal); private readonly List _gets = new(); private readonly List _sets = new(); private readonly object _gate = new(); /// Keys read through , in order. public IReadOnlyList Gets { get { lock (_gate) return _gets.ToArray(); } } /// Keys written through , in order. public IReadOnlyList Sets { get { lock (_gate) return _sets.ToArray(); } } /// public ValueTask GetAsync(string cacheKey, IExchange? exchange = null, CancellationToken ct = default) { lock (_gate) _gets.Add(cacheKey); return ValueTask.FromResult(_entries.TryGetValue(cacheKey, out var value) ? value : null); } /// public ValueTask SetAsync(string cacheKey, string outputJson, TimeSpan? ttl = null, IExchange? exchange = null, CancellationToken ct = default) { lock (_gate) _sets.Add(cacheKey); _entries[cacheKey] = outputJson; return ValueTask.CompletedTask; } /// public ValueTask ClearAsync(IExchange? exchange = null, CancellationToken ct = default) { _entries.Clear(); return ValueTask.CompletedTask; } } /// /// Tool-cache store that always fails. Pins the best-effort rule: an unavailable cache may cost a hit, /// it must never cost the run — a store outage cannot turn a working tool call into an error for the /// model (which would then retry it). /// public sealed class ThrowingToolCacheStore : IToolCacheStore { /// public ValueTask GetAsync(string cacheKey, IExchange? exchange = null, CancellationToken ct = default) => throw new InvalidOperationException("cache store is unavailable"); /// public ValueTask SetAsync(string cacheKey, string outputJson, TimeSpan? ttl = null, IExchange? exchange = null, CancellationToken ct = default) => throw new InvalidOperationException("cache store is unavailable"); /// public ValueTask ClearAsync(IExchange? exchange = null, CancellationToken ct = default) => throw new InvalidOperationException("cache store is unavailable"); } /// /// Budget-enforcer spy: delegates to the shipped per-run enforcer and records the reason of every /// stop, so a test can assert why a run stopped — the engine logs the reason and does not put /// it on the response, and a test that only counted provider calls would not notice the difference /// between "budget stopped it" and "the model asked to stop". /// public sealed class SpyBudgetEnforcer : IBudgetEnforcer { private readonly InMemoryBudgetEnforcer _inner = new(); private readonly List _stopReasons = new(); private readonly List _sawAmbientTransaction = new(); private readonly object _gate = new(); /// For every budget call, in order: whether an ambient transaction was open when the engine made it. public IReadOnlyList SawAmbientTransaction { get { lock (_gate) return _sawAmbientTransaction.ToArray(); } } /// Reasons of every the engine was handed, in order. public IReadOnlyList StopReasons { get { lock (_gate) return _stopReasons.ToArray(); } } /// Number of pre-iteration checks the engine performed. public int PreChecks { get; private set; } /// Number of post-iteration checks the engine performed. public int PostChecks { get; private set; } /// public async ValueTask PreCheckAsync( string? conversationId, AgentBudget budget, AgentUsage usageSoFar, CancellationToken ct = default) { PreChecks++; ObserveTransaction(); var decision = await _inner.PreCheckAsync(conversationId, budget, usageSoFar, ct).ConfigureAwait(false); Record(decision); return decision; } /// public async ValueTask RecordAndCheckAsync( string? conversationId, AgentBudget budget, AgentUsage iterationUsage, AgentUsage totalUsage, CancellationToken ct = default) { PostChecks++; ObserveTransaction(); var decision = await _inner.RecordAndCheckAsync(conversationId, budget, iterationUsage, totalUsage, ct) .ConfigureAwait(false); Record(decision); return decision; } private void ObserveTransaction() { lock (_gate) _sawAmbientTransaction.Add(System.Transactions.Transaction.Current is not null); } private void Record(BudgetDecision decision) { if (decision.Continue) return; lock (_gate) _stopReasons.Add(decision.Reason); } } Path: redb-route/tests/redb.Route.Tests.Llm/TestHelpers/StreamingFakeProvider.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/TestHelpers/StreamingFakeProvider.cs ---- using System.Runtime.CompilerServices; using System.Text.RegularExpressions; namespace redb.Route.Tests.Llm.TestHelpers; /// /// Plays a script as a stream: thinking and text word by word, then the last chunk with the /// whole answer (). Counts which kind of call the engine made. /// public sealed class StreamingFakeProvider(FakeProvider script) : ILlmProvider { private int _streamCalls; private int _plainCalls; /// Streamed calls made so far. public int StreamCalls => Volatile.Read(ref _streamCalls); /// Plain calls made so far. public int PlainCalls => Volatile.Read(ref _plainCalls); /// public string ProviderId => "fake-stream"; /// public string ModelId => script.ModelId; /// public Task CompleteAsync(LlmRequest request, CancellationToken ct = default) { Interlocked.Increment(ref _plainCalls); return script.CompleteAsync(request, ct); } /// public async IAsyncEnumerable StreamAsync( LlmRequest request, [EnumeratorCancellation] CancellationToken ct = default) { Interlocked.Increment(ref _streamCalls); var response = await script.CompleteAsync(request, ct); foreach (var block in response.Content) { if (block is LlmThinkingBlock thinking) foreach (var piece in Words(thinking.Text)) yield return new LlmStreamChunk([new LlmThinkingBlock(piece)], null, null); else if (block is LlmTextBlock text) foreach (var piece in Words(text.Text)) yield return new LlmStreamChunk([new LlmTextBlock(piece)], null, null); } yield return new LlmStreamChunk( [.. response.Content.OfType()], response.StopReason, response.Usage) { Response = response }; } private static IEnumerable Words(string text) => Regex.Split(text, "(?<= )").Where(w => w.Length > 0); } Path: redb-route/tests/redb.Route.Tests.Llm/TestHelpers/TenantScopedTool.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/TestHelpers/TenantScopedTool.cs ---- using System.Collections.Concurrent; using redb.Route.Configuration; namespace redb.Route.Tests.Llm.TestHelpers; /// /// Descriptor for a per-tenant tool: its address is built from the caller's tenant header, which is /// the one thing may legitimately do with the /// parent exchange. Exists to prove the tool cache keys on the resolved address — two tenants with /// the same input must never share an entry. /// public sealed class TenantScopedToolDescriptor : ILlmToolDescriptor { /// Header carrying the tenant id ( would propagate this in a real host). public const string TenantHeader = "x-tenant-id"; /// Tool name exposed to the model. public const string ToolName = "lookup"; private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}"""; /// public LlmToolCapability Capability { get; } = new() { Name = ToolName, Description = "Look up a fact for the calling tenant.", InputSchema = Schema, Safety = new LlmToolSafety { SideEffect = ToolSideEffect.ReadOnly, Caching = ToolCachingPolicy.Persist } }; /// public string BuildEndpointUri(string inputJson, IExchange parentExchange) => $"direct:tool-lookup.{ResolveTenant(parentExchange)}"; /// Tenant id of , or none when the header is absent. public static string ResolveTenant(IExchange exchange) => exchange.In.Headers.TryGetValue(TenantHeader, out var tenant) && tenant is not null ? tenant.ToString()! : "none"; } /// /// Mounts one direct:tool-lookup.{tenant} endpoint per tenant and counts dispatches, so a test /// can assert both "the right tenant was called" and "the other tenant's cached answer was not /// served". Each endpoint answers with its own tenant id and its own call counter — a cross-tenant /// leak would be visible in the payload, not only in the counters. /// public sealed class TenantScopedToolRoutes : RouteBuilder { private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}"""; private readonly ConcurrentDictionary _counts = new(StringComparer.Ordinal); /// Dispatches per tenant id. public IReadOnlyDictionary Counts => _counts; /// Dispatches for one tenant id (0 when never called). public int CountFor(string tenant) => _counts.TryGetValue(tenant, out var n) ? n : 0; /// protected override void Configure() { Mount("a"); Mount("b"); Mount("none"); } private void Mount(string tenant) { From($"direct:tool-lookup.{tenant}") .Process(e => { var call = _counts.AddOrUpdate(tenant, 1, (_, n) => n + 1); e.Out ??= e.In.Clone(); e.Out.Body = $$"""{"tenant":"{{tenant}}","call":{{call}}}"""; e.Out.Headers["Content-Type"] = "application/json"; }); } } Path: redb-route/tests/redb.Route.Tests.Llm/TestHelpers/ToolInvocationSpy.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/TestHelpers/ToolInvocationSpy.cs ---- using System.Collections.Concurrent; using redb.Route.Llm.Engine.Observability; namespace redb.Route.Tests.Llm.TestHelpers; /// /// Captures every call so a live test /// can assert which tools the model actually invoked, what input JSON it sent and what /// the tool returned. Other observer events are accepted as no-ops. /// public sealed class ToolInvocationSpy : IAgentObserver { private readonly ConcurrentBag _invocations = new(); /// Snapshot of every captured invocation in registration order. public IReadOnlyCollection Invocations => _invocations.ToArray(); /// Convenience filter — returns invocations whose tool name matches. public IReadOnlyCollection ForTool(string name) => _invocations.Where(i => i.Tool.Name == name).ToArray(); /// public Task OnRunStartedAsync(AgentRunContext context, CancellationToken ct = default) => Task.CompletedTask; /// public Task OnIterationCompletedAsync(AgentIterationContext context, CancellationToken ct = default) => Task.CompletedTask; /// public Task OnToolInvokedAsync(AgentToolInvocationContext context, CancellationToken ct = default) { _invocations.Add(context); return Task.CompletedTask; } /// public Task OnRunCompletedAsync(AgentRunCompletedContext context, CancellationToken ct = default) => Task.CompletedTask; } Path: redb-route/tests/redb.Route.Tests.Llm/ToolExchangeContextTests.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/ToolExchangeContextTests.cs ---- using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm; /// /// End-to-end tests for what a tool route actually receives when the agent /// dispatches a tool call. Guards the fix for "tool exchange built from scratch": /// the tool now runs on a linked child of the agent exchange, so properties, /// route id and the parent's DI scope come across, while headers stay filtered /// by . /// public sealed class ToolExchangeContextTests { private static EchoToolRoute EchoTool() => new( toolName: "echo", description: "echo back the result", inputSchema: """{"type":"object","properties":{"v":{"type":"number"}}}""", replyJson: """{"r":42}"""); private static FakeProvider ToolThenText() => new FakeProvider() .EnqueueToolUse("echo", "{\"v\":1}") .EnqueueText("done"); private static async Task HostAsync(FakeProvider fake, EchoToolRoute tool, string llmUri) { var host = LiveLlmHost.Build(); host.Context.AddToRegistry("fake", new LlmConnectionFactory { Name = "fake", Provider = "fake", ModelId = fake.ModelId, PrebuiltProvider = fake }); await host.StartAsync(tool, r => r.From("direct:agent").To(llmUri).To("mock:done")); return host; } [Fact] public async Task ToolExchange_InheritsParentPropertiesAndRouteId() { var fake = ToolThenText(); var tool = EchoTool(); // ?redb=my-llm-db lands in exchange.Properties[LlmKeys.RedbName] — the // canonical example of state a tool needs and used to lose. await using var host = await HostAsync(fake, tool, LlmDsl.Factory("fake").Tools("echo").AsUri() + "&redb=my-llm-db"); await host.SendAsync("direct:agent", "go"); tool.CapturedProperties.Should().ContainSingle(); tool.CapturedProperties[0].Should().ContainKey(LlmKeys.RedbName) .WhoseValue.Should().Be("my-llm-db"); tool.CapturedRouteIds[0].Should().NotBeNull(); } [Fact] public async Task ToolExchange_SharesTheAgentDiScope() { var fake = ToolThenText(); var tool = EchoTool(); IServiceProvider? agentScope = null; var host = LiveLlmHost.Build(); host.Context.AddToRegistry("fake", new LlmConnectionFactory { Name = "fake", Provider = "fake", ModelId = fake.ModelId, PrebuiltProvider = fake }); await using var _ = host; await host.StartAsync(tool, r => r .From("direct:agent") .Process(e => agentScope = e.ServiceProvider) .To(LlmDsl.Factory("fake").Tools("echo").AsUri()) .To("mock:done")); await host.SendAsync("direct:agent", "go"); agentScope.Should().NotBeNull("the test host wires a scope factory onto the inbound exchange"); tool.CapturedServiceProviders.Should().ContainSingle(); // Same instance, not merely non-null: scoped services the conversation // resolved (principal, tenant accessor, per-exchange IRedbService) must be // the very ones the tool sees. tool.CapturedServiceProviders[0].Should().BeSameAs(agentScope); } [Fact] public async Task ToolExchange_CarriesResolvedPrincipalAndAuditTags() { var fake = ToolThenText(); var tool = EchoTool(); // ?user= is an expression over the inbound exchange — the resolved value, // not the raw llm.user.id header, is what must reach the tool. await using var host = await HostAsync(fake, tool, LlmDsl.Factory("fake") .Tools("echo") .User("${header.X-User-Id}") .Audit("tier", "gold") .AsUri()); await host.SendAsync("direct:agent", "go", new Dictionary { ["X-User-Id"] = "alice@example.com" }); var headers = tool.CapturedHeaders.Should().ContainSingle().Subject; headers[LlmHeaders.UserId].Should().Be("alice@example.com"); headers[LlmHeaders.AuditTagPrefix + "tier"].Should().Be("gold"); } [Fact] public async Task ToolExchange_DoesNotLeakInboundTransportHeaders() { var fake = ToolThenText(); var tool = EchoTool(); await using var host = await HostAsync(fake, tool, LlmDsl.Factory("fake").Tools("echo").AsUri()); await host.SendAsync("direct:agent", "go", new Dictionary { ["Authorization"] = "Bearer secret", ["Cookie"] = "session=abc", ["x-tenant-id"] = "acme" }); var headers = tool.CapturedHeaders.Should().ContainSingle().Subject; headers.Should().NotContainKey("Authorization"); headers.Should().NotContainKey("Cookie"); headers.Should().NotContainKey("x-tenant-id"); // The engine's own stamps are always there. headers[LlmHeaders.ToolName].Should().Be("echo"); } [Fact] public async Task PropagateToolHeaders_OptsNamedHeadersIn() { var fake = ToolThenText(); var tool = EchoTool(); await using var host = await HostAsync(fake, tool, LlmDsl.Factory("fake") .Tools("echo") .PropagateToolHeaders("x-tenant-id", "x-app-*") .AsUri()); await host.SendAsync("direct:agent", "go", new Dictionary { ["x-tenant-id"] = "acme", ["x-app-locale"] = "ru-RU", ["Authorization"] = "Bearer secret" }); var headers = tool.CapturedHeaders.Should().ContainSingle().Subject; headers["x-tenant-id"].Should().Be("acme"); headers["x-app-locale"].Should().Be("ru-RU"); headers.Should().NotContainKey("Authorization", "opt-in is per name, not a blanket open"); } [Fact] public async Task ToolCall_StillReturnsResultToTheModel() { // Regression guard for the dispatch rewrite itself (RequestBody → RequestAsync // on a caller-owned exchange): the reply must still round-trip. var fake = ToolThenText(); var tool = EchoTool(); await using var host = await HostAsync(fake, tool, LlmDsl.Factory("fake").Tools("echo").AsUri()); await host.SendAsync("direct:agent", "go"); tool.CapturedInputs.Should().ContainSingle().Which.Should().Contain("\"v\":1"); fake.CapturedRequests[^1].Messages .SelectMany(m => m.Content) .OfType() .Should().ContainSingle() .Which.OutputJson.Should().Contain("42"); } [Fact] public async Task AgentExchange_KeepsItsScopeAfterTheToolCall() { // The linked child must not dispose the shared parent scope on the way out — // otherwise everything after the tool call runs on a disposed provider. var fake = ToolThenText(); var tool = EchoTool(); await using var host = await HostAsync(fake, tool, LlmDsl.Factory("fake").Tools("echo").AsUri()); var ex = await host.SendAsync("direct:agent", "go"); ex.ServiceProvider.Should().NotBeNull(); // Resolving after the run proves the scope is still alive, not disposed. var act = () => ex.ServiceProvider!.GetService(typeof(IRouteContext)); act.Should().NotThrow(); } } Path: redb-route/tests/redb.Route.Tests.Llm/ToolHeaderPolicyTests.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/ToolHeaderPolicyTests.cs ---- namespace redb.Route.Tests.Llm; /// /// Unit tests for — the default-deny allowlist that /// decides what a tool route sees of the agent exchange. /// public sealed class ToolHeaderPolicyTests { private static AgentRequest Request( IDictionary? parentHeaders = null, string? userId = null, IReadOnlyDictionary? auditTags = null, IReadOnlyList? propagate = null) { var msg = new Message("body"); if (parentHeaders is not null) foreach (var kv in parentHeaders) msg.Headers[kv.Key] = kv.Value; return new AgentRequest { Factory = new LlmConnectionFactory { Name = "f", Provider = "stub", ModelId = "m" }, Exchange = new Exchange(msg), UserContent = [new LlmTextBlock("hi")], UserId = userId, AuditTags = auditTags, PropagateToolHeaders = propagate }; } private static Dictionary Apply(AgentRequest request) { var target = new Dictionary(StringComparer.OrdinalIgnoreCase); ToolHeaderPolicy.Apply(request, target); return target; } [Fact] public void Defaults_CarryConversationAndCorrelationIds() { var target = Apply(Request(new Dictionary { [LlmHeaders.ConversationId] = "conv-1", ["X-Correlation-Id"] = "corr-1", ["CorrelationId"] = "corr-2" })); target[LlmHeaders.ConversationId].Should().Be("conv-1"); target["X-Correlation-Id"].Should().Be("corr-1"); target["CorrelationId"].Should().Be("corr-2"); } [Fact] public void ArbitraryInboundHeader_IsNotPropagated() { // The whole point of default-deny: an HTTP consumer's headers must not // ride along into every tool just because the tool shares the host. var target = Apply(Request(new Dictionary { ["Authorization"] = "Bearer secret", ["Cookie"] = "session=abc", ["x-tenant-id"] = "acme" })); target.Should().NotContainKey("Authorization"); target.Should().NotContainKey("Cookie"); target.Should().NotContainKey("x-tenant-id"); } [Fact] public void ResolvedUserId_WinsOverHeader() { // `?user=${header.X-User}` resolves before the run; copying the raw // llm.user.id header would have dropped exactly this case. var target = Apply(Request( parentHeaders: new Dictionary { [LlmHeaders.UserId] = "from-header" }, userId: "resolved-alice")); target[LlmHeaders.UserId].Should().Be("resolved-alice"); } [Fact] public void UserIdHeader_IsFallbackWhenNothingResolved() { // Engine driven without LlmProducer (inline .Llm(), eval runner) still propagates. var target = Apply(Request( parentHeaders: new Dictionary { [LlmHeaders.UserId] = "from-header" })); target[LlmHeaders.UserId].Should().Be("from-header"); } [Fact] public void ResolvedAuditTags_BecomePrefixedHeaders() { var target = Apply(Request(auditTags: new Dictionary { ["tier"] = "gold", ["bucket"] = "A" })); target[LlmHeaders.AuditTagPrefix + "tier"].Should().Be("gold"); target[LlmHeaders.AuditTagPrefix + "bucket"].Should().Be("A"); } [Fact] public void AuditHeaders_AreFallbackWhenNoResolvedTags() { var target = Apply(Request(new Dictionary { [LlmHeaders.AuditTagPrefix + "region"] = "eu-west", ["llm.unrelated"] = "nope" })); target[LlmHeaders.AuditTagPrefix + "region"].Should().Be("eu-west"); target.Should().NotContainKey("llm.unrelated"); } [Fact] public void OptIn_CopiesExactNames() { var target = Apply(Request( parentHeaders: new Dictionary { ["x-tenant-id"] = "acme", ["Authorization"] = "Bearer secret" }, propagate: ["x-tenant-id"])); target["x-tenant-id"].Should().Be("acme"); target.Should().NotContainKey("Authorization"); } [Fact] public void OptIn_SupportsTrailingStarAsPrefix() { var target = Apply(Request( parentHeaders: new Dictionary { ["x-app-locale"] = "ru-RU", ["x-app-build"] = "42", ["x-other"] = "no" }, propagate: ["x-app-*"])); target["x-app-locale"].Should().Be("ru-RU"); target["x-app-build"].Should().Be("42"); target.Should().NotContainKey("x-other"); } [Fact] public void NullHeaderValues_AreSkipped() { var target = Apply(Request( parentHeaders: new Dictionary { ["x-tenant-id"] = null }, propagate: ["x-tenant-id"])); target.Should().NotContainKey("x-tenant-id"); } [Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] [InlineData(",,")] public void ParseCsv_ReturnsNullForEmptyInput(string? csv) => ToolHeaderPolicy.ParseCsv(csv).Should().BeNull(); [Fact] public void ParseCsv_TrimsAndUrlDecodes() { var parsed = ToolHeaderPolicy.ParseCsv("x-tenant-id, x-app-* ,accept%2Dlanguage"); parsed.Should().BeEquivalentTo(["x-tenant-id", "x-app-*", "accept-language"]); } } Path: redb-route/tests/redb.Route.Tests.Llm/TranscriptionProviderTests.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/TranscriptionProviderTests.cs ---- using System.Net; using System.Text; using AwesomeAssertions; using redb.Route.Llm; using redb.Route.Llm.Providers; namespace redb.Route.Tests.Llm; /// /// request/response mapping, driven through a /// stub — no live key, no audio, deterministic. /// /// The interesting part of a speech transport is not the happy path but the shape of the /// upload: speech endpoints choose a decoder from the file name they are handed, and a /// route whose Ogg/Opus voice note arrives announced as "some bytes" gets a decode error /// instead of a transcription. /// /// public sealed class TranscriptionProviderTests { private sealed class StubHandler( string responseBody, HttpStatusCode status = HttpStatusCode.OK, string mediaType = "application/json") : HttpMessageHandler { public HttpRequestMessage? LastRequest { get; private set; } public string? LastBody { get; private set; } protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) { LastRequest = request; LastBody = request.Content is null ? null : await request.Content.ReadAsStringAsync(ct); return new HttpResponseMessage(status) { Content = new StringContent(responseBody, Encoding.UTF8, mediaType) }; } } private static LlmConnectionFactory Factory(string provider = "openai", string model = "whisper-1") => new() { Provider = provider, ModelId = model, ApiKey = "sk-test" }; private static TranscriptionRequest Voice(string fileName = "voice.oga") => new(new byte[] { 0x4F, 0x67, 0x67, 0x53 }, fileName, Language: "ru"); [Fact] public async Task TranscribeAsync_ReadsTheText_AndShapesTheUpload() { var handler = new StubHandler("""{"text":" привет "}"""); var provider = new OpenAiTranscriptionProvider(Factory(), new HttpClient(handler)); var result = await provider.TranscribeAsync(Voice()); result.Text.Should().Be("привет", "trailing whitespace is the model's, not the speaker's"); handler.LastRequest!.RequestUri!.ToString().Should().Be("https://api.openai.com/v1/audio/transcriptions"); handler.LastRequest.Headers.Authorization!.ToString().Should().Be("Bearer sk-test"); var body = handler.LastBody!; body.Should().Contain("whisper-1", "the model has to be named in the form, not the URL"); body.Should().Contain("filename=voice.oga", "speech endpoints pick a demuxer by extension — the name is what decodes the file"); body.Should().Contain("audio/ogg"); body.Should().Contain("name=language").And.Contain("ru"); } [Fact] public async Task TranscribeAsync_SilenceIsAnEmptyString_NotAFailure() { var handler = new StubHandler("""{"text":""}"""); var provider = new OpenAiTranscriptionProvider(Factory(), new HttpClient(handler)); var result = await provider.TranscribeAsync(Voice()); // Silence and music transcribe to nothing. That is an answer the route can act on // ("I did not hear speech"), and turning it into an exception would make it // indistinguishable from a broken server. result.Text.Should().BeEmpty(); } [Fact] public async Task TranscribeAsync_AcceptsAPlainTextAnswer() { // Several local servers ignore response_format and answer with the bare text. A // transcription that arrived is not worth discarding over its envelope. var handler = new StubHandler("привет", mediaType: "text/plain"); var provider = new OpenAiTranscriptionProvider(Factory("lmstudio"), new HttpClient(handler)); (await provider.TranscribeAsync(Voice())).Text.Should().Be("привет"); } [Fact] public async Task TranscribeAsync_ReadsLanguageAndDurationWhenTheProviderReportsThem() { var handler = new StubHandler("""{"text":"hi","language":"russian","duration":12.5}"""); var provider = new OpenAiTranscriptionProvider(Factory(), new HttpClient(handler)); var result = await provider.TranscribeAsync(Voice()); result.Language.Should().Be("russian"); result.DurationSeconds.Should().Be(12.5); } [Fact] public async Task TranscribeAsync_TypesTheFailure_SoDegradingIsNotBlind() { var handler = new StubHandler("""{"error":"slow down"}""", HttpStatusCode.TooManyRequests); var provider = new OpenAiTranscriptionProvider(Factory(), new HttpClient(handler)); // A route that answers "sorry, I did not catch that" must not say it to a person // whose recording was fine and whose server was merely busy. var act = async () => await provider.TranscribeAsync(Voice()); await act.Should().ThrowAsync(); } [Fact] public async Task TranscribeAsync_EmptyAudioIsRejectedBeforeTheCall() { var handler = new StubHandler("""{"text":"should never be asked for"}"""); var provider = new OpenAiTranscriptionProvider(Factory(), new HttpClient(handler)); var act = async () => await provider.TranscribeAsync( new TranscriptionRequest(ReadOnlyMemory.Empty, "voice.oga")); await act.Should().ThrowAsync(); handler.LastRequest.Should().BeNull("a zero-byte upload is a bug upstream, not silence"); } [Fact] public async Task TranscribeAsync_LocalServerNeedsNoKey() { var handler = new StubHandler("""{"text":"локально"}"""); var factory = new LlmConnectionFactory { Provider = "local", ModelId = "large-v3", BaseUrl = new Uri("http://127.0.0.1:8083/v1/") }; var provider = new OpenAiTranscriptionProvider(factory, new HttpClient(handler)); (await provider.TranscribeAsync(Voice())).Text.Should().Be("локально"); handler.LastRequest!.RequestUri!.ToString() .Should().Be("http://127.0.0.1:8083/v1/audio/transcriptions"); handler.LastRequest.Headers.Authorization.Should().BeNull( "a whisper server on loopback has no key to send, and sending an empty Bearer is a 401"); provider.ProviderId.Should().Be("local"); } } Path: redb-route/tests/redb.Route.Tests.Llm/Transport/HttpPrincipalToAgentTests.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/Transport/HttpPrincipalToAgentTests.cs ---- using System.Net; using System.Net.Sockets; using System.Security.Claims; using redb.Route.Http; using redb.Route.Tests.Llm.TestHelpers; using LlmDsl = redb.Route.Llm.Fluent.Llm; namespace redb.Route.Tests.Llm.Transport; /// /// The joint level: a caller identified by the HTTP transport /// () drives an LLM route whose tool demands a claim. /// /// The other levels prove the halves — the transport puts the principal on the exchange, the engine /// enforces claims read from the exchange's principal — and each of them stubs the other side. Here /// nothing is stubbed: the request goes over a real socket, the resolver identifies it, and the tool /// fires (or not) on what the transport established. /// /// [Trait("Category", "Governance")] public sealed class HttpPrincipalToAgentTests { private const string Schema = """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}"""; private const string Input = """{"q":"x"}"""; private const string Claim = "orders:read"; private const string TokenHeader = "X-Test-Token"; private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); /// A resolver that knows one token, in the shape a real middleware would use. private static HttpHostingOptions Hosting(string claim, bool authenticated = true) => new() { ResolvePrincipal = ctx => Task.FromResult( ctx.Request.Headers[TokenHeader].ToString() == "good" ? new ClaimsPrincipal(new ClaimsIdentity( [new Claim("scope", claim)], authenticated ? "test" : null)) : null) }; private static async Task SendAsync(int port, bool withToken) { using var http = new HttpClient(); using var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, $"http://127.0.0.1:{port}/agent") { Content = new StringContent("Call the tool.") }; if (withToken) request.Headers.Add(TokenHeader, "good"); return await http.SendAsync(request); } [Fact] public async Task CallerIdentifiedByTheTransport_SatisfiesTheToolClaim() { var port = FreePort(); var toolName = $"http_{Guid.NewGuid():N}"[..20]; var provider = new FakeProvider() .EnqueueToolUse(toolName, Input, "tu_1") .EnqueueText("done"); var tool = new EchoToolRoute(toolName, "Look up a fact.", Schema, """{"answer":"42"}""", requiredClaims: [Claim]); await using var host = LiveLlmHost.Build( engineFromDi: true, httpHosting: Hosting(Claim), httpPort: port) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From($"http:127.0.0.1:{port}/agent?inOut=true") .To(LlmDsl.Factory("demo").Tools(toolName).MaxIterations(4).AsUri()) .To("mock:done")); var response = await SendAsync(port, withToken: true); response.IsSuccessStatusCode.Should().BeTrue( $"the route ran to completion, got {(int)response.StatusCode}"); tool.CapturedInputs.Should().HaveCount(1, "the claim came from the transport-verified caller — no test hook put anything on the exchange"); } [Fact] public async Task CallerWithoutTheClaim_IsDeniedByTheEngine() { var port = FreePort(); var toolName = $"httpdeny_{Guid.NewGuid():N}"[..20]; var provider = new FakeProvider() .EnqueueToolUse(toolName, Input, "tu_1") .EnqueueText("done"); var tool = new EchoToolRoute(toolName, "Look up a fact.", Schema, """{"answer":"42"}""", requiredClaims: [Claim]); // The caller authenticates and holds a different scope: the transport did its job, and the engine // still must refuse — an identified caller is not automatically an authorised one. await using var host = LiveLlmHost.Build( engineFromDi: true, httpHosting: Hosting("billing:read"), httpPort: port) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From($"http:127.0.0.1:{port}/agent?inOut=true") .To(LlmDsl.Factory("demo").Tools(toolName).MaxIterations(4).AsUri()) .To("mock:done")); await SendAsync(port, withToken: true); tool.CapturedInputs.Should().BeEmpty("the tool's claim is not in the caller's scope"); } [Fact] public async Task AnonymousCaller_IsDeniedByTheEngine() { var port = FreePort(); var toolName = $"httpanon_{Guid.NewGuid():N}"[..20]; var provider = new FakeProvider() .EnqueueToolUse(toolName, Input, "tu_1") .EnqueueText("done"); var tool = new EchoToolRoute(toolName, "Look up a fact.", Schema, """{"answer":"42"}""", requiredClaims: [Claim]); await using var host = LiveLlmHost.Build( engineFromDi: true, httpHosting: Hosting(Claim), httpPort: port) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From($"http:127.0.0.1:{port}/agent?inOut=true") .To(LlmDsl.Factory("demo").Tools(toolName).MaxIterations(4).AsUri()) .To("mock:done")); await SendAsync(port, withToken: false); tool.CapturedInputs.Should().BeEmpty( "the resolver refused to identify the caller, so there is no scope to check"); } [Fact] public async Task IdentityWithoutAuthenticationType_IsDenied() { var port = FreePort(); var toolName = $"httpauth_{Guid.NewGuid():N}"[..20]; var provider = new FakeProvider() .EnqueueToolUse(toolName, Input, "tu_1") .EnqueueText("done"); var tool = new EchoToolRoute(toolName, "Look up a fact.", Schema, """{"answer":"42"}""", requiredClaims: [Claim]); // The scope claim is present, but the identity was built without an authentication type: the source // treats it as unverified, and the tool must not run on an unverified identity. await using var host = LiveLlmHost.Build( engineFromDi: true, httpHosting: Hosting(Claim, authenticated: false), httpPort: port) .AddFactory("demo", new LlmConnectionFactory { Provider = "stub", PrebuiltProvider = provider }); await host.StartAsync(tool, r => r.From($"http:127.0.0.1:{port}/agent?inOut=true") .To(LlmDsl.Factory("demo").Tools(toolName).MaxIterations(4).AsUri()) .To("mock:done")); await SendAsync(port, withToken: true); tool.CapturedInputs.Should().BeEmpty( "an unauthenticated identity is not a verified caller, whatever claims it carries"); } } Path: redb-route/tests/redb.Route.Tests.Llm/appsettings.json 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/appsettings.json ---- { "ConnectionStrings": { "Postgres": "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Pooling=true;Include Error Detail=true;Timeout=600;Command Timeout=600;Options=-c jit=off", "MsSql": "Server=msdb;Database=redb;User Id=sa;Password=1;TrustServerCertificate=true;Command Timeout=600;", "Sqlite": "Data Source=redb_tests_route_llm.db" } } Path: redb-route/tests/redb.Route.Tests.Llm/redb.Route.Tests.Llm.csproj 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/redb.Route.Tests.Llm.csproj ---- PreserveNewest PreserveNewest Path: redb-route/tests/redb.Route.Tests.Llm/xunit.runner.json 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/xunit.runner.json ---- { "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json", "parallelizeTestCollections": false }