Path: redb-route/tests/redb.Route.Tests.Llm/TestHelpers/SpyStores.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/tests/redb.Route.Tests.Llm/TestHelpers/SpyStores.cs ---- using System.Collections.Concurrent; using redb.Route.Llm.Engine.Governance; using redb.Route.Llm.Engine.Storage; namespace redb.Route.Tests.Llm.TestHelpers; /// /// Idempotency-store spy for governance tests. Records every reservation, completion and /// release so a test can assert whether the engine consulted the store at all — /// which is the observable difference behind the SideEffect gate. /// /// Unlike the shipped in-memory store this one does not use an /// IIdempotentRepository: the tests care about the engine's calls, not about dedup /// implementation, and a plain dictionary keeps the double free of infrastructure. /// /// public sealed class SpyIdempotencyStore : IToolIdempotencyStore { private readonly ConcurrentDictionary _outputs = new(StringComparer.Ordinal); private readonly List _reservations = new(); private readonly List _completions = new(); private readonly List _releases = new(); private readonly object _gate = new(); /// Keys the engine tried to reserve, in order ({conversationId}:{toolUseId}). public IReadOnlyList Reservations { get { lock (_gate) return _reservations.ToArray(); } } /// Keys the engine completed after a successful dispatch. public IReadOnlyList Completions { get { lock (_gate) return _completions.ToArray(); } } /// Keys the engine released after a failed dispatch. public IReadOnlyList Releases { get { lock (_gate) return _releases.ToArray(); } } /// public Task TryReserveAsync( string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default) { var key = Key(conversationId, toolUseId); lock (_gate) _reservations.Add(key); return Task.FromResult(_outputs.TryGetValue(key, out var cached) ? ToolIdempotencyReservation.Hit(cached) : ToolIdempotencyReservation.NewReservation); } /// public Task CompleteAsync( string conversationId, string toolUseId, string outputJson, IExchange? exchange = null, CancellationToken ct = default) { var key = Key(conversationId, toolUseId); lock (_gate) _completions.Add(key); _outputs[key] = outputJson; return Task.CompletedTask; } /// public Task ReleaseAsync( string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default) { var key = Key(conversationId, toolUseId); lock (_gate) _releases.Add(key); return Task.CompletedTask; } private static string Key(string conversationId, string toolUseId) => $"{conversationId}:{toolUseId}"; } /// /// Tool-cache spy. Records reads and writes so a test can assert the engine consulted the /// cache (wave 3 wires it; before that, the counts stay at zero — which is itself the finding). /// public sealed class SpyToolCacheStore : IToolCacheStore { private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal); private readonly List _gets = new(); private readonly List _sets = new(); private readonly object _gate = new(); /// Keys read through , in order. public IReadOnlyList Gets { get { lock (_gate) return _gets.ToArray(); } } /// Keys written through , in order. public IReadOnlyList Sets { get { lock (_gate) return _sets.ToArray(); } } /// public ValueTask GetAsync(string cacheKey, IExchange? exchange = null, CancellationToken ct = default) { lock (_gate) _gets.Add(cacheKey); return ValueTask.FromResult(_entries.TryGetValue(cacheKey, out var value) ? value : null); } /// public ValueTask SetAsync(string cacheKey, string outputJson, TimeSpan? ttl = null, IExchange? exchange = null, CancellationToken ct = default) { lock (_gate) _sets.Add(cacheKey); _entries[cacheKey] = outputJson; return ValueTask.CompletedTask; } /// public ValueTask ClearAsync(IExchange? exchange = null, CancellationToken ct = default) { _entries.Clear(); return ValueTask.CompletedTask; } } /// /// Tool-cache store that always fails. Pins the best-effort rule: an unavailable cache may cost a hit, /// it must never cost the run — a store outage cannot turn a working tool call into an error for the /// model (which would then retry it). /// public sealed class ThrowingToolCacheStore : IToolCacheStore { /// public ValueTask GetAsync(string cacheKey, IExchange? exchange = null, CancellationToken ct = default) => throw new InvalidOperationException("cache store is unavailable"); /// public ValueTask SetAsync(string cacheKey, string outputJson, TimeSpan? ttl = null, IExchange? exchange = null, CancellationToken ct = default) => throw new InvalidOperationException("cache store is unavailable"); /// public ValueTask ClearAsync(IExchange? exchange = null, CancellationToken ct = default) => throw new InvalidOperationException("cache store is unavailable"); } /// /// Budget-enforcer spy: delegates to the shipped per-run enforcer and records the reason of every /// stop, so a test can assert why a run stopped — the engine logs the reason and does not put /// it on the response, and a test that only counted provider calls would not notice the difference /// between "budget stopped it" and "the model asked to stop". /// public sealed class SpyBudgetEnforcer : IBudgetEnforcer { private readonly InMemoryBudgetEnforcer _inner = new(); private readonly List _stopReasons = new(); private readonly List _sawAmbientTransaction = new(); private readonly object _gate = new(); /// For every budget call, in order: whether an ambient transaction was open when the engine made it. public IReadOnlyList SawAmbientTransaction { get { lock (_gate) return _sawAmbientTransaction.ToArray(); } } /// Reasons of every the engine was handed, in order. public IReadOnlyList StopReasons { get { lock (_gate) return _stopReasons.ToArray(); } } /// Number of pre-iteration checks the engine performed. public int PreChecks { get; private set; } /// Number of post-iteration checks the engine performed. public int PostChecks { get; private set; } /// public async ValueTask PreCheckAsync( string? conversationId, AgentBudget budget, AgentUsage usageSoFar, CancellationToken ct = default) { PreChecks++; ObserveTransaction(); var decision = await _inner.PreCheckAsync(conversationId, budget, usageSoFar, ct).ConfigureAwait(false); Record(decision); return decision; } /// public async ValueTask RecordAndCheckAsync( string? conversationId, AgentBudget budget, AgentUsage iterationUsage, AgentUsage totalUsage, CancellationToken ct = default) { PostChecks++; ObserveTransaction(); var decision = await _inner.RecordAndCheckAsync(conversationId, budget, iterationUsage, totalUsage, ct) .ConfigureAwait(false); Record(decision); return decision; } private void ObserveTransaction() { lock (_gate) _sawAmbientTransaction.Add(System.Transactions.Transaction.Current is not null); } private void Record(BudgetDecision decision) { if (decision.Continue) return; lock (_gate) _stopReasons.Add(decision.Reason); } }