Path: redb-route/redb.Route.Llm/Storage/Redb/RedbToolResultCache.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/RedbToolResultCache.cs ---- using redb.Core; using redb.Core.Exceptions; 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 . Cache entries are keyed on the /// caller-supplied content hash stored in _objects.value_string (partial /// index on PostgreSQL/SQLite; MSSQL cannot index NVARCHAR(MAX), lookups there /// scan the scheme's rows). The key also rides in _objects._value_unique, /// whose per-scheme unique index makes concurrent writers of one key converge /// on a single row. TTL is honoured lazily — entries past expiry are dropped on /// read. /// /// Distinct from : idempotency answers "have I already run /// this tool call (by tool_use_id)?", while this store answers "do I already have an output for /// this exact input?". The engine consults this store for ToolCachingPolicy.Persist tools, /// after approval and before the idempotency reservation. /// /// /// 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 RedbToolResultCache : IToolCacheStore { private readonly IRouteContext _context; private readonly string? _defaultRedbName; /// Creates the store. Scheme is synced by the host's redb.InitializeAsync(). public RedbToolResultCache(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 ValueTask GetAsync(string cacheKey, IExchange? exchange = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(cacheKey); var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var row = await redb.Query() .WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(cacheKey)) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is null) return null; if (row.Props.ExpiresAtUtc is { } exp && exp <= DateTimeOffset.UtcNow) { // Lazy eviction — soft-delete and report a miss. Whoever asked sees a miss, and the // two cases (cold key, expired entry) are indistinguishable through this interface. await redb.SoftDeleteAsync([row]).ConfigureAwait(false); return null; } return row.Props.OutputJson; } /// public async ValueTask SetAsync(string cacheKey, string outputJson, TimeSpan? ttl = null, IExchange? exchange = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(cacheKey); ArgumentNullException.ThrowIfNull(outputJson); var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; var existing = await redb.Query() .WhereRedb(o => o.ValueUnique == RedbUniqueKey.Normalize(cacheKey)) .FirstOrDefaultAsync() .ConfigureAwait(false); var now = DateTimeOffset.UtcNow; var expiresAt = ttl is { } span && span > TimeSpan.Zero ? now.Add(span) : (DateTimeOffset?)null; if (existing is null) { // The cache key rides in _value_unique: of two concurrent SetAsync for one // key the per-scheme unique index lets exactly one insert through — before, // both inserted and readers picked an arbitrary (possibly stale) copy. var row = new RedbObject { value_string = cacheKey, ValueUnique = RedbUniqueKey.Normalize(cacheKey), Props = new ToolCacheProps { OutputJson = outputJson, CreatedAtUtc = now, ExpiresAtUtc = expiresAt } }; try { await redb.SaveAsync(row).ConfigureAwait(false); } catch (RedbUniqueViolationException) { // Lost the creation race — a cache Set is last-writer-wins, so write // onto the winner's row, resolved by the key that collided. var winnerKey = row.ValueUnique; var winner = await redb.Query() .WhereRedb(o => o.ValueUnique == winnerKey) .FirstOrDefaultAsync() .ConfigureAwait(false); if (winner is null) throw; // the key vanished again (evicted mid-race) winner.Props.OutputJson = outputJson; winner.Props.CreatedAtUtc = now; winner.Props.ExpiresAtUtc = expiresAt; winner.date_modify = now; await redb.SaveAsync(winner).ConfigureAwait(false); } } else { // Hash-pre-check: idempotent SetAsync (same json/ttl/key) becomes // a no-op instead of a round-trip through SaveAsync change-tracking. var hashBefore = existing.ComputeHash(); existing.Props.OutputJson = outputJson; existing.Props.CreatedAtUtc = now; existing.Props.ExpiresAtUtc = expiresAt; if (existing.ComputeHash() == hashBefore) return; existing.date_modify = now; await redb.SaveAsync(existing).ConfigureAwait(false); } } /// public async ValueTask ClearAsync(IExchange? exchange = null, CancellationToken ct = default) { var redb = Resolve(exchange, out var owned); await using var ownedScope = owned; // Project only ids — avoids materialising props blobs server-side just // to feed them into the bulk SoftDeleteAsync(IEnumerable) overload. var ids = await redb.Query() .Select(r => r.id) .ToListAsync() .ConfigureAwait(false); if (ids.Count == 0) return; await redb.SoftDeleteAsync(ids).ConfigureAwait(false); } }