Repository navigation
feat(cache): keep an idle prompt cache alive, price the 1h write tier, and say what cachesplit did - #86
Conversation
…, and say what cachesplit did ttl_expiry is 23.6% of this service's spend ($741.07 of $3,139.97 over 19,805 requests) and costs 8.5x a request that hit. The provider documents the fix: "the cache is refreshed for no additional cost each time the cached content is used", and the lifetime "is measured from the start of the request that writes or reads the cache entry". A read costs 0.1x base input where re-creating the prefix costs 1.25x, so one ping buys back 11.5 of itself. Add a host-level idle keep-alive. It cannot be a component: the expensive event happens when no request is in flight. After X seconds idle it re-sends the session's last request with max_tokens 1 and stream false — fields outside the tools/system/messages hash, so the prefix stays byte-identical and the request is a pure cache READ. A ping whose usage reports more written than read is the mechanism being wrong rather than expensive: ERROR, counted, and that session is dropped. Off by default and opt-in per account, because it spends the caller's money without the caller asking. X=280 and K=2 are measured, not chosen: 280 wastes 68 pings on gaps that would have hit where 240 wastes 148, and the net peaks at K=2-3 because a session that has ENDED is not detectable. Capped per session in dollars, bounded to a tenant's slack so a ping is skipped rather than queued ahead of real traffic, and killable with CONTEXT_GURU_KEEPALIVE=off. Deliberately NOT stopping on stop_reason end_turn. That reads like a session-end signal and is the opposite: P(gap > 300s) is 37.15% after end_turn against 0.74% after tool_use, and 83.7% of the recoverable dollars sit behind it. Every ping is a dashboard row marked keepalive with its own cost, and the saving is credited only where a ping preceded the request, the gap exceeded the lifetime, the provider read more than it wrote, and the amount is capped at what that ping actually refreshed. Replaying the snapshot through the shipped decision function: +$134.01, 4.27% of spend, 159 of 357 addressable misses. Live on the gateway, same script either side of a 330s gap: ttl_expiry with 48,335 written at $0.0928 becomes a hit with 48,211 read at $0.0085 plus $0.0073 of ping. Add the mixed 1h/5m TTL on the head breakpoints, off. It re-labels existing marks so it spends no breakpoint slot, and 1h-before-5m holds by construction. Measured live, it is worth $0 here: aws/claude-haiku-4-5 grants the tier (36,251 of 36,574 written tokens) while aws/claude-sonnet-5 silently downgrades it (0 of 48,212). The ttl field is not stripped in transit as previously believed — Bedrock's model coverage is what refuses. That probe exposed a pricing defect: a 1h write billed at 2.0x was recorded at the 5-minute 1.25x, $0.0348 against a real $0.0554. Carry the provider's per-tier breakdown and add the premium, since a cost wrong in the flattering direction argues for spending. cachesplit needed no fix. Its credit is 4 rows / $0.0381 because 32 of 35 split sessions carry one distinct tail hash for the whole session: Claude Code captures its environment snapshot once per session, so mid-session turns hit whether or not we split. Pricing the 1,729 uncredited hits at $18.79 would book the provider's cache as ours. What was missing was legibility, so /stats now states a per-component verdict — acted, moved, skipped, idle — because "acted 0" beside "mutated 755" has been filed as a bug twice against a mechanism working as designed. Signed-off-by: Osher-Elhadad <[email protected]>
… and close the 1h-TTL avenue Gate the idle keep-alive on "not the session's first request AND a billed prefix of at least 20,000 tokens". Replayed through the shipped decision function that sends 912 pings instead of 8,915 for 1.7% less money — 9.8x less gateway load for almost none of the value, on a path that returned 180 HTTP 429s in the same window. Ping cost is bimodal (p50 $0.0004, p99 $0.2275), so what the gate drops is the near-free pings on single-request sessions with 1k-token prefixes. The first-request skip is a cheap filter and not a claim that later turns miss more often: P(next request is an addressable TTL miss) is flat at 2.24% from turn 0 through 2.29% at turn 100. The gate belongs at record time, not in due(). Evaluating it per sweep left un-pingable sessions in the map holding a request body and a caller credential until memory pressure evicted them; on the production replay the 512-session bound saturated and eviction then discarded the entries about to pay, cutting conversions from 153 to 69. Gating at record keeps nothing we will not use, which is also the better security posture. Replace the per-session dollar cap with a per-ping budget. A per-session cap truncates exactly the long large-prefix sessions holding the value — capping the window's pings per session at 20 drops the net to $92.34 and at 10 to $54.04 — while the variance worth guarding is between pings. The projection is computed from the prefix and the model's own read rate before anything is sent. Keep ping rows out of every agent-traffic aggregate. A ping is a request we made on the user's behalf, so counting it inflates their request count and drags every per-request average towards a one-token response. One line in Filter.where() covers the overview, buckets, per-model groups, facets, session list and read-value queries together; the request LIST and the keep-alive ledger opt back in, so the audit trail stays visible and the spend stays attributed. Close the 1-hour TTL avenue with the evidence, rather than leaving it as folklore. Blanket 1h is −$18.34 by one counterfactual and −$93.51 by another; gating it on the best predictor leaves −$18.32, which is structural because premium and benefit scale with the same cache_write on the same requests. And the tier does not arrive: zero 2.0x writes in 19,805 requests. The received explanation was that LiteLLM strips the ttl field; measured live, aws/claude-haiku-4-5 GRANTS the tier (36,251 of 36,574 written tokens) while aws/claude-sonnet-5 silently downgrades it, so the field does reach Bedrock and it is model coverage that refuses. Same conclusion, right mechanism — the fix if it ever pays is a model allowlist, not an upstream patch. Assess and reject the parallel fan-out lever on cold_start. 1,260 cold starts sit within 10s of another in the same tenant, but only 2 worth $0.66 plausibly share a prefix: 886 of the 1,626 rows are litellm one-shots with mean cache_write of zero, and 1,494 are genuine session firsts. Serialising 1,260 requests behind a first-token wait to recover $0.66 is not worth building. Fix the documented 1h break-even, wrong by 18 points in two places. (2.0-1.25)/(1-0.1) = 83.3% assumes a lapsed entry re-bills at the fresh rate; it re-bills as a 1.25x creation, because those tokens still carry cache_control. Production ttl_expiry rows show it — cache_write averages 178,793 against fresh_input 1,712. The correct figure is 65.2%. Carry the provider's per-TTL write breakdown so a 1h write is priced at 2.0x rather than 1.25x. The live probe was recorded at $0.0348 against a real $0.0554; a cost wrong in the flattering direction argues for spending. schemaVersion is unchanged at 6 and all four columns are additive, so the 19,805 stored requests survive the deploy. Signed-off-by: Osher-Elhadad <[email protected]>
OsherElhadad
left a comment
There was a problem hiding this comment.
Reviewer verdict: CHANGES-REQUIRED. Posted as a comment review because GitHub refuses
REQUEST_CHANGESon a pull request owned by the same account.
Review: CHANGES-REQUIRED
Reviewed at eba59a2. This is strong work. The economics are real, the headline reproduces to the cent through your own shipped decision function, the live proof is genuine, and the credit formula is an identity rather than an estimate. All three places you disagreed with instructions check out on the evidence, and I've said so inline. Four things must not ship as built — two of them have the same fix.
Verified myself, clean extraction of eba59a2 (the worktree was being edited mid-review, and go test ./... there reports ok .../proxy (cached) from a stale entry while the package's tests no longer compile)
gofmt -l . # empty
go vet ./... # clean
CGO_ENABLED=1 go test -race -count=1 ./... # 25 packages ok, no races
schemaVersion is still 6 and all four columns go through additiveColumns — the deploy-time data-loss hazard is correctly avoided. DCO signed off, author/committer correct, conventional title, no AI attribution anywhere, no credential shapes in the diff.
The projection reproduces. TestKeepAliveOnProductionSnapshot at X=280s K=2: pings 8969 ping $109.08 converted 159 saved $243.09 NET $+134.01 (4.27%), 3814 pinged | 37 net positive | 3777 net NEGATIVE costing $13.10 | worst -$0.9490. Exactly what the PR body claims.
The live evidence is what it says it is. From the raw rows: the ping is cache_read: 48211, cache_write: 0 — a pure cache read. The OFF arm's ttl_expiry row has cache_read: 0, satisfying the standard's requirement that a cold-turn claim show the column and a zero read. The harness avoids the trap this repo has been caught by before: a separate nonce per arm, so the second arm cannot free-ride on the first's 48k prefix — and it worked, both arms' turn 1 wrote 48,211 fresh.
max_tokens and stream really are outside the hashed prefix. Against Anthropic's invalidation hierarchy, the tiers are invalidated by tool definitions, model, speed/web-search/citations, system content, tool_choice/images/thinking, and message content. Neither max_tokens nor stream appears in any tier. tool_choice, images and thinking config do invalidate at the messages level exactly as you state, and the ping resends all of them unchanged. The mechanism is also Anthropic's own documented advice for this case ("for bursty traffic with long idle gaps, either re-warm just under the TTL").
The credit is an identity, and it matches the measured counterfactual. For aws/claude-sonnet-5 at in: 1.52, 1.25x1.52 - 0.1x1.52 = $1.748/MTok, and the stored credit divided by tokens is exactly $1.7480/MTok. Better:
OFF turn2 $0.09281234 - ON turn2 $0.008541412 = $0.084270928 (measured)
stored keepalive_saved_usd = $0.084272828
difference = $0.0000019 (0.002%)
This is the most careful savings figure I have seen in this repo. It declines to credit itself, caps at what the ping actually refreshed, and states the content-keyed confound as a ceiling rather than hiding it.
Blocking
- The kill switch does not stop credential retention, and with the sweep dead nothing enforces the
(K+1)·Xbound that the code comment and the docs page both promise. An operator pulls the switch because something is wrong and gets retention with no pings. - The recommended gate is missing. Through your own harness:
turn>=1 AND prefix>=20ksends 9.3x fewer pings and touches 32x fewer sessions (3,809 → 120) for 4.2% less money. It is also the fix for (1), and the reason the 512-session bound binds on real traffic (measuredpeak live sessions 512). AcquireSparecharges the tenant's rate window for pings it then refuses — 10 refused pings consumed 10 of 100 requests/minute. Directly contradicts its own contract, and fires exactly when the tenant is busiest.MaxUSDPerSessionis a per-span cap documented per-session in three places. Your own worst session (−$0.9490) is 3.8x the shipped $0.25 ceiling — those two numbers cannot both be right.
Plus: ping rows credit themselves with provider cache savings (~$0.13 per 48k ping against $0.0073 of cost) and inflate COUNT(*); the consent copy promises a Requests-tab marker and an Overview ledger that aren't implemented and omits the losing-median disclosure your docs page carries; three comments still repeat the refuted LiteLLM claim.
On credential retention: acceptable with specific changes
Not "not acceptable". One correction to the framing I was given: authHeaders are forwarded, not stripped — that's the whole caller-pays design; only our own minted token is scrubbed. The real invariant is docs/hosted.md:48 — "The service holds no provider credential of its own and stores none: the key is read off the request and dropped." The PR makes the second clause false in the opt-in case and does not touch that file.
I checked the blast radius rather than assuming it. /stats, /metrics, logs, and persistence are all clean — KeepAliveStats carries only counters, no %+v of kaEntry or pingJob exists anywhere, nothing writes hdr or body. Cross-tenant is clean: the map key is tenant\x00session and both record and arrive key on tn.ID, with the upstream travelling inside the entry, so there is no path for one tenant's key to authenticate another's ping. Server-key upstreams retain nothing, and our token is scrubbed before retention — both tested. The genuine widenings are a process dump (the key in heap for ~14 min instead of ~ms, same class as an in-flight request) and the retained body, which is the user's whole conversation and is the one nobody has consented to.
Required before merge: make the kill switch stop retention; retire stopped entries immediately instead of after a further X; honour consent withdrawal at sweep time rather than trusting the record-time e.pol snapshot (currently up to ~14 min stale); update docs/hosted.md; disclose the retained body in the consent copy; and ship the gate, which cuts retained credentials 32-fold for $5.57.
Numbers I could not verify
- +$170.08 / 9,234 pings / 182 misses — the simulator's figures, quoted in
proxy/keepalive.go:46-48and the K-curve inconfig/config.goas if they describe the shipped defaults. The shipped function gives +$134.01 / ~8,964 / 159. The PR body reports +$134.01 correctly, so this is a comment problem — but the file's own headline overstates the mechanism it implements by 27%. - "the net peaks at K=2" — not reproduced. K=3 gives +$134.43 against K=2's +$134.01; they tie. The clean K=2 peak doesn't survive the gates the shipped code adds.
- 8,962 pings — one draw of a non-reproducible statistic (8,961–8,969 observed across runs; money identical to the cent).
- "1 of 1,332 passes tail-moved" — I measure 2,039 rows carrying a split and 4 credited; 1,332 is a denominator I can't reconstruct. The load-bearing part verifies exactly: 35 sessions with a nonzero tail hash, 32 carrying one distinct hash all session, 4 rows / $0.0381 credited. Declining to inflate that to $18.79 is right, and it's the behaviour the review standard exists to protect.
- The mixed-TTL head-share sweep — external simulation. Moot: the feature is off and honestly projected at $0 on the models this service runs.
One provenance note on the e2e
The binary (bin/cgp-ka, built 00:39) predates the commit (01:02), and the ping row shows max_tokens: 0 where the committed record1 sets ev.MaxTokens = 1. The benign reading is well supported — output_tokens: 1 with stop_reason: max_tokens is what max_tokens: 1 on the wire produces, not max_tokens: 0 (which returns content: [] and bills no output) — so this is the dashboard column being added after the run, not a different wire body. Worth saying in the PR rather than leaving the row to be noticed.
Separately: the max_tokens: 1 comment's reason is wrong. max_tokens: 0 is rejected with stream: true, thinking.type: "enabled", output_config.format, or a forcing tool_choice — and the ping sets stream: false and refuses thinking, so those two don't apply. The choice is still defensible (output_config.format, forced tool_choice, gateway variance); the stated justification isn't.
Full review with every command and reproduction at /tmp/cg-orch/REVIEW-86.md. The reviewer's arms are left as proxy/{keepalive_gate_review,ka_probe_review,limits_review,spend_review}_test.go in a pinned tree — happy to hand those over if useful.
The parts that were hardest to get right are right: kaEntry.startedAt anchored at request start is the single decision that keeps this positive rather than −$241.99, and it's correct and tested. None of the blocking items is a redesign.
| if k == nil { | ||
| return | ||
| } | ||
| if keepAliveDisabled() { |
There was a problem hiding this comment.
The kill switch stops pinging but not retention, and it removes the only thing that enforces the 14-minute bound.
keepAliveDisabled() is read only here. With CONTEXT_GURU_KEEPALIVE=off the sweep never launches, but record() still runs from serve's defer and still retains the caller's provider credential and full request body. The sweep is the only path that retires an entry by policy (L411-423), so with it dead the remaining removal paths are arrive (next request on that session) and evictLocked (512 sessions / 128 MiB). A session that never comes back is held until eviction pressure arrives — on a quiet box, indefinitely.
That makes two published statements false:
- L158 — "held for at most MaxPings x Idle plus one sweep"
docs/how-to/cache-keepalive.md:137— "retired by the policy itself after at most(K+1) x X"
The docs put the kill-switch section immediately before the retention section, so an operator reads both and neither holds in combination. This is the worst case available: the switch gets pulled at 3am precisely because something is wrong, and the result is every opted-in tenant's provider key resident in memory with no ping to show for it.
TestKillSwitch documents the behaviour ("the switch stops the timer") and calls recordOne before its assertion without ever checking that nothing is held.
Fix (two lines): capture the switch on the keeper in newKeeper and test it at the top of record beside pol.on(). Then assert k.Stats().Live == 0 in TestKillSwitch.
| // | ||
| // startedAt is the instant the upstream request STARTED, per the provider's lifetime rule. | ||
| // The body is the exact bytes that went upstream. | ||
| func (k *keeper) record(tn *Tenancy, session string, startedAt time.Time, body []byte, |
There was a problem hiding this comment.
The gate the adjudication recommended is absent, and it is the highest-leverage change in this review.
record tests status 2xx, pol.on(), body <= 8 MiB, cacheAwareProvider, "the response reported some cache tokens", and thinking.type != enabled. There is no turn counter and no prefix-size floor, and config.CacheConfig exposes no knob for either.
I quantified it by applying the gate at this call site and driving your own snapshot harness (proxy/keepalive_gate_review_test.go):
| policy | pings | ping $ | converted | net $ | sessions touched | net-negative |
|---|---|---|---|---|---|---|
| blanket (as shipped) | 8,964 | 109.08 | 159 | +134.01 | 3,809 | 3,772 |
| turn>=1 | 1,861 | 105.76 | 157 | +132.01 | 358 | 321 |
| prefix>=20k | 986 | 107.44 | 155 | +132.05 | 128 | 93 |
| turn>=1 AND prefix>=20k | 961 | 105.73 | 153 | +128.44 | 120 | 85 |
9.3x fewer pings and 32x fewer sessions touched for 4.2% less money — stronger than the adjudication's 8.7x/3.3%. Ping cost barely moves ($109.08 -> $105.73) because the gate drops only the near-free pings, exactly as predicted.
Three reasons this is not a preference:
- 8,003 avoidable requests onto a path that already logged 180 HTTP 429s in this window — and your snapshot test correctly notes it models no rate limits, so it is an upper bound on pings.
- It is also the fix for the credential question. 120 retained credentials instead of 3,809 is a 32x reduction in blast radius for $5.57.
- It is why the 512-session bound binds. Instrumenting the replay:
peak live sessions 512 (bound 512). The keeper is evicting live sessions on real traffic. Under the gate it never comes close.
Side effect worth knowing: because eviction ties break on Go map order, the projected ping count is not reproducible — three runs of X=280s_K=2 gave 8,961 / 8,966 / 8,967, mine gave 8,964, the PR body says 8,962. Ping cost, conversions and saved dollars are identical to the cent across all runs, so +$134.01 stands; the ping count is one draw of a +/-0.1% distribution.
| // event would make a healthy account look throttled on its own dashboard. | ||
| return func() {}, errNoSpare | ||
| } | ||
| t.count++ |
There was a problem hiding this comment.
A ping that is refused on concurrency has already consumed one of the tenant's requests-per-minute.
t.count++ lands here, then the concurrency check below returns errNoSpare without decrementing it. Proven (proxy/limits_review_test.go):
tenant rpm counter: before=1 after=11 (10 pings, all REFUSED on concurrency)
FAIL: 10 refused pings consumed 10 of the tenant's 100 requests/minute
This contradicts this function's own contract at L164-171 — "the requirement is that it never crowd out a request an agent is waiting on ... Skipping costs one idle span's refresh; displacing costs an agent a 429 it did not earn." It fires exactly when the tenant is at its concurrency ceiling, i.e. when it is busiest, and with K=2 across many idle sessions a sweep can burn a visible slice of the rate window on pings that all got refused.
Two more in the same function:
reserved() floors at 1, so reserved(1,0.25)=1 and reserved(2,0.25)=1. With Concurrent: 1 a ping takes the only slot and a real request behind it gets a 429 — demonstrated in the same test file. TestPingNeverUsesTheLastConcurrencySlot only proves a ping will not take an already occupied slot; the name claims more than it tests.
The headroom check is not atomic with the select send. The comment allows for "a racing real request", but the real risk is racing pings: sweep dispatches every due job on its own goroutine, so N pings for one tenant can each observe headroom and collectively overrun the reservation up to cap.
Fix: decrement t.count on the concurrency-refusal path (or test concurrency headroom first), and either drop the floor-at-1 or reword the contract to admit it.
| // MaxPings is K: the most pings one idle span may send. Zero disables. | ||
| MaxPings int | ||
| // MaxUSDPerSession caps what pings may cost one session. | ||
| MaxUSDPerSession float64 |
There was a problem hiding this comment.
This is a per-idle-span cap, not a per-session cap.
record builds a fresh kaEntry on every request (L360) and discards the previous one without carrying spent across, so every turn resets the budget. Proven (proxy/spend_review_test.go):
after a session had already spent $0.0200 against a $0.0100 cap, the next span starts at
spent=$0.0000 pings=0
Documented as per-session in three places: here, L166, and config.KeepAliveMaxUSDPerSession ("caps what pings may cost one session"). A session with N idle spans may spend N x the cap, and Claude Code session lifetime runs to p99 12.9 h.
Your own numbers already contradict the documentation: the replay reports worst single session -$0.9490, which is 3.8x the shipped $0.25 "per-session" cap. Those two figures cannot both be right unless the cap is per-span.
TestSpendCapStopsTheSession stages e.spent = 0.02 by hand, so it tests the gate but never the accumulation or the scope. Note also that testKeeper supplies no Prices, so every ping in the unit tests costs $0 and the e.spent += cost path is never exercised at all.
Either carry spent (and a turn count) in a small per-session ledger that outlives the entry, or rename the knob to what it is.
| // the session-recency map: doing so would re-date the session and make the NEXT real | ||
| // request's gap read as four minutes instead of the twenty it actually was, hiding the | ||
| // very thing this mechanism is here to demonstrate. | ||
| ev.Price(price, priced && (u.CacheRead > 0 || u.CacheWrite > 0 || u.Output > 0)) |
There was a problem hiding this comment.
Every ping credits itself with provider-prompt-cache savings.
Event.Price computes CacheSavedUSD from CacheRead unconditionally (dash/event.go:583-591), and this call prices ping rows through the same path. So a ping is booked as having "saved" the difference between fresh input and the read rate on tokens the ping would never have sent at all.
On your own live run that is ~$0.13 of phantom cache_saved_usd against $0.0073 of real cost — 18x the ping's own price. Scaled over the window's pings it is on the order of +$1,000 of fabricated cache savings in a headline PR #83 shipped.
keepaliveSavedUSD has exactly the right guard for this — if e.KeepAlive ... return 0 // a ping never credits itself. CacheSavedUSD needs the same one.
Related, in dash/overview.go:266-269: COUNT(*) and SUM(r.cache_read) include ping rows, so request counts, AVG(upstream_ms) and every per-request average are diluted. dash/query.go and dash/api.go contain no keepalive reference in this commit, so per-tenant stats and the Requests list neither exclude nor mark them. The two new waterfall steps are honestly built and do render — but they sit beside aggregates that quietly absorb the same spend.
| + 'ping buys back about 11.5 of itself. On this service\u2019s traffic, requests that ' | ||
| + 'resumed after the 5-minute window cost 8.5x a request that hit, and they were 23.6% ' | ||
| + 'of all spend. It is off by default because it is your money and nobody asked for it ' | ||
| + 'to be spent. Every ping is a row on your Requests tab marked keep-alive with its own ' |
There was a problem hiding this comment.
This promises an audit trail that is not implemented, and omits the disclosure your docs page carries.
grep keepalive dash/ui/app.js returns only this settings block. There is no Requests-tab badge, and no renderer for keepalive_pings, keepalive_misses_avoided or keepalive_net_usd — only the two waterfall dollar steps appear. A ping row on the Requests tab is currently indistinguishable from agent traffic.
On framing: docs/how-to/cache-keepalive.md:100-113 is exemplary — "a lottery with a strongly positive expectation and a losing median", 37 ahead / 3,775 behind, $0.0035 average loss, worst -$0.95, positive for 10 of 13 tenants. That is the honest account.
This control carries only the favourable half: "buys back about 11.5 of itself", "8.5x", "23.6% of all spend". 11.5:1 is a per-rescue ratio, not a per-session expectation, and a manager reading this box would reasonably conclude their sessions save money when 99.0% of individual sessions pay slightly more. One sentence fixes it — the docs page already has the words.
Two smaller points:
- The control is drawn only for managers (
if (mgr)), so a non-manager whose key is being spent cannot see the setting or turn it off. Exposing the aggregate ledger to everyone is the right half — per-tenant is the correct unit for a bill, and per tenant this is positive for 10 of 13 — but that should be a stated decision, not an omission. - The retained request body (the user's whole conversation, up to 8 MiB, for up to 14 minutes) is not mentioned here at all. Content capture is a separate consent control; a tenant who declined it has not agreed to this.
| // | ||
| // It is still off, because on THIS deployment the tier does not arrive. LiteLLM's | ||
| // Bedrock transform drops the `ttl` field before the request leaves (its | ||
| // `_remove_ttl_from_cache_control`, upstream issues #19848 / #20326), and Bedrock's own |
There was a problem hiding this comment.
This repeats the claim your own probe refuted. Same in proxy/modes.go:51 ("the gateway strips the ttl field before the provider sees it") and apply/opts.go:51 ("silently stripped before it reaches the provider").
apply/headttl.go and docs/how-to/cache-keepalive.md carry the corrected account, and I accept the refutation — it is logically airtight: if the field were stripped in transit, aws/claude-haiku-4-5 could not have returned ephemeral_1h_input_tokens: 36,251 of 36,574. The field arrives; Bedrock's model coverage is what refuses.
Please delete or correct these three, otherwise the next person to read config.go re-learns the wrong thing — and this is exactly the kind of disagreement-with-evidence that should be preserved, not buried under a stale comment.
| if !explicitBreakpointProvider(provider) { | ||
| return body, false, 0 // no explicit breakpoints, so no TTL to state | ||
| } | ||
| if len(body)/4 < minTokens { |
There was a problem hiding this comment.
The size gate can invalidate the cached head mid-session. Low priority since the feature is off by default.
This is evaluated per-request against a body that grows every turn. A session crossing 50,000 estimated tokens mid-session gains a ttl:"1h" inside its system blocks, changing the hashed head bytes and re-writing the whole prefix. Compaction then shrinks the body back below the threshold, and upgradeHeadTTL never strips an existing ttl — it returns the body untouched — so the head bytes flip back. Each crossing is a full-prefix write at 1.25x/2.0x, and the quoted economics (769 head-write events) do not appear to price the crossings.
There is no Ctx.TailOnly / ColdCache guard on this path. The mutation is stable while the body stays on one side of the threshold, which is why this is a threshold-crossing bug rather than a per-turn one.
Everything else about this file is right: it only re-labels existing marks so it spends no breakpoint slot (correct against the cap of 4 and issue #32), 1h-before-5m holds by construction because tools/system precede every message breakpoint, and it fails open whole-body.
| // by the difference. Derived from the documented multiplier rather than from a second | ||
| // configured rate, because no gateway publishes one: 2.0x input, minus whatever the 5m | ||
| // write rate is, on exactly the tokens the response says were written at 1h. | ||
| if e.CacheWrite1h > 0 { |
There was a problem hiding this comment.
The 1h pricing fix is correct and correctly scoped. Verified: (2*Input - CacheWrite) x CacheWrite1h matches the documented 2.0x/1.25x tiers, and deriving the premium from the multiplier rather than adding a prices.yaml field is the right call — /etc/context-guru/prices.yaml carries only global cache_read_frac: 0.1 / cache_write_frac: 1.25, and no gateway publishes a 1h rate.
I checked the other seven Price.Cost callers (extract_llm.go, extract_econ.go, cheapmodel/usage.go, promexport.go, proxy.go, dashcapture.go): every one prices context-guru's own compaction spend, which never sets a 1h TTL, so omitting the premium there is right rather than inconsistent.
One gap: cache_write_1h has no read path. The column's own doc says it "is the ONLY signal that a requested ttl: 1h was honoured", and the docs page says it "is what says when that changes" — but nothing in dash/api.go, dash/query.go, dash/ui/app.js or /stats reads it. The feature's stated verification mechanism currently requires hand-written SQL.
…zeroize, mask, revocation The idle keep-alive has to hold a caller's provider credential between requests, because the default deployment is caller-pays and a ping happens when no request is in flight. Seven controls, so the arrangement is reviewable rather than merely defensible. A hard deadline instead of an opportunistic sweep. Retirement at (K+1)x Idle is now a scheduled time.AfterFunc, so a process with no traffic still releases on time: coupling a security bound to a liveness loop is how a bounded hold silently becomes unbounded. The sweep's release is kept as the EARLIER of the two, not as the guarantee. Zeroize rather than dereference. A dropped []byte sits in the heap until a collection that may never come, and a dump taken in between still yields it, so every release path overwrites the bytes. That forced one design change and it is an improvement: the retained body is now a keeper-owned copy rather than the slice serve used, because overwriting a shared slice is the kind of cleverness that produces a mystery bug in a month. The zero-copy retention was a micro-optimisation in the wrong place, and the gate has cut tracked sessions to a handful. Mask the credential at rest under a crypto/rand per-process key. Be precise about what that buys: a heap or core dump, a crash report or a strings pass over a snapshot yields masked bytes instead of a working key, which is the accidental-capture class. It does not stop an attacker with code execution in this process — the mask is in the same address space. It is obfuscation at rest, not encryption. The credential is still plaintext for the duration of the ping, because net/http holds header values as strings and a Go string cannot be overwritten; the window is one request rather than the whole idle hold. Consent is re-read per request and withdrawing it retires what is already held, so a stale account flag can never extend a hold. A session that goes quiet instead is dropped by the deadline. The kill switch stops RETENTION, not merely pinging. CONTEXT_GURU_KEEPALIVE=off now retires in record instead of holding: a switch that kept the material while refusing to use it is the worst of both. Tests: the credential is held masked and never plaintext while still unmasking to the caller's own value; a server-held key retains nothing; release zeroizes the actual buffers, asserted on handles taken before release so it is about the bytes and not the pointer; the hard deadline fires with no request, no sweep and nothing else running; withdrawn consent retires an existing hold; the kill switch holds nothing. And an output-surface test over /stats, /metrics, the keeper snapshot, %+v of the live entry and the JSON log sink AT DEBUG LEVEL — for the credential and for the retained body, which holds the user's whole conversation — that fails if the debug log carries no keep-alive line, so it cannot pass by never exercising the path. Signed-off-by: Osher-Elhadad <[email protected]>
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review at 11ce67d — verdict still CHANGES-REQUIRED
Posted as a comment review because GitHub refuses
REQUEST_CHANGESon a pull request owned by the same account.
11ce67d lands the gate and fixes four of my earlier findings properly. What blocks merge is now almost entirely the owner's credential-hardening bar, which this commit predates.
Verification on a clean extraction of 11ce67d: gofmt -l . empty, go vet ./... clean, CGO_ENABLED=1 go test -race -count=1 ./... → 25 packages ok, no races, exit 0.
Compliance against the seven hardening requirements: 0 met, 2 partial, 5 not met
| # | Requirement | Status |
|---|---|---|
| 1 | Hard timer for (K+1)·X, no other activity, fake-clock testable | NOT MET — keepAliveTick = 2s is still the only mechanism; no time.Timer/AfterFunc; retirement is still opportunistic inside sweep |
| 2 | Zeroize on retirement and every exit path incl. panic, shutdown | NOT MET — clear() nils references; no recover on the ping path |
| 3 | Not plaintext at rest; ephemeral per-process key | NOT MET — no obfuscation of any kind |
| 4 | Consent echoed per request; revocation retires held state | PARTIAL — pol := tn.Cache is re-read per request so new retention stops, but it is still the stored flag, and held entries keep their e.pol snapshot and keep pinging for up to (K+1)·X |
| 5 | Durable audit row per ping | PARTIAL — all five fields present and correctly kept visible in the list while excluded from aggregates, but gated on k.h.rec != nil, so --dashboard off means no audit while pings still fly |
| 6 | Leak test for credential and body, with debug logging on | NOT MET — no such test exists |
| 7 | Kill switch stops retention and retires held state | NOT MET — keepAliveDisabled() still read only in start() |
Details and file:line in the inline comments. Sequencing noted for the record: this commit addresses my first-round findings, not the hardening bar, which is consistent with it having been authored before those requirements were sent.
Two exposure routes the seven requirements do not close
Account deletion and token revocation have no purge path. The keeper exposes only start, Stop, arrive, record, Stats; Stop() is process-wide and there is no per-tenant purge. So tenant.Delete, a revoke, and a disable all leave that tenant's credential and conversation resident for up to (K+1)·X — or indefinitely with the kill switch set. This repo already holds that invariant explicitly (TestDeleteCascadesEveryCredential); the keeper is a new credential store the cascade does not know about. Requirement 4 does not cover it — consent-via-config and account-deletion are different paths.
Requirement 3 leaves the body plaintext. It names only the credential, while requirement 6 correctly names the credential and the body. A core dump still yields every retained conversation in full. A leaked key is rotatable; a leaked transcript is not — worth a deliberate decision either way rather than an omission.
The gate: confirmed landed, confirmed default, figures re-derived
turn >= 1 is hardcoded in pingable() and DefaultKeepAliveMinPrefix = 20000 is applied by Resolved() on any value <= 0, so the floor can be raised but not removed. Re-derived from TestKeepAliveOnProductionSnapshot myself:
| arm | pings | ping $ | converted | net $ | sessions | winners / losers | worst |
|---|---|---|---|---|---|---|---|
| blanket X=280 K=2 | 8,915 | 93.79 | 153 | +127.26 (4.05%) | 3,810 | 36 / 3,774 (−$13.10) | −$0.9490 |
| gated (default) | 912 | 90.76 | 148 | +125.08 (3.98%) | 119 | 34 / 85 (−$13.59) | −$2.4192 |
9.8× fewer pings, 32× fewer sessions, 1.7% less money — exactly as the commit message claims, both figures to the digit. (The "8,962 vs 1,060" pair still in circulation is from the earlier body and the adjudication's simulator; at HEAD it is 8,915 → 912.)
The gate also fixed a reproducibility defect as a side effect: three runs now give a stable pings 912, where the blanket arm drifted 8,961–8,969 because the 512-session bound saturated and eviction ties break on Go map order. And gating at record rather than in due() independently reaches the finding I filed last round (eviction discarding the entries about to pay, 153 → 69) — right call, and the better security posture since it holds nothing for a session it will not ping.
Fixed properly, and worth saying so
- Aggregate contamination — one
r.keepalive = 0inFilter.where(), withWithKeepAliveopted back in for the list and the ledger, and money deliberately retained inTenantSpendand the Prometheus series because the spend was real. Right shape, and the comment names the failure it prevents. - Per-session cap → per-ping budget, projected before sending, failing open on an unpriced model with the reasoning stated. Correct answer to the bimodal cost distribution.
- The consent disclosure now carries the losing median and matches my independent numbers exactly (34 of 119 ahead, worst $2.42). The docs downside table likewise does not hide that the gate makes the worst session worse. That is the standard.
- The three stale LiteLLM comments are corrected.
- Also: the body's "4.5 days" is right and my brief's "5.5 days" was wrong — the snapshot spans 2026-08-17T11:48:31Z .. 2026-08-21T23:01:45Z.
Still open from the first review
AcquireSparerate-budget leak — unchanged; my test still fails (10 refused pings consume 10 of 100 req/min). The gate makes it 10× rarer, not fixed.CacheSavedUSDstill fabricated on ping rows — the aggregate error is fixed, but the per-row value is now displayed in the one view that opts pings back in.- The audit surfaces the consent copy promises still do not render — the backend now supplies everything; of five promises only ping cost renders.
upgradeHeadTTL's mid-session size-gate invalidation — unchanged, still low priority since the feature is off.
Housekeeping
PII scan of the full diff (1dca2eb..11ce67d, 4,136 lines) and the rendered body (421 lines) against a PUBLIC repo: no email addresses, no session/request UUIDs, no /home or /Users paths, no screenshots or githubusercontent links, no named tenants or account labels, no third-party handles. The only credential-shaped strings are the synthetic sk-caller-secret and cg_live_0123… fixtures in the retention test, which are correct. Commit Author / Signed-off-by carry the repo owner's own address, which is expected. Nothing to redact.
No history rewrite is needed or recommended — the branch squash-merges, so the hardening belongs in a further commit on top.
Full review including every command at /tmp/cg-orch/REVIEW-86.md.
| if k == nil { | ||
| return | ||
| } | ||
| if keepAliveDisabled() { |
There was a problem hiding this comment.
Hardening requirement 7 — NOT MET (unchanged). keepAliveDisabled() is still called only from start(). record() has no check, so CONTEXT_GURU_KEEPALIVE=off retains the credential and body while removing the sweep that is the only thing that would ever retire them.
Requirement 1 — NOT MET. keepAliveTick = 2 * time.Second (L141) remains the only mechanism; there is no time.Timer / time.AfterFunc in the file, and retirement is still an opportunistic branch inside sweep (L519-528). The bar asks for a hard timer that fires with no other request or sweep activity, testable on a fake clock.
These two interact: with the switch set there is no sweep, so the (K+1)·X bound the comment at L158 and docs/how-to/cache-keepalive.md both promise does not exist on that path.
|
|
||
| // clear drops an entry's body and credential. Called on every removal path, because the two | ||
| // things this holds are the two things it must not hold longer than it needs to. | ||
| func (e *kaEntry) clear() { |
There was a problem hiding this comment.
Requirement 2 — NOT MET. clear() drops references (body = nil; hdr = nil); the bar asks for the bytes to be overwritten. Note hdr is an http.Header map, so zeroizing it means walking the values, not just nilling the map.
Also not covered: the panic path. fire has no recover, so a panic in record1 or sendPing unwinds with the entry still populated, and Stop() only runs on an orderly shutdown.
Requirement 3 — NOT MET (no obfuscation of any kind). One thing to get right when it is implemented: XOR against an ephemeral per-process key defeats casual scraping — a strings pass, an accidental log capture, a naive crash reporter — and nothing more, because the key lives in the same address space as the ciphertext. State that limit in the comment and the PR body, or the mitigation will be read as protection it is not.
And a scope gap worth raising with the owner: requirement 3 names only the credential, while requirement 6 correctly names both the credential and the body. A core dump still yields every retained conversation in full. A leaked key is rotatable; a leaked transcript is not.
| if status < 200 || status >= 300 { | ||
| return | ||
| } | ||
| pol := tn.Cache |
There was a problem hiding this comment.
Requirement 4 — PARTIAL. pol := tn.Cache is re-read on every request, so revocation stops new retention at the tenant's next request. Two gaps against the bar:
- It is still the stored account flag, not a per-request echo.
- Nothing retires what is already held. The entry keeps its record-time
e.polsnapshot, and bothdue()(L213) and the retirement branch (L522) read that snapshot — so a tenant who revokes consent keeps being pinged with the old policy for up to (K+1)·X.
An exposure route none of the seven closes: the keeper exposes only start, Stop, arrive, record, Stats — there is no per-tenant purge, and Stop() is process-wide. So tenant.Delete, a token revoke, and an account disable all leave that tenant's credential and conversation resident for up to (K+1)·X, or indefinitely with the kill switch set.
This repo already treats that as an invariant — tenant/manager_test.go has TestDeleteCascadesEveryCredential. The keeper is a new credential store the cascade does not know about. Suggest a keeper.forget(tenantID) called from the delete/revoke/disable paths, and extend that existing cascade test to cover it.
| break | ||
| } | ||
| } | ||
| if k.h.rec != nil { |
There was a problem hiding this comment.
Requirement 5 — PARTIAL. The row carries all five required fields (tenant, session, timestamp, cost, and read-vs-wrote via cache_read/cache_write), and 11ce67d improved it correctly: pings are excluded from aggregates while the request list opts back in, so the trail stays visible and the counts stay honest.
The gap is this line. if k.h.rec != nil means that with --dashboard off there is no row and therefore no audit at all, while pings still fly. An audit control that a deployment flag silently removes is not a control — the bar calls this "the control that makes the arrangement reviewable".
Two options: refuse to ping when there is nowhere to record it, or give the keeper a minimal always-on sink independent of the dashboard.
Requirement 6 — NOT MET. No leak test exists: grep 'slog.SetDefault|LevelDebug|CG_LOG_LEVEL|NewJSONHandler' across proxy/keepalive_test.go and dash/keepalivecost_test.go returns nothing. My own first-pass audit found no leak by inspection (no %+v of kaEntry/pingJob, nothing writes hdr/body, /stats carries counters only) — but inspection is not the control, and production runs CG_LOG_LEVEL=debug at ~8x the line volume, which is the realistic path. The test must assert on both the credential and the body, with debug logging on.
| // session-end signal and is the opposite — P(gap > 300s) is 37.15% after it against 0.74% | ||
| // after `tool_use`, and 83.7% of the recoverable dollars sit behind it. | ||
| func (e *kaEntry) pingable() bool { | ||
| return e.turn >= 1 && e.prefix >= int64(e.pol.MinPrefixTokens) && |
There was a problem hiding this comment.
The gate is confirmed landed, and confirmed to be the DEFAULT rather than opt-in. turn >= 1 is hardcoded here with no knob, and DefaultKeepAliveMinPrefix = 20000 is applied by Resolved() whenever the configured value is <= 0 — so a tenant can raise the floor but cannot remove it by omitting or zeroing it, and validate() rejects negatives. Good shape.
I re-derived both figures from TestKeepAliveOnProductionSnapshot myself and they reproduce to the digit:
| arm | pings | ping $ | converted | net $ | sessions | winners/losers | worst |
|---|---|---|---|---|---|---|---|
| blanket X=280 K=2 | 8,915 | 93.79 | 153 | +127.26 | 3,810 | 36 / 3,774 | -$0.9490 |
| gated (default) | 912 | 90.76 | 148 | +125.08 | 119 | 34 / 85 | -$2.4192 |
9.8x fewer pings, 32x fewer sessions, for 1.7% less money — exactly as the commit message claims. (For the record: the "8,962 vs gated 1,060" pair in circulation comes from the earlier body and the adjudication's simulator; at HEAD it is 8,915 → 912.)
Two things worth noting in the PR body:
- The gate fixed a reproducibility defect as a side effect. Three runs each now give a stable
pings 912; before the gate the blanket arm drifted 8,961-8,969 across runs because the 512-session bound saturated and eviction ties break on Go map order. - Gating at record time rather than in
due()is the right call, and your note at L205-211 independently reaches the finding I filed on the previous commit (eviction discarding the entries about to pay, 153 → 69 conversions). It is also the better security posture, since it holds no body or credential for a session it will not ping.
| @@ -539,6 +591,7 @@ func (e *Event) Price(p modelinfo.Price, accountingComplete bool) { | |||
| e.CacheSavedUSD = 0 // a provider whose cache reads cost MORE than fresh input saved nothing | |||
There was a problem hiding this comment.
Residual from the previous review: CacheSavedUSD (L589, just above) is still unconditional on ping rows.
The Filter.where() exclusion in 11ce67d fixes the aggregate error properly — that was the ~$1,000 of phantom cache savings, and the fix is the right shape. But the stored per-row value is still fabricated, and it is now displayed in the one view that opts pings back in: a ping row on the Requests tab shows "cache saved ~$0.13" beside a cost of $0.0073, on tokens the ping would never have sent at all.
keepaliveSavedUSD already has exactly the right guard (if e.KeepAlive … return 0 // a ping never credits itself). Wrapping the two lines above in the same if !e.KeepAlive does it.
| + 'ping buys back about 11.5 of itself. On this service\u2019s traffic, requests that ' | ||
| + 'resumed after the 5-minute window cost 8.5x a request that hit, and they were 23.6% ' | ||
| + 'of all spend. It is off by default because it is your money and nobody asked for it ' | ||
| + 'to be spent. Every ping is a row on your Requests tab marked keep-alive with its own ' |
There was a problem hiding this comment.
The downside disclosure is now here and it is accurate — "a small tax on most of the sessions it touches, funding a large rebate on a few … 34 of 119 pinged sessions came out ahead and the worst single session paid $2.42 for nothing. Watch your own ledger and switch it off if you are not one of the winners." That matches my independent re-derivation exactly (34 winners of 119, worst -$2.4192). Thank you — this is the honest framing, and the docs downside table not hiding that the gate makes the worst session worse (-$0.95 → -$2.42) is the same standard.
Still outstanding: the surfaces this copy promises do not render. dash/query.go now supplies e.KeepAlive and e.CacheWrite1h to the list, so the data is all present — but app.js has no badge renderer and no renderer for keepalive_pings, keepalive_misses_avoided, or keepalive_net_usd. Of the five things this paragraph promises (a row marked keep-alive; pings; ping cost; misses avoided; the net) only ping cost renders, via the waterfall.
Since the backend work is done, this is a rendering change: badge the row off the keepalive column, and put the four ledger numbers somewhere on Overview.
| return func() {}, errNoSpare | ||
| } | ||
| t.count++ | ||
| t.mu.Unlock() |
There was a problem hiding this comment.
Residual from the previous review: unchanged. t.count++ still precedes the concurrency check, and the errNoSpare return below does not refund it — so a ping that never went out has consumed one of the tenant's requests-per-minute. My test still fails against this commit:
tenant rpm counter: before=1 after=11 (10 pings, all REFUSED on concurrency)
FAIL: 10 refused pings consumed 10 of the tenant's 100 requests/minute
This contradicts the contract at L164-171 ("it never crowd out a request an agent is waiting on"), and it fires exactly when the tenant is at its concurrency ceiling. The gate makes it much rarer — 912 pings instead of 8,915 — but rarer is not the same as fixed, and the failure mode is a 429 the agent did not earn.
Also unchanged: reserved(1,0.25)=1 and reserved(2,0.25)=1, so at Concurrent: 1 a ping takes the only slot; and the len(t.inFlight) check is not atomic with the send, so concurrent pings for one tenant can collectively overrun the reservation up to cap.
Fix is a t.count-- on the refusal path, or test concurrency headroom first.
Correction: compliance re-checked at
|
| # | Requirement | Status | Evidence |
|---|---|---|---|
| 1 | Hard timer for (K+1)·X, fires with no other activity | MET | e.timer = time.AfterFunc((MaxPings+1)*Idle, …) (keepalive.go:556); the sweep's release is kept as the earlier of the two rather than as the guarantee. Subtest the hard deadline fires with no other activity. |
| 2 | Zeroize on every release path | MET | clear() calls zero(e.body) and zero(e.auth[i].val) and cancels the timer (L403-415). The body is now a keeper-owned copy, which is the right call — overwriting the slice serve handed over would have been a mystery bug later. Subtest asserts on handles taken before release, so it tests the bytes and not the pointer. |
| 3 | Masked at rest under an ephemeral per-process key | MET | credMask is a 32-byte crypto/rand package-level key that panics if entropy is unavailable (L99-105) — fail-closed, no silent zero key. xorMask is its own inverse. |
| 4 | Consent re-read per request; revocation retires held state | MET | pol := tn.Cache re-read, and if !pol.on() { k.retire(key); return } (L473-477) now retires rather than merely declining to add. A session that goes quiet is caught by the hard deadline. |
| 5 | Durable audit row per ping | STILL PARTIAL | if k.h.rec != nil (keepalive.go:813) is unchanged, and the commit message does not mention this requirement. With --dashboard off there is no row and therefore no audit, while pings still fly. This is the one control still open. |
| 6 | Leak test for credential and body, debug logging on | MET | TestRetainedMaterialReachesNoOutputSurface (L736) with slog.NewJSONHandler(…, Level: slog.LevelDebug), covering /stats, /metrics, the keeper snapshot, %+v of the live entry and the JSON log sink. Doubly anti-vacuous: it fails if nothing was retained and fails if the debug log carries no keep-alive ping line. Good test. |
| 7 | Kill switch stops retention and retires held state | MET | keepAliveDisabled() now checked inside record (L464), retiring instead of holding. |
And thank you for stating requirement 3's limit precisely rather than letting it read as encryption — "a heap or core dump, a crash report or a strings pass yields masked bytes instead of a working key … It does not stop an attacker with code execution in this process — the mask is in the same address space. It is obfuscation at rest, not encryption." That is exactly right, and disclosing that the credential is unavoidably plaintext as a Go string for the duration of the ping (because http.Header holds strings) is the kind of residual that usually goes unmentioned.
Two things still open
1. Requirement 5 — the audit row is removable by a deployment flag. if k.h.rec != nil. An audit control that --dashboard silently switches off is not a control. Either refuse to ping when there is nowhere to record it, or give the keeper a minimal always-on sink.
2. Account deletion and token revocation still have no purge path. Requirement 4 closes consent-withdrawn-via-config, which is a different path. keeper now has retire(key) but still no forget(tenantID), and Stop() is process-wide — so tenant.Delete, a revoke and a disable each leave that tenant's masked credential and zeroize-on-release body held until the hard deadline. That is now bounded at (K+1)·X by requirement 1, which is a real improvement over indefinite, but this repo holds the stronger invariant explicitly (TestDeleteCascadesEveryCredential) and the keeper is a credential store the cascade does not know about.
Lower priority, noted for the record: requirement 3 masks the credential but the body — the user's whole conversation — is held plaintext until release. It is zeroized on release now, and the gate cut concurrent holds to a handful, so the exposure is much smaller than it was. Worth a deliberate decision rather than an omission.
Everything else from my two earlier reviews stands as posted: the AcquireSpare rate-budget leak (limits.go:198), CacheSavedUSD still unconditional on ping rows, and the consent copy's promised Requests-tab badge and Overview ledger still not rendering.
…used pings spending a tenant's rate budget Event.Price computed cache_saved_usd from cache_read unconditionally, and a keep-alive ping reads the whole prefix by design — so every 48k ping booked about $0.13 of provider-cache saving against $0.0073 of real cost. cache_saved_usd is a figure the dashboard puts on the page, so at production ping volumes that is order a thousand dollars of savings this service did not earn. One guard in the shared function rather than at each caller: without the keep-alive that request does not exist, so there is no fresh-input alternative for it to have saved against. The ping's own cost is untouched — the guard suppresses a phantom saving, not real spend. AcquireSpare had three faults, each of which broke the promise in its own doc comment that a ping never crowds out a real request. It incremented the per-minute counter before testing concurrency and never gave it back, so ten pings refused on concurrency ate ten of a tenant's hundred requests a minute, and did so precisely when the tenant was busiest. reserved() floored at one, so at Concurrent: 1 a ping took the only slot and the next real request got a 429; a tenant whose whole budget is one in-flight request has no slack and is now correctly never pinged. And the headroom test ran outside any lock, so two pings could both read "there is room" and both take the last spare slot. Now: slot first, counter last, both under the tenant's lock, and the slot returned if the rate check refuses. The consent copy promised an audit trail that did not render. Ping rows now carry a keep-alive pill on the Requests tab in place of the cache-outcome pill — an unlabelled one-token request the user did not make is worse than not showing it — and the Overview carries a tile with the NET and pings, ping cost, misses avoided and saving beneath it, hidden until the mechanism has done something so an unopted deployment shows no row of zeroes. Disclose the retained body. It cannot be reduced: the prefix hash covers the whole tools/system/messages sequence, so a ping that trimmed it would miss the cache and cost 12.5x instead of saving 11.5x. So the consent copy and the docs say what is held, and say explicitly that it is NOT the transcript-storage consent — that one governs writing content to disk where a manager can read it, this is memory only, masked, overwritten on release, never persisted, gone in about fourteen minutes. Enabling a spending feature is not consent to retaining conversation content. docs/hosted.md stated the invariant this feature falsifies — "stores none: the key is read off the request and dropped". It now carries a scoped exception naming the opt-in, the bound and the audit trail, and says nothing is retained for an account that has not enabled it. The forwarded-not-stripped correction is taken: forwarding the caller's key IS the caller-pays design, and only our own minted token is scrubbed. Correct the stale figures in my own comments. keepalive.go and config.go quoted +$170.08 / 9,234 pings / 182 conversions as the shipped result where the shipped function gives +$125.08 / 912 / 148, overstating the mechanism by 27%. The "net peaks at K=2" claim did not reproduce and is withdrawn: K=2 gives +$125.08 against K=3's +$130.80, a tie inside the run-to-run wobble, so K=2 is the default for the request-volume reason and not a dollar one. The max_tokens: 1 rationale was also wrong — 0 is rejected alongside streaming and thinking, and this ping excludes both — so it now states the real reason, which is one output token of compatibility insurance at a tenth of a percent of the read's cost. Also: correct three comments still repeating the refuted claim that LiteLLM strips the ttl field; sum cache_write_1h on the Overview so the mixed-TTL verification is a glance rather than hand-written SQL; and note that upgradeHeadTTL's size gate can flip mid-session, with the upgrade path named. The 512-session bound did bind on the blanket policy, which is where its ping-count wobble came from. The replay now reports peak live sessions: 512 of 512 blanket, 11 of 512 gated. The gate fixes it and the bound stays. Signed-off-by: Osher-Elhadad <[email protected]>
Final verification at
|
| route | drops cached tenancy | drops keeper hold |
|---|---|---|
ctlDeleteTenant (control.go:1894) |
yes, L1926 | no |
ctlRevokeToken (control.go:1305) |
no | no |
ctlRevokeSession (control.go:1083) |
no | no |
So a deleted, revoked or disabled account's masked credential and plaintext body stay held until the hard deadline. Requirement 1 bounds that at ~14 minutes, which is a real improvement over the unbounded case — but this repo holds the stronger invariant explicitly, and the keeper is a credential store the cascade does not know about. A keeper.forget(tenantID) iterating live on the tenant prefix, called beside the existing Tenants.Forget and added to the two revoke routes, closes it.
3. Minor, but it is in the security disclosure. docs/how-to/cache-keepalive.md describes the retained body as "memory only, masked, overwritten on release, never persisted". The body is not masked — xorMask is applied only at L890 and L918, both on a.val (the credential). The body is owned := append([]byte(nil), body...) at L522, held plaintext and zero()ed on release. One word: drop "masked" from that sentence and leave it on the credential row where it is true.
Nit: one stale simulator figure survives at dash/event.go:741 — "(39 of 9,234 at X=280s)". Under the shipped gate it is 53 of 912.
Verified fixed
The $1,000 fix, and the reasoning holds. dash/event.go: e.CostUSD = p.Cost(...) is computed before and outside the guard, so the ping's own cost survives; if !e.KeepAlive { e.CacheSavedUSD = ... } zeroes only the savings; an ordinary hit keeps its diagnostic untouched. Putting the guard in the shared Event.Price rather than per caller is the right call — every future caller inherits it, and a per-caller guard would have left the next one broken.
The counterfactual argument is sound. CacheSavedUSD answers "what did the cache save on this request, versus sending it with no cache". For a ping the counterfactual is not "the same request uncached" but "no request at all" — the cache did not save anything, it created the opportunity to spend. Zero is the correct value, not a convenient one.
And I checked the Filter.where() claim directly rather than taking it. dash/query.go:76-77 appends r.keepalive = 0 unless WithKeepAlive; dash/overview.go:274 calls f.where() and COUNT(*) (L280), SUM(r.cache_read) (L283) and AVG(r.upstream_ms) (L330) are all inside that one query using that cond. dash/api.go has zero WithKeepAlive references and builds its Filter at L584, so it inherits the exclusion. Exactly one opt-in exists (query.go:179, the request list), plus the ledger which correctly uses a separate query — withKeepAlive(f).where() at overview.go:385 — rather than trying to read ping rows out of a query that excludes them. That was the subtle way to get this wrong and it was avoided.
AcquireSpare — all three, plus the race. My own arms, re-run against this commit:
TestReviewSkippedPingConsumesRPM: before=1 after=1 (10 pings, all REFUSED) PASS
TestReviewReservationFloorAtOne: reserved(1,0.25)=0 "ping refused the only slot" SKIP
The skip is for the right reason: reserved now floors at 0 via math.Ceil, so at Concurrent: 1 the headroom test len(inFlight) >= 0 is true immediately and the ping is refused — my test's AcquireSpare genuinely errored rather than the assertion being bypassed.
Better than the refund I suggested: the order is inverted — concurrency first, rate counter incremented last, so on the concurrency path there is nothing to refund. And the reverse path is handled: if the rate check fails after the slot is taken, release() is called ("give the concurrency slot straight back") — I checked specifically for a leaked slot there and there isn't one. The ping-vs-ping race I raised is also closed: the headroom test and the slot take are now both under t.mu, so two pings cannot both read "there is room".
The retained body — I accept the irreducibility argument, with one refinement. It is correct that the cache key is the exact bytes of the rendered prompt cumulatively up to each breakpoint, so a trimmed replay misses. The precise statement is narrower than "cannot be reduced": a ping could legitimately replay only up to an earlier breakpoint and refresh that entry. It would just be nearly worthless here — production's modal layout is 2 breakpoints in system plus 1 trailing message block, and in that shape the bulk of a 48k prefix sits behind the trailing one. A head-only ping refreshes the head, the next real request then misses on everything after the last system breakpoint and re-writes it, and you have paid for a partial rescue. Truncating messages instead is not available at all: it breaks role alternation and orphans tool_use ids into a 400.
So: irreducible for a full-prefix refresh, which is the only refresh worth having. The claim is right; I would just phrase it as that rather than as an absolute.
And the disclosure is genuinely good. "The body is conversation content, and enabling the keep-alive is what consents to holding it" — with the distinction from transcript-storage consent stated explicitly and correctly: "that one governs writing content to disk, where a manager can read it and a retention window applies. This is memory only … never persisted, and gone within about 14 minutes." That is the right distinction and the right place for it. Fix the "masked" word (item 3) and it is accurate as well as adequate. The one thing the checkbox copy itself still omits is the body — the docs carry it, the consent control does not.
Everything else confirmed: docs/hosted.md:46-52 now scopes the clause (the "and stores none" absolute is gone, followed by "One exception, and only if you switch it on"). The Requests-tab pill renders (app.js:1454) and the Overview tile renders behind (o.keepalive_pings || o.keepalive_saved_usd) so it is hidden until the feature has done something (L694-699), showing the net as the headline with "N pings $X · M misses avoided $Y" and colouring on the sign. All three LiteLLM comments corrected. cache_write_1h has its read path and SUM(r.cache_write_1h) at overview.go:341. The upgradeHeadTTL mid-session flip is documented as a ponytail: comment naming the ceiling and the upgrade path ("latch the decision per session instead of recomputing it") — and it correctly notes a differing ttl does not change the prefix hash, so neither direction costs a miss, which is a better answer than my original finding assumed.
K: ship K=2 — and the framing undersells the decision
K=2 +$125.08 / 912 pings against K=3 +$130.80 / 1,226 pings, both re-derived here. Ship K=2, and I would not describe it as trading dollars for request volume, because the dollars are not real:
$5.72 over 4.47 days is $1.28/day on a policy whose bootstrap CI is [$95, $237] with a 1.4× split-half temporal swing. A 4.6% difference is far inside that — the two are statistically indistinguishable at this sample size. What K=3 costs, by contrast, is all measurable and all directional:
| K=2 | K=3 | ||
|---|---|---|---|
| pings | 912 | 1,226 | +34% onto a path that logged 429s |
| ping spend | $90.76 | $121.33 | +34% spent to earn +$36 |
| worst session | −$2.42 | −$3.63 | +50% worse for the unluckiest user |
| total losses | $13.59 | $19.15 | +41% |
| retention window | 3×280s ≈ 14 min | 4×280s ≈ 18.7 min | +33% credentials held longer |
Two further reasons. The extra K=3 value comes from pings further from the last real request, which is precisely where the ping-onto-a-dead-entry failure lives — a write at 1.25× instead of a read at 0.1×, the one mode that inverts the feature. And the product promise is "save money and not raise their bill": making the worst individual session 50% worse for 4.6% aggregate is the wrong trade for a feature whose fairness case is already thin at 85 of 119 sessions losing.
If the K=3 dollars are wanted later, the honest lever is the prefix floor, not K — prefix>=50k at K=2 already gives +$125.12 on 908 pings, so raising the floor concentrates spend where it pays instead of extending coverage into the risky tail.
The 512 bound: 11 is representative, and the byte bound is the real ceiling
Good instrumentation — the test now reports it directly ("live sessions: peak 11 of 512 bound"). Sanity-checked: 119 gated sessions over 4.47 days is ~1.1/hour, and a ~14-minute hold gives an expected concurrency near 0.26, so a peak of 11 is a plausible burst rather than an artifact. It also moves sensibly with K (10 at K=1, 11 at K=2/K=3, 15 at K=12), which is what you would expect if it were tracking the hold window rather than noise.
Two caveats worth recording rather than acting on. It scales linearly with opted-in traffic — today that is zero tenants, so 46× headroom is a statement about today's mix, not an invariant. And the byte bound, not the session bound, is the effective ceiling: the replay uses ~350-byte synthetic bodies, where real gated sessions carry ≥20k-token prefixes at roughly 100 KB–1 MB. 128 MiB therefore binds at ~130 large sessions, well before 512. Both bounds are present and correct; it is just worth knowing which one would actually fire. Leaving 512 alone is right.
Two independent implementations, 0.7% apart
Worth recording: my harness and yours land at 909/+$124.26/119 sessions/87 losing and 912/+$125.08/119/85, worst session −$2.4192 in both — within 0.7% on dollars and identical on the session count and the worst case. Two implementations written from the same documented mechanism, disagreeing only in the noise, is decent evidence the mechanism is actually understood rather than curve-fitted.
Verdict: CHANGES-REQUIRED on requirement 5 and the purge path, plus the one-word docs fix. Both code items are small and the hook points already exist. Everything else on the list is done, and several things are done better than I proposed.
…n, and mask the retained body An audit control that --dashboard silently removes is not a control, and the per-ping row is the one that makes the whole credential arrangement reviewable. Given the choice between an unconditional second sink and refusing to hold what we cannot account for, take the second: with no dashboard recorder the keeper retains nothing. Three lines instead of a parallel writer, and it fails in the safe direction — a deployment without the dashboard keeps none of a caller's credential and none of their conversation. Account deletion, token revocation and disablement each end an account's authority, and the keeper is a credential store the registry's cascade did not know about. Requirement 4 covered consent withdrawn through configuration and the hard deadline bounds anything that goes quiet, but this repo asserts the stronger invariant explicitly in tenant.TestDeleteCascadesEveryCredential, and a revocation the user performed deliberately should not wait on a timer. Add keeper.forget(tenantID) and call it from all three control-plane paths; the ponytail comment names the fourth-path risk and the consolidation if revoke and disable ever start invalidating the cached tenancy too. Mask the retained body under the same per-process key as the credential. The asymmetry decides it: a leaked key is rotatable and a leaked transcript is not, and this is up to 8 MiB of the user's conversation. The sweep hands each ping an unmasked copy that fire zeroizes on every exit path, so the long-lived hold contains no readable transcript while the bytes on the wire stay identical — which the test asserts, because a ping that sent altered bytes would write a new entry at 12.5x instead of refreshing one at 0.1x. The audit-sink requirement changed what the test fixtures have to supply, and one of them was lying by omission: the output-surface leak test built a handler whose recorder was assigned after construction, which left it half-wired. It now uses a real in-memory recorder through New(), like the dashboard tests, so the surfaces under test are the fully-wired ones a deployment serves. Also: correct the last stale ping figure in a dash comment (39 of 9,234 -> 53 of 912), so every number in the tree quotes the shipped gated policy rather than an earlier blanket vintage. Signed-off-by: Osher-Elhadad <[email protected]>
Finding → commit mapFindings and fixes interleaved across five commits, so here is which commit closed what. Review verdicts were against
Three notes for the final verification: 1. The body-masking finding was resolved the other way round. The instruction was to drop "masked" from the docs because the body was not masked. Instead the body is now masked ( 2. The third purge route is a deliberate substitution, not a missed one. The finding named 3. Requirement 5 took the "refuse to retain" half of the choice, not the unconditional-writer half. That change also exposed a test of mine that could not have caught its own subject: the output-surface leak test assigned its recorder after |
Final verification at
|
Close-out at
|
…s bytes exactly, and record why K is 2 PUT /api/me is the route the Settings checkbox posts to, so unticking the keep-alive arrives at ctlUpdateMe rather than ctlPatchTenant — which made the PRIMARY consent-withdrawal path the one unwired route. Bounded either way (record re-reads the policy per request and the hard deadline caps the hold), but the path a user is most likely to take should not be the one relying on the backstop. TestRetainedBodyIsMaskedAtRest asserted bytes.Contains on a marker, and a surviving marker is not byte identity: a single corrupted byte anywhere else in the prefix passed, and that byte is a 1.25x write instead of a 0.1x refresh. The companion test exercises pingBody before masking exists, so neither covered the mask round trip. Now bytes.Equal against pingBody of the recorded body, which is the assertion that actually guards the failure mode. Justify K=2 honestly. It is not a dollars-for-volume trade, because the dollars are not real: K=3's +$5.72 over 4.47 days is $1.28/day against a bootstrap CI of [$95, $237] and a 1.4x split-half swing. What K=3 costs is measurable — 34% more pings onto a path that returned 180 HTTP 429s, the worst single session 50% worse at −$3.63, total losses up 41%, and a third longer on the credential hold. And its marginal value comes from pings furthest from the last real request, which is exactly where the ping-onto-a-dead-entry failure lives. If those dollars are ever wanted the lever is the prefix floor rather than K: 50,000 tokens at K=2 gives +$125.12 on 908 pings. Note that maxKeepAliveBytes rather than maxKeepAliveSessions is the binding ceiling. A gated session carries at least a 20k-token prefix, so 128 MiB binds around 130 sessions well before the 512 count; the replay's peak of 11 exercises the count bound only because it drives ~350-byte synthetic bodies. Signed-off-by: Osher-Elhadad <[email protected]>
Spot-check at
|
…x the stale purge-path comment The two existing tests leave the seam between them uncovered. TestRetainedBodyIsMaskedAtRest stops at the k.send fake, so it asserts what fire HANDS to send rather than what is posted; TestSendPingHitsTheUpstream starts after masking, passing a plaintext Authorization and pingBody output directly, so it never exercises an unmask at all. A mask bug between those points is invisible to both, and that bug is a 1.25x cache write where a 0.1x refresh was intended — the one failure mode that inverts the feature. So drive the whole chain: masked hold, sweep unmask, fire, and the real sendPing over real HTTP to an httptest server with k.send deliberately not overridden. It asserts the RECEIVED body is byte-equal to pingBody of the recorded one, compares the six hashed fields off those received bytes, checks the cache_control count is unchanged, and confirms the wire Authorization is the caller's plaintext key — so the unmask happens, and happens only there. It fatals first if the hold is not actually masked, so it cannot pass vacuously. The body half of that is the silent failure and is what makes this worth having; the credential half is loud (a corrupted key is a 401, markStopped, and zero successful pings), so this is coverage rather than a hole being closed. Also: the ponytail comment on keeper.forget had gone stale in the way that matters, describing three call sites that "revoke authority" when there are now four and the fourth does not fit that description. PUT /api/me ends CONSENT — the credential still works and the hold is still authorized, but permission to use it is gone. That authority-versus-consent distinction is the reasoning that justified leaving ctlRevokeSession out, so a comment that loses it loses the design rationale, not just a count. Signed-off-by: Osher-Elhadad <[email protected]>
#86 (cache keep-alive) landed on main and touched the same apply.Opts literal in applyMode that this branch touches, so proxy/modes.go conflicted textually while both sides were purely additive. Resolved by keeping both: RatesFor (this branch, so a component that compacts with a model other than the request's own prices from the operator's rate card) alongside HeadTTL1h / HeadTTLMinTokens (main, the mixed-TTL head from the tenant's cache policy). Nothing dropped from either side; the observe() literal took this branch's RatesFor unconflicted because main did not touch it. Signed-off-by: Osher-Elhadad <[email protected]>
#86 (cache keep-alive), #90 and #89 landed on main and touched the same four files this branch does. Every conflict was two additive changes sharing a line; none had opposed intent, and both sides survive everywhere. dash/schema.go — additiveColumns holds all seven new columns (this branch's cache_ttl, sse_buffered, ttfb_ms plus main's cache_write_1h, keepalive, keepalive_pings, keepalive_saved_usd). schemaVersion stays 6: a bump renames the live database aside and would discard the dashboard's whole request history to gain a column that ALTER TABLE adds in place. dash/store.go — the requests INSERT takes the union of both column lists, with the placeholder count and the Exec argument list widened to match (60 columns, 60 placeholders, 60 values, in order). dash/overview.go — the Overview query appends both sides' aggregates and both sides' Scan targets in the same order (47 and 47): the streaming split, breakpoint placement and coverage counters from here, the keep-alive saving and 1h-write total from main. Filter.where()'s `r.keepalive = 0` exclusion is untouched, so ping rows still stay out of COUNT(*), SUM(cache_read) and the averages. proxy/proxy.go — the per-request defer runs both: main's keeper.record first, on the final round's body, then this branch's SSE accounting to the aggregator and the dashboard row. Still once per client request, not once per upstream round. Signed-off-by: Osher-Elhadad <[email protected]>
…gaps and cost (#196) * feat(kvcache): measure the idle keep-alive per ping — cache outcome, gaps and cost keepalive.go states what the mechanism is worth from a replay. This asks the same questions of what actually shipped, one row per ping, against the live ledger: did the ping read the entry it meant to refresh, how long after the previous request did it fire, did the request it was protecting then hit and how much later, and what did the ping cost. Add deploy/harbor/keepalive_ping_stats.py, next to the kv_ttl_* scripts, with two subcommands. The split is forced rather than stylistic: the dashboard database is readable only by the account the service runs as, and that account has no site-packages, so `collect` is stdlib-only and `stats` runs afterwards wherever pandas is. `collect` also reads a session export bundle, which needs no privileged access and is how this was developed. Identify a ping by requests.keepalive = 1. That is exact one way and a lower bound the other, and the script says so where a reader will see it: KeepAlive: true is set in exactly one non-test place (record1), nothing UPDATEs the column afterwards, and the column shipped with the emitter in #86 so no ping predates the flag — but a ping refused by the limiter, failed in transport or answered 4xx returns before record1 and never becomes a row. The collector cross-checks the flag against an independent fingerprint of record1's row shape, in both directions, and prints disagreement as a number rather than absorbing it. Two traps found against real rows, each of which silently inverts a headline: ts is the request START on an agent row and the ping's COMPLETION on a ping row, so every gap here is start-to-start — the footing CachePolicy.Idle and the provider's lifetime rule both use. Corrected, gap_before_s holds a 1.6s spread; uncorrected it scatters over 15s, the noise being the ping's own round trip. A non-2xx row is not "the request after the ping". A ping is frequently followed within a second by a 400 carrying one message and no tokens, and AttributeCache still stamps it with a cache_miss_reason. Taking it reported 0 of 4 following requests hitting where 2 of 4 read the ping's prefix back token for token. Read-only throughout: no Go code, no schema change, no runtime path. Account ids are pseudonymized and session ids hashed unless --raw-ids; request_content is never queried. Evidence: 14/14 tests green; 1,038 recorded pings over 2026-08-23..09-02 across 255 sessions and 15 accounts, $150.87 of ping spend, identification audit clean both ways, 91.8% of gaps inside the band a 2s sweep produces. Assisted-By: Claude Opus 5 <[email protected]> Signed-off-by: Itay Nakash <[email protected]> * fix(kvcache): create the ping-stats CSV 0600 instead of chmod'ing it 644 os.chmod(args.out, 0o644) ran unconditionally after writing the file, widening it past the creating umask even under --raw-ids, where the CSV carries real tenant_id plus per-row dollar figures. Follow the sibling kv_ttl_cost_model.py precedent: create the file 0600 via os.open with O_CREAT|O_TRUNC so there is no window where it exists world-readable. Also fix two stale line citations in the docstring against current Go (proxy/keepalive.go:908, proxy/proxy.go:1143), note that the agent column is exported verbatim regardless of --raw-ids, drop the now-dead io import, and round out test_keepalive_ping_stats.py: skipUnless guards on the three pandas-only tests so a pandas-less run reports "skipped" rather than erroring, plus tests for a 5xx ping with no usage and for a session with no pings contributing no rows. Signed-off-by: Osher-Elhadad <[email protected]> --------- Signed-off-by: Itay Nakash <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]> Co-authored-by: Osher-Elhadad <[email protected]>
The problem, in one table
Measured on the hosted service: 19,805 requests, $3,139.97, 2026-08-16 → 21.
A TTL-expired request costs 8.5x a request that hit. Against each row's own
counterfactual — the same tokens billed as a read — the penalty is 11.35x, of which
91.2% is pure re-write. The addressable population is 357 claude-cli requests / $734.75.
$584.83 — 18.6% of ALL spend — sits in misses whose idle gap was under an hour. For
scale: the entire transformation pipeline's measured net over the same window is $9.72.
The caching math, with the doc quotes it rests on
Multipliers: 5m write 1.25x base input, 1h write 2.0x, read 0.1x. Backed out of
production billing independently and confirmed to the cent — read 0.1000 at every prefix
size, write 1.250, so write/read is 12.5x.
Converting one miss recovers
(1.25 − 0.1) = 1.15xon the prefix; one ping costs0.1x.Saving : ping = 11.5 : 1, and both sides scale with the model's input rate, so the ratio
survives the whole price list.
1. The idle keep-alive (
proxy/keepalive.go)Host-level, not a component, because the expensive event happens when no request is in
flight. After a session has been idle
Xseconds the proxy re-sends its last request withmax_tokens: 1andstream: false— a pure cache read, which refreshes the entry. Those twofields sit outside the
tools→system→messageshash, so the prefix is byte-identical.The timer origin — the one decision that flips the sign
The timer is armed at REQUEST START, never at response completion (
kaEntry.startedAt,set from
serve'slastUpStart). The provider's lifetime runs from request start, so ananchor at completion silently spends the response's own duration out of the 20 s of margin X
leaves:
upstream_msis p50 8.9 s, p75 17.5 s, p90 33.4 s, so ~21% of first pings would landafter the entry had expired — and a ping onto a dead entry pays a 1.25x write, the exact
cost it exists to avoid. Simulated, that one change takes X=280 from +$164 to −$241.99
with ping cost tripling to $408.85. The number is in the code comment beside the field so
nobody "simplifies" it later.
A ping is itself a cache read, so it re-anchors the clock: the bridgeable span is
K·X + TTL, notK·X.TestMaxPingsAndPingRestartsTheClockasserts it.The gate — what makes this deployable rather than merely profitable
Shipped default:
X=280s, K=2, and a session is pinged only when it is not on its firstrequest AND its billed prefix (
cache_read + cache_write) is ≥ 20,000 tokens.9.8× fewer pings for 1.7% less money. What the gate drops is the near-free pings: cost
is bimodal (p50 $0.0004 against a p99 of $0.2275), and 45.7% of blanket pings fire on
single-request sessions with ~1k-token prefixes. 8,000 requests of real gateway load
disappear — on a path that returned 180 HTTP 429s in the same window — and almost none of
the value does.
The first-request skip is a cheap filter, not a claim that later turns miss more often:
P(next request is an addressable TTL miss) is flat — 2.24% at turn 0, 2.33% at 5, 2.47% at
20, 2.29% at 100. K=2 ships over K=3 (marginally better here, +$130.80) because they are
a tie inside the run-to-run wobble and K=2 sends 26% fewer requests. The earlier claim that the
net "peaks at K=2" did not reproduce and is withdrawn.
No per-session ping cap. It truncates exactly the long large-prefix sessions holding the
value — cap-20 drops the net to $92.34, cap-10 to $54.04. The guard that works is
keepalive_max_usd_per_ping(default $0.25), checked against a projection computed from theprefix and the model's own read rate before anything is sent.
Guards
keepalive_idle_seconds(X)keepalive_max_pings(K)keepalive_min_prefix_tokenskeepalive_max_usd_per_pingAcquireSpare, 25% reservedCONTEXT_GURU_KEEPALIVE=offNever adds or moves a breakpoint.
TestPingBodyLeavesTheHashedPrefixByteIdenticalassertsthe
cache_controlcount is unchanged and thatmodel/tools/system/messages/thinking/tool_choiceare byte-identical. A runtimeguard backs it up: a ping whose usage reports more written than read is logged at ERROR,
counted as
wrote_instead_of_read, and that session is never pinged again.Will not ping
thinking.type: enabled— it requiresmax_tokensabove a 32,000-tokenbudget, and altering thinking invalidates the message-level prefix. Exposure: 17 of 357
addressable misses, $14.29 of $732 = 2.0%.
adaptiveis 81% and unaffected.Not gated on
end_turn, and the data is whyend_turnreads like a session-end signal and is the opposite: P(gap > 300s) is 37.15%after it against 0.74% after
tool_use, and 83.7% of the recoverable dollars sitbehind it. Only 290 of 3,891 session-final requests (7.5%) end that way. Stopping there would
discard most of the value. What ships instead: K, a stop on any 4xx, and a stop on a ping that
wrote.
A bug the gate exposed in this PR's own code
Gating inside
due()left un-pingable sessions sitting in the map holding a body and acredential until memory pressure evicted them. On the replay the 512-session bound saturated
and eviction then discarded the entries about to pay — conversions fell from 153 to 69. The
gate now runs in
record, so nothing is held for a session we will not ping. That is also thebetter security posture, and it is why
pingable()is separate fromdue().Credential retention — escalated, ruled on, and hardened
On a caller-pays upstream this is the one place the service holds a caller's provider
credential beyond the life of a request. The default deployment is caller-pays
(
/etc/context-guru/upstreams.yamlnames no key), so without retention the mechanism cannotexist here, and pinging on the operator's key would bill the wrong party. The owner's ruling
was acceptable only with hardening; all seven controls are in:
time.AfterFunc((K+1)·X)≈ 14 min — a scheduled deadline, so a process with zero traffic still releases on time. A security bound must not depend on a liveness loop. The sweep's eager release is kept as the earlier of the two, not as the guarantee.zero()overwrites the bytes on every release path — next request, gate refusal, retirement, eviction, shutdown, panic. A dropped[]bytesits in the heap until a collection that may never come.crypto/randper-process key. The asymmetry decides the body: a leaked key is rotatable, a transcript is not.recordre-readstn.Cacheevery request and retires what is already held when it is off. A stale flag from when the hold began cannot extend it.requestsrow with tenant, session,ts,cost_usd,cache_read/cache_write— and unconditional: with no recorder to write one, nothing is retained. An audit control--dashboardcan switch off is not a control.keeper.forget(tenantID)on account deletion, token revocation and disablement. The deadline would get there in minutes, but a revocation the user performed deliberately should not wait on a timer./stats,/metrics,KeepAliveStats,%+vof the live entry (the panic-trace path) and the JSON log sink at debug level — for both the credential and the retained body, which holds the user's whole conversation.CONTEXT_GURU_KEEPALIVE=offnow stops retention, not merely pinging:recordretires instead of holding. A switch that kept the material while refusing to use it is the worst of both.What the masking does and does not buy — stated plainly rather than sold. A heap or core
dump, a crash report, a
/proc/<pid>/memread or astringspass over a snapshot yieldsmasked bytes rather than a working key: the accidental-capture class, which is the realistic
one. It does not stop an attacker with code execution in this process — the mask is in the
same address space. It is obfuscation at rest, not encryption. And the credential is
necessarily plaintext for the duration of the ping itself, because
net/http's header mapholds strings and a Go string cannot be overwritten; the window is one request instead of the
whole idle hold, which is the part worth closing.
Two further items from the re-review are in. The audit row is now unconditional — the choice
was between a second durable sink and refusing to hold what cannot be accounted for, and this
takes the second: three lines, and it fails in the safe direction. And revocation purges:
keeper.forget(tenantID)runs on delete, revoke and disable, because the keeper is a credentialstore
tenant.TestDeleteCascadesEveryCredentialdid not know about.A test of mine that could not have caught its own subject. Requiring an audit sink broke the
output-surface leak test, which turned out to be assigning its recorder after
New()— leavingit half-wired, so the surfaces it probed were not the ones a deployment serves and its earlier
PASS was unproven. It now uses a real in-memory recorder through
New()like the dashboard tests.The fixture churn in the test diff is that fix, not a weakening: the test got stronger.
One design change the zeroize requirement forced, and it is an improvement: the retained body
is now a keeper-owned copy rather than the slice
serveused. Overwriting a shared sliceis the kind of cleverness that produces a mystery bug in a month. The zero-copy retention was
a micro-optimisation in the wrong place, and with the gate down to ~119 tracked sessions the
copy costs nothing.
Bounded on volume too: 512 sessions / 128 MiB total / 8 MiB per body.
2. CLOSED AVENUE: selective and mixed 1-hour TTL
Do not re-attempt this.
apply/headttl.goships implemented and disabled, purely sothe negative result is verifiable rather than folklore.
Why it cannot pay, three independent ways:
(−$773.00); the benefit lands on 290 (+$754.66). Net −$18.34. An independent
counterfactual puts it at −$93.51 (+$455.96 rescued against −$549.47 of premium), worse
because the naive threshold assumes one write per session while real traffic writes nearly
every turn (
hitrows averagecache_write6,183) — the premium lands on 192.8 MTok ofwrites against 104 MTok of rescuable prefix.
indistinguishable from blanket. Structural, not a tuning failure — premium and benefit
scale with the same
cache_writeon the same requests, so a probability filter cannotflip a sign. (A dollar filter can:
tokens_before ≥ 50k→ +$48.81. Still not shipped,because of 3.)
5,386 rows with
cache_write > 1000, 3,615 match 1.25x and none match 2.0x. Bedrockannounced 1h on 2026-01-26 for the Claude 4.5 family; our spend is Opus 5, Opus 4.8,
Sonnet 5, Opus 4.6.
One received claim I have to correct, because I measured it. The blocker was believed to be
LiteLLM stripping the field (
_remove_ttl_from_cache_control, upstream #19848/#20326). Probedlive, one request each with the head labelled 1h:
ephemeral_1h_input_tokensephemeral_5m_input_tokensaws/claude-haiku-4-5aws/claude-sonnet-5Haiku honouring the tier proves the field does reach Bedrock. What refuses is model
coverage. Same conclusion, correct mechanism — and it matters, because the fix if this ever
becomes worth having is a model allowlist, not a LiteLLM patch.
Mixed TTL (1h head + 5m tail) is implemented for the same reason and off for the same one. It
needs no extra breakpoint slot — it re-labels existing marks, asserted by
TestHeadTTLAddsNoBreakpoint— and 1h-before-5m holds by construction, asserted byTestHeadTTLUpgradesTheHeadAndNotTheTail. Projected net on today's spend mix: $0.A pricing defect that probe exposed, and this PR fixes
The Haiku response was billed at the 1h tier and the dashboard priced it at the 5-minute rate:
$0.0348 recorded against a real $0.0554.
Usage.CacheWrite1hand acache_write_1hcolumnnow carry the provider's own per-tier breakdown, and
Event.Priceadds the2.0x input − 5m write ratepremium on exactly those tokens. A cost wrong in the flatteringdirection argues for spending.
3. CLOSED AVENUE: parallel fan-out on
cold_start— measured, not happeningThe idea: "a cache entry becomes readable only after the first response begins streaming", so
concurrent requests sharing a prefix can all miss and all pay 1.25x.
cold_startis $253.82(8.1% of spend), and Claude Code fans out subagents, so it was worth checking.
cold_startrowscold_startin the same session within 10 scold_startin the same tenant within 10 scache_writewithin 5%)The same-tenant number is a mirage.
litellmis 886 of the 1,626 rows ($112.64) with meancache_write0 — one-shot calls with no cacheable prefix at all, near-simultaneous becausethey are a batch, with nothing to race for. Same for
python-requests(276, write 0) andanthropic(240, write 57). Onlyclaude-clicold starts carry real prefixes (219 rows, meancache_write108,640), and 1,494 of 1,626 cold starts are the session's genuine first request.Serialising 1,260 requests behind a first-token wait to recover $0.66 is not worth building.
Skipped.
4.
cachesplit: nothing was broken, and the reporting now says soacted: 0besidemutated: 755is correct by design — the split moves tokens betweenbilling tiers rather than removing them.
/statsnow publishes a per-componentverdict:acted|moved|skipped|idle.The credit is not raised. Recomputing the shipped gates over the snapshot:
cache_read ≥ stablecache_write < stable32 of 35 split sessions carry exactly ONE distinct tail hash for the whole session — Claude
Code captures its environment snapshot once per session, so mid-session there is nothing to
protect. Pricing the 1,729 "uncredited hits carrying a tail hash" at $18.79 would credit the
provider's cache to us. The honest number is ~$0.04 and it stays.
5. Doc bug fixed: the 1h break-even is 65.2%, not 83.3%
cacheinject.goanddocs/components/cacheinject.mdboth stated(2.0−1.25)/(1−0.1) = 83.3%. That denominator assumes a lapsed entry re-bills at the 1.0xfresh rate. It does not: those tokens still carry
cache_control, so the provider creates anew entry at 1.25x. Production
ttl_expiryrows say so —cache_writeaverages 178,793against
fresh_input1,712. Correct denominator(1.25−0.1) = 1.15, giving 65.2%.Conclusion unchanged, the documented number was wrong by 18 points.
6. A closed dead end, restated: cross-session prefix repair
Not rebuilt. Refuted live — the billing-header block is exempt from this gateway's cache
hash, so there was nothing to repair, and v1 measured a +5.5% cost regression.
Review response (
REVIEW-86.md, againsteba59a2)Four of the ten findings were already fixed in commits 2–3 while the review was in flight; six
needed work. Every one is addressed.
1. Ping rows credited themselves with
cache_saved_usd— the serious one.Event.Pricecomputed it from
CacheReadunconditionally, so each 48k ping booked ~$0.13 of phantomprovider-cache saving against $0.0073 of real cost. On a figure PR #83 puts on the page, at
production ping volumes, that is order $1,000 of fabricated savings. One guard in the shared
function, where all callers route through —
if !e.KeepAlive. The counterfactual is the tell:without the keep-alive that request does not exist, so there is nothing for it to have saved
against.
TestPingsDoNotCreditProviderCacheSavingsalso asserts the ping's own cost survivesthe guard and that an ordinary hit keeps its diagnostic.
On the three aggregates:
COUNT(*),SUM(cache_read)andAVG(upstream_ms)all live in theOverview query, which routes through
Filter.where()— so the one-line exclusion reaches allthree.
dash/api.gobuilds a singleFilterand is covered by the same line. Nothing needed aper-caller patch.
2. Kill switch stopped pinging, not retention. Fixed in commit 3:
recordcallsretirewhen
keepAliveDisabled(). Test asserts nothing is held with the switch set.3.
AcquireSparecharged the rate window for refused pings. Three real bugs, all fixed.The concurrency slot is now taken first and the rate counter incremented only once the ping
is certain to be sent, with
release()returning the slot if the rate check then refuses.reserved()now floors at 0, not 1 — a floor of 1 let a ping take the only slot atConcurrent: 1, which is the exact outcome the doc comment forbids; a tenant with a budget ofone has no slack and is correctly never pinged. And the headroom test now happens under the
tenant's lock together with the take, so two pings cannot both read "there is room". The
reviewer's own
TestReviewSkippedPingConsumesRPMnow passes (before=1 after=1over tenrefused pings) and
TestReviewReservationFloorAtOneskips with "ping refused the only slot".4. The consent copy promised an audit trail that did not render. Both halves now exist: a
keep-alivepill on the Requests tab in place of the cache-outcome pill (a one-token requestthe user did not make, unlabelled, is worse than not showing it), and an Overview tile carrying
the net with
pings · ping cost · misses avoided · savingas its subtitle — hidden untilthe mechanism has done something, so an unopted deployment shows no row of zeroes. The ledger
bars were already rendering generically from
delta_usd.5.
docs/hosted.mdstated the invariant this falsifies. Updated. The reviewer's correctionis taken:
authHeadersare forwarded, which is the caller-pays design, and only our ownminted token is scrubbed — so the sentence that changed is "and stores none: the key is read off
the request and dropped". It now carries that clause plus a scoped exception naming the opt-in,
the bound, and the audit trail, and says plainly that nothing is retained for an account that
has not enabled it.
6. The retained BODY needed its own disclosure. It cannot be reduced — the prefix hash
covers the whole
tools→system→messagessequence, so a ping that trimmed the body wouldmiss the cache and cost 12.5x instead of saving 11.5x, which is the mechanism inverted. So it is
disclosed, in the consent copy and the docs, and explicitly distinguished from the
transcript-storage consent: that one governs writing content to disk where a manager can
read it; this is memory only, masked, overwritten on release, never persisted, gone in ~14
minutes. The reviewer is right that enabling a spending feature is not consent to retaining
conversation content, so the copy now says both.
7. Stale numbers in my own code.
keepalive.goandconfig.goquoted +$170.08 / 9,234 /182 as the shipped result; the shipped function gives +$125.08 / 912 / 148. Corrected, and the
comments now say they come from the replay so a policy change moves them too. "Net peaks at
K=2" did not reproduce and is withdrawn: K=2 gives +$125.08 against K=3's +$130.80 — a tie
inside the run-to-run wobble. K=2 ships for the ping-volume reason (26% fewer requests on a path
that returned 180 HTTP 429s), not a dollar one.
8. Three comments repeated the refuted "LiteLLM strips ttl". All three corrected to Bedrock
model coverage.
9.
cache_write_1hhad no read path. Row-level scan landed in commit 2; the Overview nowalso sums it, so the feature's own verification is a glance rather than hand-written SQL.
10.
upgradeHeadTTL's size gate can flip mid-session. Noted with aponytail:commentnaming the upgrade path (latch per session). Harmless while off, and a differing
ttldoes notchange the prefix hash, so neither direction costs a miss.
The 512-session bound — confirmed, and the gate is what fixes it
The reviewer's instrumentation was right. Measured with
peak livenow reported by the replay:No need to raise the bound. Money was identical to the cent across runs either way, as the
reviewer found.
Process and provenance
-count=1from here on. The reviewer caught a cachedok .../proxyfor a package that nolonger compiled, because
MaxUSDPerSessionhad been replaced mid-review. Fair, and thegreen-suite claim below is
-count=1.max_tokens: 0where committed
record1sets 1. The benign reading is the right one and the evidence supportsit: the ping returned
output_tokens: 1withstop_reason: max_tokens, which is only possibleif
max_tokens: 1was on the wire. What the binary lacked was the dashboard column for it —ev.MaxTokens = 1was added after that run. The billed tiers, which are the claim, areunaffected.
max_tokens: 1justification was wrong and is rewritten.0is rejected alongsidestreaming and thinking, and this ping excludes both — so that was not the reason. The real one
is compatibility for one output token costing $0.0000076 against a $0.0073 read: a tenth of a
percent, not worth a negotiation risk on a request that must not fail surprisingly.
MaxUSDPerSessionwas per-idle-span while documented per-session, and its test stagede.spentby hand against a keeper with noPrices, so the accumulation path never ran. It isgone;
TestPerPingCostGuarddrives the realprojectedPingUSDpath through an injectedPricerand asserts both the refusal and that the same traffic under a larger budget ISpinged.
Evidence
Live end-to-end, real gateway, nothing simulated
Two arms, byte-identical bodies, a real 48k-token Claude Code
system+toolsprefix onaws/claude-sonnet-5, 330 s of idle across the 300 s lifetime. Per-arm nonce in the firstcache_control-marked system block — the cache is content-keyed, so without it the second armfree-rides on the first arm's write. (Not block 0: this gateway exempts its billing-header
block from the hash.)
Keep-alive OFF — the failure this exists to fix, reproduced:
Keep-alive ON — same script, same gap:
ttl_expiry, 48,335 writtenhit, 48,211 readThe ping reported
cache_read = 48,211andcache_write = 0— verified as the full prefixand not a partial refresh, which would have looked like a win and cost money. Live miss/hit
ratio 10.87x against 11.35x from production.
/statsduring the run:{"live_sessions":1,"pings":1,"skipped":0,"failed":0,"wrote_instead_of_read":0,"spend_usd":0.007339}.Harness
/tmp/cg-orch/ka-e2e.py, raw rows/tmp/cg-orch/runs/ka1/result.json. Credentialsread from
~/.claude/settings.jsonat call time and passed through the proxy's environmentonly. (A purpose-built 2-turn driver rather than the shared
drive.py, because the ping hasto fire between two turns against this branch's own binary and
cache:block. It produces thesame before/after comparison the shared harness would.)
Projection from the SHIPPED decision function
TestKeepAliveOnProductionSnapshotreplays the snapshot through the realkeeper— realdue(), realpingable(), real K, real cost guard, real thinking gate, realrecord/arrivelifecycle — and prices every ping through the same
Pricerthe request path uses. Not aseparate model.
Shipped policy: +$125.08 over 4.47 days = ~$28/day at current volume and mix. Rescue value
is the identity
(1.25 − 0.10) × in_rate × cache_write, never a share ofcost_usd.Do not annualise this. It is 13 tenants over 4.5 days and it scales with the opus share and
with
ttl_expiryfrequency. Both sides are priced fromprices.yamlat current list ratesand never netted against historical
cost_usd: a price cutover on 2026-08-19 01:00 UTC droppedthe input rate by exactly 1.3158 (opus $5.00 → $3.80) mid-window, so 7,269 rows carry the older
dearer rate.
Not modelled, and stated because a projection that hides its assumptions is worth nothing:
AcquireSparereads the wall clock, which a synthetic clock cannot drive,so ping counts are an upper bound.
refresh the same entry for free, so some conversions credited here would have happened
anyway. Same confound as the live credit, same direction.
trajectory; the prefix still grows and still expires, which is what is under test.
The honest downside
The policy is a very small tax on almost every session it touches, funding a large rebate for
a few dozen. The gate does not make the tax rarer per session touched — it makes it fall on
119 sessions instead of 3,809, leaving 3,690 untouched entirely. That is the fairness argument,
independent of the dollars: a session never pinged cannot lose.
Given this shape the opt-in default and the per-account ledger are not optional. The Settings
copy says so in the user's own terms: "34 of 119 pinged sessions came out ahead and the worst
single session paid $2.42 for nothing. Watch your own ledger and switch it off if you are not
one of the winners."
Verification after rollout
Confirm against
cache_miss_reasonand the tiers, not a modelled delta: ping rows mustshow
cache_read > 0andcache_write == 0before a dollar is credited. This is thecross-session-prefix-repair lesson — that idea also looked right on paper and was a +5.5%
regression live.
wrote_instead_of_readin/statsis the alarm.Schema and shared files
schemaVersionis unchanged at 6. Production holds 19,805 requests / 64 MB at/var/lib/context-guru/cg.db; a version bump would rename that aside on first restart. Allfour columns go in
additiveColumns, applied idempotently byaddColumns():keepaliveINTEGER NOT NULL DEFAULT 0keepalive_pingsINTEGER NOT NULL DEFAULT 0keepalive_saved_usdREAL NOT NULL DEFAULT 0cache_write_1hINTEGER NOT NULL DEFAULT 0A ping is a
requestsrow with a flag, not its own table, because it is a real upstreamrequest with real usage and real cost, and every existing per-request facility (pricing, tenant
scoping, retention, purge) already applies to it. What that costs is one risk, handled in one
place:
Filter.where()now excludeskeepalive = 1by default, so the overview, buckets,per-model groups, facets, session list and read-value queries are all agent-only at once. Two
callers opt back in — the request LIST (the audit trail; each row carries
keepaliveso the UIcan badge it) and the keep-alive ledger itself. Spend figures deliberately still include pings:
the money was really spent on the caller's key.
TestPingsAreVisibleAsRowsAndExcludedFromAggregatespins both halves.Shared files touched, for merge sequencing:
apply/apply.go(+24),apply/opts.go(+10) — purely additive: twoOptsfields, twoTracefields, one call site beside the existingtoolschema/toolfilterrewrites.Ctx.ColdCache,Ctx.IdleMs,cacheIsColdandcacheTTLare untouched (zero changedlines matching them). One interaction to note: with
head_ttl_1hon,bodyAsksExtendedTTLbecomes true, socacheTTLreturns 1h andcacheIsColdgrows morepermissive. That is correct when the tier is granted and a safe over-estimate when it is not,
and it cannot affect anything today because the flag is off. Documented at the field.
modes.Tracker. Deliberate: the trackeranswers "is the cache certainly gone" (conservative, +1 min margin, false when unknown),
which is the opposite question from "is the cache about to go" — and the keeper additionally
has to hold a body and a credential, which the tracker must not.
dash/schema.go,dash/event.go,dash/store.go,dash/query.go,dash/overview.go—flag to the dashboard workstream if they also add
additiveColumnsentries.Tests and lint
New coverage: the ping is a cache READ with a byte-identical prefix and an unchanged breakpoint
count; a ping that wrote stops the session; timing from request start; X, K, and a ping
re-anchoring the clock; the gate (first request skipped, prefix floor); the per-ping cost
guard; a ping never takes the last concurrency slot; fail-open with no in-sweep retry; 4xx
stops the session;
thinking: enabledrefused whileadaptiveworks; a disabled policy and arefused request hold nothing;
arrivecancels and reports; credential rules in bothdirections; memory bounds; kill switch; a real HTTP round trip; head-TTL adds no breakpoint and
never invents one, size gate, explicit-breakpoint providers only, idempotent, fails open on
four malformed shapes; the keep-alive credit and all five of its gates, the refresh cap, the
11.5:1 ratio, the 1h tier priced at its own rate; the per-TTL usage breakdown from both
live fixtures in JSON and SSE; pings visible as rows and excluded from aggregates; the
cache:block withidle_seconds ≥ 300refused at load;verdictdistinguishingmovedfrom
skipped.The seven hardening controls each have their own subtest: the credential is held masked and
never plaintext while still unmasking to the caller's own value; a server-held key retains
nothing; release zeroizes the actual buffers (asserted on handles taken before release, so
it is about the bytes and not the pointer); the hard deadline fires with no request, no
sweep and nothing else running; withdrawn consent retires an existing hold; the kill switch
holds nothing;
Stopdrops everything. Plus the output-surface test above, which fails if thedebug log carries no keep-alive line — so it cannot pass by never exercising the path.
Nothing in the live deployment was changed.