|
| 1 | +# Verdict Cache |
| 2 | + |
| 3 | +**Date:** 2026-04-25 |
| 4 | +**Status:** Approved |
| 5 | +**Goal:** Cache judge verdicts so identical content is not re-judged across turns in a conversation |
| 6 | + |
| 7 | +## Context |
| 8 | + |
| 9 | +The gateway decomposes every message in a request into separate `llm.text` spans. In a multi-turn conversation, turn N includes all messages from turns 1 through N-1. Each text span hits every judge rule. Without caching, the same content is re-judged on every turn — O(N^2) judge calls over a conversation. This wastes tokens, adds latency, and can cause timeouts on large context blocks. |
| 10 | + |
| 11 | +## Design |
| 12 | + |
| 13 | +### Cache Wrapper |
| 14 | + |
| 15 | +A `judge.Cache` wraps any `judge.Provider` and returns a `Provider` with the same interface. Caching is transparent to consumers. |
| 16 | + |
| 17 | +```go |
| 18 | +// judge/cache.go |
| 19 | + |
| 20 | +type Cache struct { |
| 21 | + provider Provider |
| 22 | + mu sync.RWMutex |
| 23 | + entries map[[32]byte]Verdict |
| 24 | + order [][32]byte // insertion order for eviction |
| 25 | + maxSize int |
| 26 | +} |
| 27 | + |
| 28 | +func NewCache(provider Provider, opts ...CacheOption) *Cache |
| 29 | +func (c *Cache) Judge(ctx context.Context, req Request) (Verdict, error) |
| 30 | + |
| 31 | +type CacheOption func(*Cache) |
| 32 | +func WithMaxSize(n int) CacheOption |
| 33 | +``` |
| 34 | + |
| 35 | +### Cache Key |
| 36 | + |
| 37 | +`sha256(model + "\x00" + prompt + "\x00" + content)` |
| 38 | + |
| 39 | +Null byte separators prevent collisions between adjacent fields. The key includes all three inputs to the judge — if any differ, the verdict is re-evaluated. |
| 40 | + |
| 41 | +### Eviction |
| 42 | + |
| 43 | +Oldest-first eviction when `len(entries) > maxSize`. Default max size: 10,000 entries. Configurable via `WithMaxSize(n)`. |
| 44 | + |
| 45 | +Not true LRU (no promotion on hit). Simpler and sufficient — verdict entries are small (~200 bytes each) and the working set in a conversation is bounded by message count. |
| 46 | + |
| 47 | +### No TTL |
| 48 | + |
| 49 | +Same content + same prompt + same model = same verdict. The policy judgment is deterministic for a given input. The cache lives as long as the engine. |
| 50 | + |
| 51 | +On `engine.Reload()`, the cache persists. Changed rules produce different prompts, which produce different cache keys. Stale entries from old prompts evict naturally via oldest-first eviction. |
| 52 | + |
| 53 | +### Concurrency |
| 54 | + |
| 55 | +`sync.RWMutex` — cache lookups take read lock, inserts take write lock. The judge call itself happens outside the lock (only the key is computed under read lock, then released before the HTTP call). |
| 56 | + |
| 57 | +**Cache stampede:** Concurrent misses on the same key will all call the provider independently. The last writer wins. This is acceptable — stampede only happens within a single turn's concurrent spans, and subsequent turns hit the cache. Singleflight is a future optimization if needed. |
| 58 | + |
| 59 | +### Audit Trail |
| 60 | + |
| 61 | +`JudgeAudit` gains a `Cached bool` field: |
| 62 | + |
| 63 | +```go |
| 64 | +type JudgeAudit struct { |
| 65 | + Model string `json:"model"` |
| 66 | + Verdict string `json:"verdict"` |
| 67 | + Reason string `json:"reason"` |
| 68 | + Cached bool `json:"cached,omitempty"` |
| 69 | + LatencyMS int64 `json:"latency_ms"` |
| 70 | + Usage JudgeUsage `json:"usage"` |
| 71 | + Error string `json:"error,omitempty"` |
| 72 | +} |
| 73 | +``` |
| 74 | + |
| 75 | +**Propagation path:** `judge.Verdict` gains a `Cached bool` field. The `Cache.Judge` method sets `Cached: true` on cache hits. The existing `judgeAdapter` in `keep.go` copies `v.Cached` to `engine.JudgeResult.Cached`. The evaluator copies `jr.Cached` to `audit.Cached`. This is an additive, backward-compatible change to `judge.Verdict`. |
| 76 | + |
| 77 | +Cache hit latency is measured by the existing timer in `eval.go` which wraps the `judgeFunc` call. Cache hits return near-instantly, so `LatencyMS` will be ~0 — this is intentional and makes hits visibly fast in the audit trail. |
| 78 | + |
| 79 | +### Wiring |
| 80 | + |
| 81 | +The cache wraps the provider at the `keep.go` / `main.go` level: |
| 82 | + |
| 83 | +```go |
| 84 | +// Library |
| 85 | +provider := anthropic.New(os.Getenv("ANTHROPIC_API_KEY")) |
| 86 | +cached := judge.NewCache(provider) |
| 87 | +engine, _ := keep.Load("./rules", keep.WithJudge(cached.Judge)) |
| 88 | + |
| 89 | +// Gateway/relay main.go — wrap before passing to WithJudge |
| 90 | +p := anthropicjudge.New(apiKey) |
| 91 | +cached := judge.NewCache(p) |
| 92 | +engineOpts = append(engineOpts, keep.WithJudge(cached.Judge)) |
| 93 | +``` |
| 94 | + |
| 95 | +### What Changes |
| 96 | + |
| 97 | +- **New:** `judge/cache.go` — Cache type, NewCache, CacheOption, WithMaxSize |
| 98 | +- **New:** `judge/cache_test.go` — unit tests |
| 99 | +- **Modify:** `judge/judge.go` — `Verdict` gains `Cached bool` |
| 100 | +- **Modify:** `internal/engine/eval.go` — `JudgeAudit` gains `Cached bool`, `JudgeResult` gains `Cached bool`, evaluator copies `jr.Cached` to `audit.Cached` |
| 101 | +- **Modify:** `keep.go` — `judgeAdapter` copies `v.Cached` to `JudgeResult.Cached` |
| 102 | +- **Modify:** `cmd/keep-llm-gateway/main.go` — wrap provider with `judge.NewCache()` |
| 103 | +- **Modify:** `cmd/keep-mcp-relay/main.go` — same |
| 104 | +- **Modify:** `examples/judge-demo/demo.sh` — `print_audit` shows "(cached)" for cache hits |
| 105 | + |
| 106 | +### What Doesn't Change |
| 107 | + |
| 108 | +- `judge.Provider` interface — unchanged |
| 109 | +- `judge.Request` type — unchanged |
| 110 | +- `judge.Verdict` — gains `Cached bool` (additive, backward-compatible) |
| 111 | +- Engine internals — cache is external, injected via the same `WithJudge()` option |
| 112 | +- `keep test` fixtures — mock judge has no cache |
| 113 | +- `keep eval` — evaluates fresh each time (no cache) |
| 114 | + |
| 115 | +## Out of Scope |
| 116 | + |
| 117 | +- **Persistent cache** — in-memory only, no disk or Redis |
| 118 | +- **Cache invalidation API** — not needed; prompt changes = different key, engine restart = fresh cache |
| 119 | +- **Cache metrics** — hit/miss counters are a future enhancement |
| 120 | +- **Negative caching (errors)** — errors are not cached; only successful verdicts |