|
| 1 | +package kiro |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/sha256" |
| 5 | + "encoding/json" |
| 6 | + "math" |
| 7 | + "strings" |
| 8 | + "sync" |
| 9 | + "time" |
| 10 | +) |
| 11 | + |
| 12 | +// Kiro reports neither cache reads nor cache writes, so they are estimated |
| 13 | +// locally the way Kiro-Go does (proxy/cache_tracker.go): each request is cut |
| 14 | +// into a prelude (model, system, tools) and one block per turn, every block |
| 15 | +// end is fingerprinted with a running SHA-256, and a later request on the same |
| 16 | +// account that repeats a stored prefix reads it from "cache". Fingerprints |
| 17 | +// live in memory for the Anthropic default TTL of five minutes. The figures |
| 18 | +// are an estimate for the request log and the client, not a billing number. |
| 19 | + |
| 20 | +const ( |
| 21 | + promptCacheTTL = 5 * time.Minute |
| 22 | + // Anthropic does not cache prefixes shorter than this. |
| 23 | + minCacheableTokens = 1024 |
| 24 | + opusMinCacheableTokens = 4096 |
| 25 | + // The newest content in a request is never all served from cache. |
| 26 | + maxCacheReadShare = 0.85 |
| 27 | + // Media is counted at a flat size instead of by its base64 length. |
| 28 | + mediaTokenEstimate = 1600 |
| 29 | +) |
| 30 | + |
| 31 | +// promptCacheUsage is one request's estimate. Total is the local estimate of |
| 32 | +// the whole prompt that Read and Write are measured against. |
| 33 | +type promptCacheUsage struct { |
| 34 | + Read, Write, Total int |
| 35 | +} |
| 36 | + |
| 37 | +// scaled re-expresses the estimate against input, the prompt size the usage |
| 38 | +// chunk reports (Kiro's context share), so the shares stay the same while |
| 39 | +// read plus write never exceeds input. |
| 40 | +func (u *promptCacheUsage) scaled(input int) (int, int) { |
| 41 | + if u == nil || input <= 0 || u.Total <= 0 { |
| 42 | + return 0, 0 |
| 43 | + } |
| 44 | + ratio := float64(input) / float64(u.Total) |
| 45 | + read := min(int(math.Round(float64(u.Read)*ratio)), input) |
| 46 | + write := min(int(math.Round(float64(u.Write)*ratio)), input-read) |
| 47 | + return read, write |
| 48 | +} |
| 49 | + |
| 50 | +type cacheBreakpoint struct { |
| 51 | + fingerprint [32]byte |
| 52 | + tokens int // cumulative estimate up to and including this block |
| 53 | +} |
| 54 | + |
| 55 | +type cacheProfile struct { |
| 56 | + model string |
| 57 | + breakpoints []cacheBreakpoint |
| 58 | + total int |
| 59 | +} |
| 60 | + |
| 61 | +// buildCacheProfile fingerprints a conversation block by block. A user turn |
| 62 | +// hashes the same whether it is the current turn or a replayed history turn, |
| 63 | +// so this request's full prompt is the prefix the next turn looks up. |
| 64 | +func buildCacheProfile(c conversation) *cacheProfile { |
| 65 | + hasher := sha256.New() |
| 66 | + profile := &cacheProfile{model: c.Model} |
| 67 | + add := func(value any, tokens int) { |
| 68 | + encoded, err := json.Marshal(value) |
| 69 | + if err != nil { |
| 70 | + return |
| 71 | + } |
| 72 | + hasher.Write(encoded) |
| 73 | + hasher.Write([]byte{0}) |
| 74 | + profile.total += tokens |
| 75 | + var fingerprint [32]byte |
| 76 | + copy(fingerprint[:], hasher.Sum(nil)) |
| 77 | + profile.breakpoints = append(profile.breakpoints, cacheBreakpoint{fingerprint: fingerprint, tokens: profile.total}) |
| 78 | + } |
| 79 | + prelude := struct { |
| 80 | + Model, System string |
| 81 | + Tools []toolSpec |
| 82 | + }{c.Model, c.System, c.Tools} |
| 83 | + add(prelude, preludeTokens(c)) |
| 84 | + for _, turn := range c.History { |
| 85 | + switch { |
| 86 | + case turn.User != nil: |
| 87 | + add(turn.User, userTokens(*turn.User)) |
| 88 | + case turn.Assistant != nil: |
| 89 | + add(turn.Assistant, assistantTokens(*turn.Assistant)) |
| 90 | + } |
| 91 | + } |
| 92 | + add(c.Current, userTokens(c.Current)) |
| 93 | + if len(profile.breakpoints) == 0 || profile.total <= 0 { |
| 94 | + return nil |
| 95 | + } |
| 96 | + return profile |
| 97 | +} |
| 98 | + |
| 99 | +func preludeTokens(c conversation) int { |
| 100 | + total := estimateTokens(c.System) |
| 101 | + for _, tool := range c.Tools { |
| 102 | + total += estimateTokens(tool.Name) + estimateTokens(tool.Description) |
| 103 | + if schema, err := json.Marshal(tool.Parameters); err == nil { |
| 104 | + total += estimateTokens(string(schema)) |
| 105 | + } |
| 106 | + } |
| 107 | + return total |
| 108 | +} |
| 109 | + |
| 110 | +func userTokens(turn userTurn) int { |
| 111 | + total := estimateTokens(turn.Text) + mediaTokenEstimate*(len(turn.Images)+len(turn.Documents)) |
| 112 | + for _, result := range turn.Results { |
| 113 | + total += estimateTokens(result.Output) |
| 114 | + } |
| 115 | + return total |
| 116 | +} |
| 117 | + |
| 118 | +func assistantTokens(turn assistantTurn) int { |
| 119 | + total := estimateTokens(turn.Text) |
| 120 | + for _, block := range turn.Reasoning { |
| 121 | + total += estimateTokens(block.Text) |
| 122 | + } |
| 123 | + for _, call := range turn.ToolUses { |
| 124 | + total += estimateTokens(call.Name) |
| 125 | + if input, err := json.Marshal(call.Input); err == nil { |
| 126 | + total += estimateTokens(string(input)) |
| 127 | + } |
| 128 | + } |
| 129 | + return total |
| 130 | +} |
| 131 | + |
| 132 | +func minCacheableFor(model string) int { |
| 133 | + if strings.Contains(strings.ToLower(model), "opus") { |
| 134 | + return opusMinCacheableTokens |
| 135 | + } |
| 136 | + return minCacheableTokens |
| 137 | +} |
| 138 | + |
| 139 | +// promptCache holds stored prefix fingerprints per account. The zero of a nil |
| 140 | +// *promptCache is valid and estimates nothing. |
| 141 | +type promptCache struct { |
| 142 | + mu sync.Mutex |
| 143 | + entries map[string]map[[32]byte]time.Time // account -> fingerprint -> expiry |
| 144 | + now func() time.Time |
| 145 | +} |
| 146 | + |
| 147 | +func newPromptCache() *promptCache { |
| 148 | + return &promptCache{entries: map[string]map[[32]byte]time.Time{}, now: time.Now} |
| 149 | +} |
| 150 | + |
| 151 | +// compute estimates cache use for profile without storing it. The first |
| 152 | +// cacheable request on an account writes the whole prompt. Later requests read |
| 153 | +// the longest stored prefix, capped so part of the prompt stays uncached, and |
| 154 | +// write the rest up to that cap. |
| 155 | +func (t *promptCache) compute(account string, profile *cacheProfile) promptCacheUsage { |
| 156 | + usage := promptCacheUsage{Total: profile.total} |
| 157 | + minTokens := minCacheableFor(profile.model) |
| 158 | + if profile.total < minTokens { |
| 159 | + return usage |
| 160 | + } |
| 161 | + now := t.now() |
| 162 | + t.mu.Lock() |
| 163 | + defer t.mu.Unlock() |
| 164 | + t.pruneLocked(now) |
| 165 | + entries := t.entries[account] |
| 166 | + if len(entries) == 0 { |
| 167 | + usage.Write = profile.total |
| 168 | + return usage |
| 169 | + } |
| 170 | + cacheable := int(float64(profile.total) * maxCacheReadShare) |
| 171 | + matched := 0 |
| 172 | + for i := len(profile.breakpoints) - 1; i >= 0; i-- { |
| 173 | + point := profile.breakpoints[i] |
| 174 | + if point.tokens < minTokens { |
| 175 | + break |
| 176 | + } |
| 177 | + if _, ok := entries[point.fingerprint]; ok { |
| 178 | + matched = min(point.tokens, cacheable) |
| 179 | + break |
| 180 | + } |
| 181 | + } |
| 182 | + usage.Read = matched |
| 183 | + usage.Write = max(cacheable-matched, 0) |
| 184 | + return usage |
| 185 | +} |
| 186 | + |
| 187 | +// update stores every cacheable prefix of profile for the TTL. |
| 188 | +func (t *promptCache) update(account string, profile *cacheProfile) { |
| 189 | + minTokens := minCacheableFor(profile.model) |
| 190 | + now := t.now() |
| 191 | + t.mu.Lock() |
| 192 | + defer t.mu.Unlock() |
| 193 | + t.pruneLocked(now) |
| 194 | + entries := t.entries[account] |
| 195 | + if entries == nil { |
| 196 | + entries = map[[32]byte]time.Time{} |
| 197 | + t.entries[account] = entries |
| 198 | + } |
| 199 | + for _, point := range profile.breakpoints { |
| 200 | + if point.tokens >= minTokens { |
| 201 | + entries[point.fingerprint] = now.Add(promptCacheTTL) |
| 202 | + } |
| 203 | + } |
| 204 | + if len(entries) == 0 { |
| 205 | + delete(t.entries, account) |
| 206 | + } |
| 207 | +} |
| 208 | + |
| 209 | +func (t *promptCache) pruneLocked(now time.Time) { |
| 210 | + for account, entries := range t.entries { |
| 211 | + for fingerprint, expires := range entries { |
| 212 | + if !expires.After(now) { |
| 213 | + delete(entries, fingerprint) |
| 214 | + } |
| 215 | + } |
| 216 | + if len(entries) == 0 { |
| 217 | + delete(t.entries, account) |
| 218 | + } |
| 219 | + } |
| 220 | +} |
| 221 | + |
| 222 | +// cacheTurn is one request's estimate. It is computed before the request is |
| 223 | +// sent and stored only after the stream completes, so a failed request never |
| 224 | +// seeds a hit for the next one. |
| 225 | +type cacheTurn struct { |
| 226 | + tracker *promptCache |
| 227 | + account string |
| 228 | + profile *cacheProfile |
| 229 | + usage promptCacheUsage |
| 230 | +} |
| 231 | + |
| 232 | +func (t *promptCache) begin(account string, c conversation) *cacheTurn { |
| 233 | + if t == nil || account == "" { |
| 234 | + return nil |
| 235 | + } |
| 236 | + profile := buildCacheProfile(c) |
| 237 | + if profile == nil { |
| 238 | + return nil |
| 239 | + } |
| 240 | + return &cacheTurn{tracker: t, account: account, profile: profile, usage: t.compute(account, profile)} |
| 241 | +} |
| 242 | + |
| 243 | +func (c *cacheTurn) estimate() *promptCacheUsage { |
| 244 | + if c == nil { |
| 245 | + return nil |
| 246 | + } |
| 247 | + usage := c.usage |
| 248 | + return &usage |
| 249 | +} |
| 250 | + |
| 251 | +func (c *cacheTurn) commit() { |
| 252 | + if c == nil { |
| 253 | + return |
| 254 | + } |
| 255 | + c.tracker.update(c.account, c.profile) |
| 256 | +} |
0 commit comments