Path: redb-route/redb.Route.Llm/Storage/Redb/RedbKnowledgeStore.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/RedbKnowledgeStore.cs ---- using System.Runtime.InteropServices; using System.Text.Json; 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.Storage.Redb.Schemas; using redb.Route.RedbCore; using redb.Route.RedbCore.Extensions; namespace redb.Route.Llm.Storage.Redb; /// /// REDB-backed . One row per chunk; every chunk /// field is stored on the indexed base columns and /// the scheme is intentionally /// property-less — chunks read / write a single _objects row /// with zero _props rows. Column layout: /// /// value_string — stable chunk id (business key; partial index on /// PostgreSQL/SQLite, no index on MSSQL — NVARCHAR(MAX)). New rows also /// carry it, normalized, in _value_unique: the per-scheme unique /// index keeps concurrent upserts of one id on a single row. /// name — collection / namespace. /// note — JSON envelope {"text":"...","meta":"..."}. /// value_bytes — embedding, written as the raw byte view of /// the float[] via . /// value_long — embedding dimensionality (sanity check). /// /// /// Search strategy: the MVP loads candidate chunks (filtered by /// collection) and computes cosine similarity in process. Acceptable up to a /// few thousand chunks. For production scale plug in a pgvector / Qdrant /// adapter that overrides only . /// /// /// The store does not own an instance — each call /// resolves one through IRouteContext.GetRedbService(name, exchange), /// which honours the per-exchange scope cache. The redb name is read from /// exchange.Properties[LlmKeys.RedbName] (set by the LLM endpoint URI), /// falling back to the constructor-supplied default name and then to the host's /// default unnamed instance. /// /// public sealed class RedbKnowledgeStore : IKnowledgeStore { private readonly IRouteContext _context; private readonly string? _defaultRedbName; /// Creates the store. Scheme is synced by the host's redb.InitializeAsync(). public RedbKnowledgeStore(IRouteContext context, string? defaultRedbName = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _defaultRedbName = defaultRedbName; } /// /// The service a call works on: the exchange's with one; without one a scope of its own, handed back in /// for the caller to dispose, so concurrent calls do not share the context's single /// instance and its one connection. /// private IRedbService 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; if (exchange is not null) { owned = null; return _context.GetRedbService(name ?? string.Empty, exchange); } owned = _context.CreateRedbScope(name); return owned.Service; } /// public async Task UpsertAsync(KnowledgeChunk chunk, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(chunk); ArgumentException.ThrowIfNullOrWhiteSpace(chunk.Id); ArgumentException.ThrowIfNullOrWhiteSpace(chunk.Text); var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var existing = await redb.Query() .WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(chunk.Id)) .FirstOrDefaultAsync() .ConfigureAwait(false); if (existing is not null) { Populate(existing, chunk, out var row); await redb.SaveAsync(row).ConfigureAwait(false); return; } // The chunk id rides in _value_unique: two concurrent ingestors of one id race // to a single row — before, both inserted and searches returned duplicate hits. Populate(new RedbObject(), chunk, out var fresh); fresh.ValueUnique = RedbUniqueKey.Normalize(chunk.Id); try { await redb.SaveAsync(fresh).ConfigureAwait(false); } catch (RedbUniqueViolationException) { // Lost the creation race — an upsert is last-writer-wins, so write this // chunk onto the winner's row, resolved by the key that collided. var winnerKey = fresh.ValueUnique; var winner = await redb.Query() .WhereRedb(o => o.ValueUnique == winnerKey) .FirstOrDefaultAsync() .ConfigureAwait(false); if (winner is null) throw; // the key vanished again (deleted mid-race) Populate(winner, chunk, out var row); await redb.SaveAsync(row).ConfigureAwait(false); } } /// public async Task UpsertManyAsync(IEnumerable chunks, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(chunks); // One chunk per id even within one call — the last entry wins (re-chunking // pipelines do emit an id twice). Two fresh rows sharing an id would // otherwise self-collide on the unique index inside a single bulk save // (the pre-barrier code silently inserted both). var input = chunks .Where(c => c is not null && !string.IsNullOrWhiteSpace(c.Id) && !string.IsNullOrWhiteSpace(c.Text)) .GroupBy(c => c.Id, StringComparer.Ordinal) .Select(g => g.Last()) .ToList(); if (input.Count == 0) return; var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; await UpsertManyCoreAsync(redb, input, retryOnRace: true, ct).ConfigureAwait(false); } private static async Task UpsertManyCoreAsync( IRedbService redb, List input, bool retryOnRace, CancellationToken ct) { // ONE IN-clause lookup for all keys (partial index on PG/SQLite; a scan on // MSSQL), then ONE bulk SaveAsync — insert/update streams are internal. var keys = input.Select(c => c.Id).ToArray(); var existingByKey = (await redb.Query() .WhereRedb(o => keys.Contains(o.ValueString)) .ToListAsync() .ConfigureAwait(false)) .Where(o => o.value_string is not null) .ToDictionary(o => o.value_string!, StringComparer.Ordinal); if (!retryOnRace) { // Retry pass after a lost creation race: the winners hold the unique key — // resolve by it too, so every collided chunk becomes an update. var normByKey = input.ToDictionary(c => c.Id, c => RedbUniqueKey.Normalize(c.Id), StringComparer.Ordinal); var norms = normByKey.Values.ToArray(); var keyByNorm = normByKey.ToDictionary(kv => kv.Value, kv => kv.Key, StringComparer.Ordinal); var byUnique = await redb.Query() .WhereRedb(o => norms.Contains(o.ValueUnique)) .ToListAsync() .ConfigureAwait(false); foreach (var row in byUnique) if (row.ValueUnique is { } u && keyByNorm.TryGetValue(u, out var k)) existingByKey.TryAdd(k, row); } var rowsToSave = new List(input.Count); foreach (var chunk in input) { ct.ThrowIfCancellationRequested(); if (existingByKey.TryGetValue(chunk.Id, out var existing)) { // No Props-hash pre-check here: KnowledgeChunkProps is a // property-less marker (text/id/embedding live on the base // _objects columns, not Props), so ComputeHash() is always empty // and would treat every re-upsert as "unchanged" — silently // dropping real text/embedding updates. Always save the row; // SaveAsync's own change-tracking still diffs the base columns. Populate(existing, chunk, out var same); rowsToSave.Add(same); } else { Populate(new RedbObject(), chunk, out var fresh); fresh.ValueUnique = RedbUniqueKey.Normalize(chunk.Id); rowsToSave.Add(fresh); } } if (rowsToSave.Count == 0) return; try { await redb.SaveAsync(rowsToSave).ConfigureAwait(false); } catch (RedbUniqueViolationException) when (retryOnRace) { // A concurrent ingestor claimed one of the fresh chunk ids after our lookup // and the batch rolled back whole. The winners are visible now: rebuild from // a fresh lookup (collided ids become updates) and retry once — a second // violation is a real error. await UpsertManyCoreAsync(redb, input, retryOnRace: false, ct).ConfigureAwait(false); } } /// public async Task DeleteAsync(string chunkId, IExchange? exchange = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(chunkId); var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var row = await redb.Query() .WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(chunkId)) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is not null) await redb.SoftDeleteAsync([row]).ConfigureAwait(false); } /// public async Task> SearchAsync( ReadOnlyMemory queryEmbedding, int topK, string? collection = null, IExchange? exchange = null, CancellationToken ct = default) { if (queryEmbedding.Length == 0) return []; var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; // Pre-filter by collection on the indexed _objects.name column at the // SQL layer; the cosine pass is in-process. var rows = collection is null ? await redb.Query().ToListAsync().ConfigureAwait(false) : await redb.Query() .WhereRedb(o => o.Name == collection) .ToListAsync() .ConfigureAwait(false); if (rows.Count == 0) return []; var ranked = new List(rows.Count); var query = queryEmbedding.Span; foreach (var row in rows) { var embedding = DecodeEmbedding(row.value_bytes); var score = CosineSimilarity(query, embedding); ranked.Add(new KnowledgeSearchResult(MaterializeChunk(row, embedding), score)); } return ranked .OrderByDescending(r => r.Score) .Take(Math.Max(1, topK)) .ToArray(); } /// public async Task> SearchTextAsync( string query, int topK, string? collection = null, IExchange? exchange = null, CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(query)) return []; var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; // Push the substring filter to SQL (LIKE) on the indexed _objects.note // column — which holds the {text,meta} envelope. Only matching rows come // back; we never load the whole table. Collection stays an indexed // _objects.name equality in the same WHERE. // Case-insensitive substring → the parser maps Contains(.., OrdinalIgnoreCase) // to a server-side ILIKE (ComparisonOperator.ContainsIgnoreCase), so "Mask" // matches "mask"/"MASK" in SQL, not just in the in-process re-score below. var matches = collection is null ? await redb.Query() .WhereRedb(o => o.Note != null && o.Note.Contains(query, StringComparison.OrdinalIgnoreCase)) .ToListAsync() .ConfigureAwait(false) : await redb.Query() .WhereRedb(o => o.Note != null && o.Note.Contains(query, StringComparison.OrdinalIgnoreCase) && o.Name == collection) .ToListAsync() .ConfigureAwait(false); if (matches.Count == 0) return []; // Re-score the (already small) matched set against the DECODED text, not // the raw envelope: this ranks by real occurrence count and drops rows // where the substring only hit the JSON structure / meta, never the text. var ranked = new List(matches.Count); foreach (var row in matches) { var embedding = DecodeEmbedding(row.value_bytes); var chunk = MaterializeChunk(row, embedding); var score = KnowledgeTextMatch.CountOccurrences(chunk.Text, query); if (score == 0) continue; ranked.Add(new KnowledgeSearchResult(chunk, score)); } return ranked .OrderByDescending(r => r.Score) .Take(Math.Max(1, topK)) .ToArray(); } private static void Populate(RedbObject row, KnowledgeChunk chunk, out RedbObject result) { var embedding = chunk.Embedding.Span; // float[] -> raw bytes via MemoryMarshal — zero-copy reinterpret + ToArray() // produces the exact little-endian byte sequence we can decode later // with MemoryMarshal.Cast. var bytes = MemoryMarshal.AsBytes(embedding).ToArray(); var envelope = new ChunkEnvelope(chunk.Text, chunk.MetadataJson); row.value_string = chunk.Id; row.name = chunk.Collection ?? string.Empty; row.note = JsonSerializer.Serialize(envelope, EnvelopeJsonOptions); row.value_bytes = bytes; row.value_long = embedding.Length; row.date_modify = new DateTimeOffset(DateTime.SpecifyKind(chunk.UpdatedAtUtc, DateTimeKind.Utc)); result = row; } private static KnowledgeChunk MaterializeChunk(RedbObject row, float[] embedding) { var envelope = TryParseEnvelope(row.note); return new KnowledgeChunk { Id = row.value_string ?? string.Empty, Collection = string.IsNullOrEmpty(row.name) ? null : row.name, Text = envelope.Text, Embedding = embedding, MetadataJson = envelope.Meta, UpdatedAtUtc = row.date_modify.UtcDateTime }; } private static float[] DecodeEmbedding(byte[]? bytes) { if (bytes is null || bytes.Length == 0) return []; return MemoryMarshal.Cast(bytes).ToArray(); } private static ChunkEnvelope TryParseEnvelope(string? json) { if (string.IsNullOrWhiteSpace(json)) return new ChunkEnvelope(string.Empty, null); try { return JsonSerializer.Deserialize(json, EnvelopeJsonOptions) ?? new ChunkEnvelope(string.Empty, null); } catch { return new ChunkEnvelope(json, null); } } 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; } private static readonly JsonSerializerOptions EnvelopeJsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, // Store the text as-is (UTF-8), NOT \uXXXX-escaped. The default encoder // escapes every non-ASCII char, which would bury Cyrillic / CJK text as // "\u041C\u0430..." in the note column — making the keyword LIKE in // SearchTextAsync unable to match a raw non-ASCII query. Relaxed escaping // is safe for DB storage (it only skips HTML-sensitive escaping). Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; private sealed record ChunkEnvelope(string Text, string? Meta); }