Path: redb-route/redb.Route.Llm/Storage/Redb/RedbToolIdempotencyStore.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/RedbToolIdempotencyStore.cs ---- using System.Collections.Concurrent; 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; using redb.Route.RedbCore.Repositories; namespace redb.Route.Llm.Storage.Redb; /// /// REDB-backed . Reservations are tracked by a /// (processor name llm-tool-idempotency) over the same redb the tool /// outputs go to: the instance the endpoint's ?redb= names, else the constructor's default name, else the /// context's default redb. One rule for every case, so a reservation never sits in another database than the output it /// guards. The scope of that redb is opened per operation, on first use. Idempotent tool outputs /// are persisted in a row whose composite /// key "llm-tool:{conv}:{toolUseId}" lives in _objects.value_string /// (partial index on PostgreSQL/SQLite; MSSQL cannot index NVARCHAR(MAX)) and, /// normalized, in _objects._value_unique — the per-scheme unique index /// keeps a raced completion on a single row. The dedicated scheme keeps /// idempotency rows physically separate from /// content-hash entries — lookups touch a single scheme partition. /// On a duplicate, the previously-saved output is returned and the model /// never sees a second side effect. /// /// 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 RedbToolIdempotencyStore : IToolIdempotencyStore { private readonly IRouteContext _context; private readonly string? _defaultRedbName; // Keyed by the redb name; the empty key is the context's default redb. private readonly ConcurrentDictionary _reservations = new(StringComparer.Ordinal); /// The processor name of the reservations. private const string ReservationProcessorName = "llm-tool-idempotency"; /// /// Creates the store over 's redb: the instance names /// (an endpoint's ?redb= overrides it per exchange), else the context's default redb. Reservations and cached /// outputs are kept there together. /// public RedbToolIdempotencyStore(IRouteContext context, string? defaultRedbName = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _defaultRedbName = defaultRedbName; } private string? RedbNameOf(IExchange? exchange) { if (exchange is not null && exchange.Properties.TryGetValue(LlmKeys.RedbName, out var raw) && raw is string s && s.Length > 0) return s; return string.IsNullOrEmpty(_defaultRedbName) ? null : _defaultRedbName; } /// /// The service the output row is read and written on. With an exchange it is the exchange's service. Without one /// the call opens a scope of its own and hands it back in for the caller to dispose, as /// the reservation does: the context's single instance would put concurrent calls on one connection. /// private IRedbService Resolve(IExchange? exchange, out RedbScope? owned) { var name = RedbNameOf(exchange); if (exchange is not null) { owned = null; return _context.GetRedbService(name ?? string.Empty, exchange); } owned = OpenScope(name ?? string.Empty); return owned.Service; } private IIdempotentRepository ReservationsOf(IExchange? exchange) => _reservations.GetOrAdd(RedbNameOf(exchange) ?? string.Empty, name => new RedbIdempotentRepository( () => OpenScope(name), new RedbIdempotentOptions { ProcessorName = ReservationProcessorName })); private RedbScope OpenScope(string name) { try { return _context.CreateRedbScope(name.Length == 0 ? null : name); } catch (InvalidOperationException ex) { var where = name.Length == 0 ? "the route context's default redb" : $"the redb instance '{name}'"; throw new InvalidOperationException( $"AddRedbLlmStorage: the tool idempotency reservation is kept in {where}, but the route context cannot " + $"open a redb scope for it: {ex.Message} Register redb in the context's container (services.AddRedb... " + "or AddRedbPro), or name an instance the context has (AddRedbLlmStorage(\"name\") or ?redb= on the endpoint).", ex); } } /// public async Task TryReserveAsync(string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default) { var key = BuildKey(conversationId, toolUseId); var fresh = await ReservationsOf(exchange).Add(key, ct).ConfigureAwait(false); if (fresh) return ToolIdempotencyReservation.NewReservation; var redb = Resolve(exchange, out var owned); await using var scope = owned; var cached = await LoadCachedOutputAsync(redb, key).ConfigureAwait(false); return ToolIdempotencyReservation.Hit(cached ?? "{}"); } /// public async Task CompleteAsync(string conversationId, string toolUseId, string outputJson, IExchange? exchange = null, CancellationToken ct = default) { var key = BuildKey(conversationId, toolUseId); var redb = Resolve(exchange, out var owned); await using var scope = owned; var row = await redb.Query() .WhereRedb(x => x.ValueUnique == RedbUniqueKey.Normalize(key)) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is null) { // The composite key rides in _value_unique: the reservation protocol makes // a second completer rare (release + re-reserve, crash recovery), but when // one appears the unique index keeps the output on a single row. row = new RedbObject { value_string = key, ValueUnique = RedbUniqueKey.Normalize(key), Props = new ToolIdempotencyProps { ToolName = null, OutputJson = outputJson, CreatedAtUtc = DateTimeOffset.UtcNow } }; try { await redb.SaveAsync(row).ConfigureAwait(false); } catch (RedbUniqueViolationException) { // Lost the creation race — write this completion onto the winner's row. var winnerKey = row.ValueUnique; var winner = await redb.Query() .WhereRedb(x => x.ValueUnique == winnerKey) .FirstOrDefaultAsync() .ConfigureAwait(false); if (winner is null) throw; // the key vanished again (released mid-race) winner.Props.OutputJson = outputJson; winner.date_modify = DateTimeOffset.UtcNow; await redb.SaveAsync(winner).ConfigureAwait(false); } } else { row.Props.OutputJson = outputJson; row.date_modify = DateTimeOffset.UtcNow; await redb.SaveAsync(row).ConfigureAwait(false); } await ReservationsOf(exchange).Confirm(key, ct).ConfigureAwait(false); } /// public async Task ReleaseAsync(string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default) { var key = BuildKey(conversationId, toolUseId); await ReservationsOf(exchange).Remove(key, ct).ConfigureAwait(false); var redb = Resolve(exchange, out var owned); await using var scope = owned; var row = await redb.Query() .WhereRedb(x => x.ValueUnique == RedbUniqueKey.Normalize(key)) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is not null) await redb.SoftDeleteAsync([row]).ConfigureAwait(false); } private static async Task LoadCachedOutputAsync(IRedbService redb, string key) { var row = await redb.Query() .WhereRedb(x => x.ValueUnique == RedbUniqueKey.Normalize(key)) .FirstOrDefaultAsync() .ConfigureAwait(false); return row?.Props.OutputJson; } private static string BuildKey(string conversationId, string toolUseId) => $"llm-tool:{conversationId}:{toolUseId}"; }