Path: redb-route/redb.Route.Llm/Storage/Redb/RedbConversationStore.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/redb.Route.Llm/Storage/Redb/RedbConversationStore.cs ---- using System.Collections.Concurrent; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Contracts; 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.Schemas; using redb.Route.RedbCore; using redb.Route.RedbCore.Extensions; namespace redb.Route.Llm.Storage.Redb; /// /// REDB-backed . Tree integrity is enforced by /// CreateChildAsync; transcript reads use redb's tree primitives /// (TreeQuery<T>(root) for descendants, GetPathToRootAsync /// for breadcrumbs — root → leaf order) — server-side tree traversal, not /// client-side rebuilding. /// Per-row business identifiers live on _objects base columns — /// value_string for the conversation/message id (partial index on /// PostgreSQL/SQLite; MSSQL cannot index NVARCHAR(MAX)) and value_long /// on each message for the conversation FK (== root _objects.id, indexed /// on every provider). The conversation id also rides, normalized, in the /// root's _objects._value_unique: the per-scheme unique index makes /// concurrent creators of one conversation converge on a single root instead /// of splitting the transcript. /// /// Conversation isolation is enforced by the value_long FK, not by tree /// shape. Head detection and message lookup are scoped by it explicitly, so a /// read can never surface — and a write can never attach under — another /// conversation's node, independent of how a provider evaluates tree filters. /// /// Content blocks are stored as a typed nested array, no JSON marshalling /// for our own schema. /// /// The is resolved per call through /// : /// when an is supplied (the engine forwards the route /// pipeline's exchange) the route framework hands out a per-exchange scoped /// instance and disposes it with the exchange. The named instance — /// ?redb=my-llm-db on the URI — is read from /// exchange.Properties[LlmKeys.RedbName]; missing or null falls back to /// the default IRedbService registered in the context (the host's /// instance from services.AddRedb()). /// /// public sealed class RedbConversationStore : IConversationStore { private readonly IRouteContext _context; private readonly string? _defaultRedbName; private readonly ConcurrentDictionary _rootIds = new(StringComparer.Ordinal); private static readonly TimeSpan RootCacheTtl = TimeSpan.FromMinutes(10); /// /// Creates a new store backed by the route context's redb instance(s). /// /// Route context that knows how to resolve named/default . /// /// Optional default name. When the runtime exchange does not carry /// in its properties this name is used; when /// it is null/empty the default unnamed instance is used. /// public RedbConversationStore(IRouteContext context, string? defaultRedbName = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _defaultRedbName = defaultRedbName; } private readonly record struct CachedRoot(long Id, DateTimeOffset ExpiresAt); /// /// Resolves the redb instance for this call and returns the name it was /// resolved under. The name is part of the root-id cache key: the instance is /// chosen per exchange (?redb= → LlmKeys.RedbName), so a cache /// keyed by conversation id alone would hand back an id resolved in database A /// while the call runs against database B. /// Without an exchange the call gets a scope of its own in , for the caller to dispose, /// so concurrent calls do not share the context's single instance and its one connection. /// private (IRedbService Redb, string Name) Resolve(IExchange? exchange, out RedbScope? owned) { var name = _defaultRedbName; if (exchange is not null && exchange.Properties.TryGetValue(LlmKeys.RedbName, out var raw) && raw is string s && s.Length > 0) { name = s; } var effective = name ?? string.Empty; if (exchange is not null) { owned = null; return (_context.GetRedbService(effective, exchange), effective); } owned = _context.CreateRedbScope(name); return (owned.Service, effective); } // NUL separator: instance name and conversation id are both opaque caller // strings, so any printable separator could be forged into a collision // ("a" + "b:c" vs "a:b" + "c"). private const char CacheKeySeparator = (char)0; private static string CacheKey(string redbName, string conversationId) => string.Concat(redbName, CacheKeySeparator, conversationId); /// public async Task AppendAsync( string conversationId, string? parentMessageId, LlmMessage message, ConversationMessageMeta meta, IExchange? exchange = null, CancellationToken ct = default) { var (redb, redbName) = Resolve(exchange, out var owned); await using var ownedScope = owned; var rootId = await GetOrCreateRootIdAsync(redb, redbName, conversationId, ct).ConfigureAwait(false); // The root object itself is needed only as the tree parent of a first-level // message; the counter update below re-reads it under its own lock anyway, // so threaded appends (parent supplied) skip the full root load entirely. IRedbObject parentObj; if (parentMessageId is not null) { // Scoped by rootId on purpose: the lookup is by an opaque caller-supplied // id over the whole schema, so an unscoped resolve would happily attach // this message under another conversation's node — a cross-conversation // write that no later read can undo. parentObj = await FindMessageByValueStringAsync(redb, parentMessageId, rootId).ConfigureAwait(false) ?? throw new InvalidOperationException($"Parent message {parentMessageId} not found in conversation {conversationId}."); } else { parentObj = await redb.LoadAsync(rootId).ConfigureAwait(false) ?? throw new InvalidOperationException($"Conversation root {conversationId} disappeared between lookup and load."); } var newId = Guid.NewGuid().ToString("N"); var child = new TreeRedbObject { value_string = newId, value_long = rootId, Props = new MessageProps { Role = message.Role, Iteration = meta.Iteration, CreatedAtUtc = meta.CreatedAtUtc, ProviderId = meta.ProviderId, ModelId = meta.ModelId, StopReason = meta.StopReason?.ToString(), ToolUseId = meta.ToolUseId, InputTokens = meta.Usage.InputTokens, OutputTokens = meta.Usage.OutputTokens, CacheCreationInputTokens = meta.Usage.CacheCreationInputTokens, CacheReadInputTokens = meta.Usage.CacheReadInputTokens, Temperature = meta.Temperature, MaxTokens = meta.MaxTokens, TopP = meta.TopP, PromptTemplateName = meta.PromptTemplateName, PromptTemplateVersion = meta.PromptTemplateVersion, ToolSetHash = meta.ToolSetHash, ProviderSystemFingerprint = meta.ProviderSystemFingerprint, UserId = meta.UserId, AuditTags = meta.AuditTags is { Count: > 0 } ? new Dictionary(meta.AuditTags, StringComparer.Ordinal) : null, FactoryName = meta.FactoryName, BaseUrl = meta.BaseUrl, ProviderResponseId = meta.ProviderResponseId, LatencyMs = meta.LatencyMs, ApiKeyFingerprint = meta.ApiKeyFingerprint, RetryCount = meta.RetryCount, Content = ToStoredBlocks(message.Content) } }; await redb.CreateChildAsync(child, parentObj).ConfigureAwait(false); // Counter update is a read-modify-write shared by every concurrent append // (parallel tool branches, other nodes) — serialise it on the root row the // same way RedbCostBudgetStore does, or increments get lost. await redb.Context.ExecuteAtomicAsync(async () => { await redb.LockForUpdateAsync(rootId).ConfigureAwait(false); // Re-read BY QUERY after the lock, not redb.LoadAsync. The core has since // stopped serving the zero-DB cache shortcut inside a transaction, but the query path // guarantees a fresh row read regardless of cache mode or core version — // and a stale pre-lock copy here would lose another node's increments, // the exact defect this lock exists to prevent. var fresh = await redb.Query() .WhereRedb(o => o.Id == rootId) .FirstOrDefaultAsync() .ConfigureAwait(false) ?? throw new InvalidOperationException( $"Conversation root {conversationId} disappeared during counter update."); var activityAt = new DateTimeOffset(DateTime.SpecifyKind(meta.CreatedAtUtc, DateTimeKind.Utc)); fresh.Props.LastActivityAtUtc = activityAt; fresh.Props.TotalInputTokens += meta.Usage.InputTokens; fresh.Props.TotalOutputTokens += meta.Usage.OutputTokens; // Framework does not auto-stamp date_modify; mirror LastActivityAtUtc. fresh.date_modify = activityAt; await redb.SaveAsync(fresh).ConfigureAwait(false); }).ConfigureAwait(false); return newId; } /// public async Task> LoadPathAsync( string conversationId, string? leafId = null, IExchange? exchange = null, CancellationToken ct = default) { var (redb, redbName) = Resolve(exchange, out var owned); await using var ownedScope = owned; var rootId = await GetOrCreateRootIdAsync(redb, redbName, conversationId, ct).ConfigureAwait(false); TreeRedbObject? leafObj; if (leafId is not null) { leafObj = await FindMessageByValueStringAsync(redb, leafId, rootId).ConfigureAwait(false); if (leafObj is null) return []; } else { // Head detection scoped by the conversation FK, not by tree traversal. // // The newest message of a conversation is always a leaf — anything that // became a parent has a child created after it — so "newest by // date_create within this conversation" is exactly "the freshest leaf", // without depending on how a provider implements WhereLeaves(). That // matters: a rooted TreeQuery(root).WhereLeaves() used to be evaluated // as "freshest leaf of the whole schema" (fixed for Pro in d88ff9fe, // still open for the Free PVT routing), which returned another // conversation's transcript and then attached the next message under it. // // value_long carries the root's _objects.id and lives on the indexed // _objects row, so this stays a single-row server-side lookup. var head = await redb.Query() .WhereRedb(o => o.ValueLong == rootId) .OrderByDescendingRedb(o => o.DateCreate) .FirstOrDefaultAsync() .ConfigureAwait(false); if (head is null) return []; // The path walker needs a TreeRedbObject; reload the leaf as a // single-node tree to satisfy GetPathToRootAsync. leafObj = await redb.LoadTreeAsync(head.id, maxDepth: 0).ConfigureAwait(false); if (leafObj is null) return []; } // Server-side ancestor walk; returns root → leaf order. The conversation // root is a ConversationProps node — GetPathToRootAsync // still returns it (cast to MessageProps with default Props), so trim by id. // The Role guard is belt-and-braces for that cast: a role-less row is not a // message, and letting one through means posting an empty role to the // provider (a 400 that looks like a model problem, not a storage one). var ancestors = (await redb.GetPathToRootAsync(leafObj).ConfigureAwait(false)).ToList(); var path = ancestors .Where(a => a.id != rootId && !string.IsNullOrEmpty(a.Props.Role)) .Select(row => Materialize(row, conversationId, rootId, parentLookup: null)) .ToList(); return path; } /// public async Task> LoadTreeAsync( string conversationId, IExchange? exchange = null, CancellationToken ct = default) => await LoadAllMessagesAsync(conversationId, exchange).ConfigureAwait(false); private async Task> LoadAllMessagesAsync(string conversationId, IExchange? exchange) { var (redb, redbName) = Resolve(exchange, out var owned); await using var ownedScope = owned; var rootId = await GetOrCreateRootIdAsync(redb, redbName, conversationId, CancellationToken.None).ConfigureAwait(false); var rootObj = await redb.LoadAsync(rootId).ConfigureAwait(false); if (rootObj is null) return []; // Server-side tree traversal: every MessageProps descendant of this // conversation root, regardless of nesting depth. ToFlatListAsync // skips Parent/Children pointer building — we rebuild parent linkage // manually below via the idToValueString lookup. var rows = await redb.TreeQuery(rootObj) .ToFlatListAsync() .ConfigureAwait(false); // Map redb id → business id (value_string) so child rows can resolve // their parent's business id from the tree's native parent_id. var idToValueString = rows.ToDictionary(r => r.id, r => r.value_string); var list = new List(rows.Count); foreach (var row in rows) list.Add(Materialize(row, conversationId, rootId, idToValueString)); return list; } private static ConversationMessage Materialize( TreeRedbObject row, string conversationId, long rootId, IReadOnlyDictionary? parentLookup) { string? parentValueString = null; if (row.parent_id is { } pid && pid != rootId && parentLookup is not null && parentLookup.TryGetValue(pid, out var pvs)) { parentValueString = pvs; } return new ConversationMessage { Id = row.value_string ?? row.id.ToString(), ParentId = parentValueString, ConversationId = conversationId, Message = new LlmMessage { Role = row.Props.Role, Content = FromStoredBlocks(row.Props.Content) }, Meta = new ConversationMessageMeta { CreatedAtUtc = row.Props.CreatedAtUtc.UtcDateTime, Iteration = row.Props.Iteration, ProviderId = row.Props.ProviderId, ModelId = row.Props.ModelId, StopReason = ParseStopReason(row.Props.StopReason), Usage = new LlmUsage( row.Props.InputTokens, row.Props.OutputTokens, row.Props.CacheCreationInputTokens, row.Props.CacheReadInputTokens), ToolUseId = row.Props.ToolUseId, Temperature = row.Props.Temperature, MaxTokens = row.Props.MaxTokens, TopP = row.Props.TopP, PromptTemplateName = row.Props.PromptTemplateName, PromptTemplateVersion = row.Props.PromptTemplateVersion, ToolSetHash = row.Props.ToolSetHash, ProviderSystemFingerprint = row.Props.ProviderSystemFingerprint, UserId = row.Props.UserId, AuditTags = row.Props.AuditTags is { Count: > 0 } ? new Dictionary(row.Props.AuditTags, StringComparer.Ordinal) : null, FactoryName = row.Props.FactoryName, BaseUrl = row.Props.BaseUrl, ProviderResponseId = row.Props.ProviderResponseId, LatencyMs = row.Props.LatencyMs, ApiKeyFingerprint = row.Props.ApiKeyFingerprint, RetryCount = row.Props.RetryCount } }; } private async Task GetOrCreateRootIdAsync( IRedbService redb, string redbName, string conversationId, CancellationToken ct) { // TTL-bound cache: stale entries (e.g. someone purged the conversation // out-of-band) self-heal after RootCacheTtl instead of pinning a dead // id for the whole process lifetime. Keyed by (instance, conversation) — // the same conversation id in two named databases resolves to two // different root ids, and a conversation-only key would cross them. var key = CacheKey(redbName, conversationId); var now = DateTimeOffset.UtcNow; if (_rootIds.TryGetValue(key, out var cached) && cached.ExpiresAt > now) return cached.Id; var hit = await redb.Query() .WhereRedb(x => x.ValueUnique == RedbUniqueKey.Normalize(conversationId)) .FirstOrDefaultAsync() .ConfigureAwait(false); if (hit is not null) { _rootIds[key] = new CachedRoot(hit.id, now + RootCacheTtl); return hit.id; } // The conversation key rides in _value_unique too: of two concurrent creators // (parallel exchanges, cluster nodes) the per-scheme unique index lets exactly // one root through — without it each writer minted its own root and the // conversation split in two, every reader seeing an arbitrary half. var root = new RedbObject { value_string = conversationId, ValueUnique = RedbUniqueKey.Normalize(conversationId), Props = new ConversationProps { TenantId = string.Empty, Status = "active", StartedAtUtc = now, LastActivityAtUtc = now } }; long id; try { id = await redb.SaveAsync(root).ConfigureAwait(false); } catch (RedbUniqueViolationException) { // Lost the creation race. Resolve the winner by the collided key — exactly // one row can hold it — and cache THAT id, never our stillborn row's. var winnerKey = root.ValueUnique; var winner = await redb.Query() .WhereRedb(x => x.ValueUnique == winnerKey) .FirstOrDefaultAsync() .ConfigureAwait(false); if (winner is null) throw; // the key vanished again (purged mid-race) — surface the original failure id = winner.id; } _rootIds[key] = new CachedRoot(id, now + RootCacheTtl); return id; } /// /// Resolves a message by its business id within one conversation. /// is not an optimisation — the id is opaque and /// caller-supplied, so an unscoped lookup lets a caller reach (and, through /// AppendAsync, write under) another conversation's node. Returns null /// when the message does not exist or belongs to a different conversation; /// the two cases are deliberately indistinguishable to the caller. /// private static async Task?> FindMessageByValueStringAsync( IRedbService redb, string messageId, long rootId) { // Deliberately NOT ValueUnique (the one value_string lookup left): messages carry // no unique key — messageId is only unique within its conversation, scoped by rootId here. var hit = await redb.Query() .WhereRedb(x => x.ValueString == messageId && x.ValueLong == rootId) .FirstOrDefaultAsync() .ConfigureAwait(false); return hit is null ? null : await redb.LoadTreeAsync(hit.id, maxDepth: 0).ConfigureAwait(false); } private static MessageContentBlock[] ToStoredBlocks(IReadOnlyList blocks) { if (blocks.Count == 0) return []; var arr = new MessageContentBlock[blocks.Count]; for (var i = 0; i < blocks.Count; i++) { arr[i] = blocks[i] switch { LlmTextBlock t => new MessageContentBlock { Kind = "text", Text = t.Text }, LlmToolUseBlock u => new MessageContentBlock { Kind = "tool_use", ToolUseId = u.ToolUseId, ToolName = u.Name, InputJson = u.InputJson }, LlmToolResultBlock r => new MessageContentBlock { Kind = "tool_result", ToolUseId = r.ToolUseId, OutputJson = r.OutputJson, IsError = r.IsError }, // The thought goes in its own field, with the signature it is authenticated by. LlmThinkingBlock t => new MessageContentBlock { Kind = "thinking", ThinkingText = t.Text, Signature = t.Signature, RedactedData = t.RedactedData }, _ => throw new NotSupportedException( $"Content block type '{blocks[i].GetType().Name}' has no stored form.") }; } return arr; } private static IReadOnlyList FromStoredBlocks(MessageContentBlock[]? stored) { if (stored is null || stored.Length == 0) return []; var list = new List(stored.Length); foreach (var b in stored) { list.Add(b.Kind switch { "text" => new LlmTextBlock(b.Text ?? string.Empty), "tool_use" => new LlmToolUseBlock(b.ToolUseId ?? string.Empty, b.ToolName ?? string.Empty, b.InputJson ?? "{}"), "tool_result" => new LlmToolResultBlock(b.ToolUseId ?? string.Empty, b.OutputJson ?? string.Empty, b.IsError), "thinking" => new LlmThinkingBlock( b.ThinkingText ?? string.Empty, b.Signature, b.RedactedData), _ => throw new InvalidOperationException( $"Stored content block kind '{b.Kind}' is unknown.") }); } return list; } private static LlmStopReason? ParseStopReason(string? raw) => Enum.TryParse(raw, out var parsed) ? parsed : null; }