Path: redb-route/redb.Route.Llm/Engine/Storage/IKnowledgeStore.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/Engine/Storage/IKnowledgeStore.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; namespace redb.Route.Llm.Engine.Storage; /// /// Persists embedding-backed knowledge chunks for retrieval-augmented agent /// runs. The MVP contract is intentionally narrow — upsert + cosine-similarity /// query over an opaque vector. Providers that index the chunks separately /// (e.g. pgvector, Qdrant) wrap this interface. /// /// The optional exchange parameter on every method carries the route /// pipeline's current exchange; REDB-backed implementations resolve a /// per-exchange through /// IRouteContext.GetRedbService(name, exchange). In-memory /// implementations ignore it. /// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an /// ambient (a , a /// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared /// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange, /// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations /// take part in no transaction. /// /// public interface IKnowledgeStore { /// Persists or replaces a chunk by its . Task UpsertAsync(KnowledgeChunk chunk, IExchange? exchange = null, CancellationToken ct = default); /// /// Persists or replaces many chunks at once. Bulk-friendly stores commit /// the whole set in a single transaction — orders of magnitude faster than /// looping . The default implementation falls back /// to a sequential loop for stores that have no bulk path. /// async Task UpsertManyAsync(IEnumerable chunks, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(chunks); foreach (var chunk in chunks) { ct.ThrowIfCancellationRequested(); await UpsertAsync(chunk, exchange, ct).ConfigureAwait(false); } } /// Drops a chunk by id; no-op when not found. Task DeleteAsync(string chunkId, IExchange? exchange = null, CancellationToken ct = default); /// Returns the most-similar chunks for the query embedding. Task> SearchAsync( ReadOnlyMemory queryEmbedding, int topK, string? collection = null, IExchange? exchange = null, CancellationToken ct = default); /// /// Keyword fallback — returns up to chunks whose text /// contains (case-insensitive substring), ranked by /// occurrence count. For corpora with no embeddings, or callers with no query /// vector (e.g. a small structured rule-set where exact terms beat semantic /// similarity). Backends push the substring filter down (SQL LIKE) and /// rank only the matched set — no full-table scan. /// /// The default implementation throws ; /// stores that can express a substring filter override it. Adding this as a /// default member keeps the interface source-compatible for existing /// implementers. /// /// Task> SearchTextAsync( string query, int topK, string? collection = null, IExchange? exchange = null, CancellationToken ct = default) => throw new NotSupportedException( $"{GetType().Name} does not support keyword search; supply a query embedding and call SearchAsync."); } /// A single embedded knowledge chunk. public sealed class KnowledgeChunk { /// Stable identifier — caller-supplied so updates can replace a chunk in place. public required string Id { get; init; } /// Optional collection / namespace partition (e.g. tenant id, document set). public string? Collection { get; init; } /// Original chunk text shown to the model when the chunk is retrieved. public required string Text { get; init; } /// Embedding vector; dimensionality is implementation-defined. public required ReadOnlyMemory Embedding { get; init; } /// Optional structured metadata (JSON) — e.g. source URL, page number. public string? MetadataJson { get; init; } /// Wall-clock timestamp the chunk was last upserted. public DateTime UpdatedAtUtc { get; init; } = DateTime.UtcNow; } /// A chunk returned by , with score. public sealed record KnowledgeSearchResult(KnowledgeChunk Chunk, double Score); /// /// In-memory knowledge store — does an O(N) cosine-similarity scan on every /// query. Suitable for unit tests and small fixtures only; swap in the /// production store for anything larger than a few thousand chunks. /// public sealed class InMemoryKnowledgeStore : IKnowledgeStore { private readonly ConcurrentDictionary _chunks = new(StringComparer.Ordinal); /// public Task UpsertAsync(KnowledgeChunk chunk, IExchange? exchange = null, CancellationToken ct = default) { _chunks[chunk.Id] = chunk; return Task.CompletedTask; } /// public Task DeleteAsync(string chunkId, IExchange? exchange = null, CancellationToken ct = default) { _chunks.TryRemove(chunkId, out _); return Task.CompletedTask; } /// public Task> SearchAsync( ReadOnlyMemory queryEmbedding, int topK, string? collection = null, IExchange? exchange = null, CancellationToken ct = default) { var query = queryEmbedding.Span; var ranked = new List(); foreach (var chunk in _chunks.Values) { if (collection is not null && !string.Equals(chunk.Collection, collection, StringComparison.Ordinal)) continue; var score = CosineSimilarity(query, chunk.Embedding.Span); ranked.Add(new KnowledgeSearchResult(chunk, score)); } var top = ranked.OrderByDescending(r => r.Score).Take(Math.Max(1, topK)).ToArray(); return Task.FromResult>(top); } /// public Task> SearchTextAsync( string query, int topK, string? collection = null, IExchange? exchange = null, CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(query)) return Task.FromResult>([]); var ranked = new List(); foreach (var chunk in _chunks.Values) { if (collection is not null && !string.Equals(chunk.Collection, collection, StringComparison.Ordinal)) continue; var score = KnowledgeTextMatch.CountOccurrences(chunk.Text, query); if (score == 0) continue; ranked.Add(new KnowledgeSearchResult(chunk, score)); } var top = ranked.OrderByDescending(r => r.Score).Take(Math.Max(1, topK)).ToArray(); return Task.FromResult>(top); } private static double CosineSimilarity(ReadOnlySpan a, ReadOnlySpan b) { var len = Math.Min(a.Length, b.Length); if (len == 0) return 0d; double dot = 0, na = 0, nb = 0; for (var i = 0; i < len; i++) { dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; } var denom = Math.Sqrt(na) * Math.Sqrt(nb); return denom <= 0 ? 0d : dot / denom; } } /// Shared keyword-match scoring for implementations. internal static class KnowledgeTextMatch { /// Case-insensitive count of non-overlapping occurrences in . public static int CountOccurrences(string? haystack, string? needle) { if (string.IsNullOrEmpty(haystack) || string.IsNullOrEmpty(needle)) return 0; var count = 0; var i = 0; while ((i = haystack.IndexOf(needle, i, StringComparison.OrdinalIgnoreCase)) >= 0) { count++; i += needle.Length; } return count; } }