Path: redb-route/redb.Route.Llm/Engine/Storage/IToolIdempotencyStore.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/IToolIdempotencyStore.cs
----
using redb.Route.Abstractions;
namespace redb.Route.Llm.Engine.Storage;
///
/// Tracks tool invocations so that retried or duplicated tool calls produce a
/// single side effect. The contract is intentionally a thin wrapper over
/// — the redb-backed implementation reuses
/// the existing IdempotentEntryProps table to avoid duplicating schema.
///
/// 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 IToolIdempotencyStore
{
///
/// Attempts to reserve for the given conversation.
/// Returns the cached result on a duplicate, or
/// when the caller should execute the tool and finalize via .
///
Task TryReserveAsync(
string conversationId,
string toolUseId,
IExchange? exchange = null,
CancellationToken ct = default);
/// Persists the tool output JSON for the previously-reserved key.
Task CompleteAsync(
string conversationId,
string toolUseId,
string outputJson,
IExchange? exchange = null,
CancellationToken ct = default);
/// Releases the reservation on failure so a retry can re-run the tool.
Task ReleaseAsync(
string conversationId,
string toolUseId,
IExchange? exchange = null,
CancellationToken ct = default);
}
/// Outcome of .
public sealed class ToolIdempotencyReservation
{
/// True when this caller owns the reservation and must execute the tool.
public required bool IsNew { get; init; }
/// Cached output JSON when is false and the prior call completed.
public string? CachedOutputJson { get; init; }
/// Sentinel reservation indicating the caller must execute the tool.
public static readonly ToolIdempotencyReservation NewReservation = new() { IsNew = true };
/// Builds a hit reservation that returns the previously-recorded output.
public static ToolIdempotencyReservation Hit(string outputJson) => new()
{
IsNew = false,
CachedOutputJson = outputJson
};
}
///
/// In-memory idempotency store backed by a thin
/// composition — the registered repository handles the dedup key, an internal
/// dictionary remembers the cached output.
///
/// With a ttl, a completed call is forgotten that long after it completed: its key leaves the repository and
/// its output leaves the store, lazily, on a later reservation (no timer). A reservation still in flight (reserved,
/// neither completed nor released) is never aged out, so a second run of the same call cannot start while the first is
/// still running, however long it takes. Without a ttl nothing expires.
///
///
public sealed class InMemoryToolIdempotencyStore : IToolIdempotencyStore
{
private sealed record Completed(string OutputJson, DateTimeOffset At);
private readonly IIdempotentRepository _repository;
private readonly TimeSpan? _ttl;
private readonly TimeProvider _time;
private readonly System.Collections.Concurrent.ConcurrentDictionary _outputs = new(StringComparer.Ordinal);
/// Creates a store over the given idempotency repository.
/// Keeps the reservation keys.
/// How long a completed call is remembered after it completed; null keeps it for the life of the store.
/// The clock the ttl is measured with; by default.
public InMemoryToolIdempotencyStore(IIdempotentRepository repository, TimeSpan? ttl = null, TimeProvider? time = null)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
if (ttl is { } t && t <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(ttl), ttl, "The ttl must be positive.");
_ttl = ttl;
_time = time ?? TimeProvider.System;
}
///
public async Task TryReserveAsync(string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default)
{
if (_ttl is { } ttl)
await EvictCompletedBeforeAsync(_time.GetUtcNow() - ttl, ct).ConfigureAwait(false);
var key = BuildKey(conversationId, toolUseId);
var added = await _repository.Add(key, ct).ConfigureAwait(false);
if (added) return ToolIdempotencyReservation.NewReservation;
return _outputs.TryGetValue(key, out var cached)
? ToolIdempotencyReservation.Hit(cached.OutputJson)
: ToolIdempotencyReservation.Hit("{}");
}
///
public async Task CompleteAsync(string conversationId, string toolUseId, string outputJson, IExchange? exchange = null, CancellationToken ct = default)
{
var key = BuildKey(conversationId, toolUseId);
_outputs[key] = new Completed(outputJson, _time.GetUtcNow());
await _repository.Confirm(key, ct).ConfigureAwait(false);
}
///
public async Task ReleaseAsync(string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default)
{
var key = BuildKey(conversationId, toolUseId);
_outputs.TryRemove(key, out _);
await _repository.Remove(key, ct).ConfigureAwait(false);
}
///
/// Forgets every call completed before : the key first, so a concurrent reservation either
/// still finds key and output or starts afresh, never a key without its output; then exactly the output that was
/// read, so an output a new run of the same call wrote in between stays.
///
private async Task EvictCompletedBeforeAsync(DateTimeOffset cutoff, CancellationToken ct)
{
foreach (var entry in _outputs)
{
if (entry.Value.At >= cutoff) continue;
await _repository.Remove(entry.Key, ct).ConfigureAwait(false);
_outputs.TryRemove(entry);
}
}
private static string BuildKey(string conversationId, string toolUseId) =>
$"llm-tool:{conversationId}:{toolUseId}";
}