Skip to content

feat(cache): keep an idle prompt cache alive, price the 1h write tier, and say what cachesplit did - #86

Merged
OsherElhadad merged 7 commits into
mainfrom
feat/cache-0821
Aug 22, 2026
Merged

OsherElhadad merged 7 commits into
mainfrom
feat/cache-0821

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Aug 22, 2026 •

Copy link
Copy Markdown
Collaborator

The problem, in one table

Measured on the hosted service: 19,805 requests, $3,139.97, 2026-08-16 → 21.

miss reason n share $ share of spend $/req
hit 16,368 82.6% 1,928.65 61.4% 0.1178
ttl_expiry 742 3.7% 741.07 23.6% 0.9987
cold_start 1,626 8.2% 253.82 8.1% 0.1561
prefix_change 292 1.5% 205.05 6.5% 0.7022
unknown 777 3.9% 11.38 0.4% 0.0146

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

By default, the cache has a 5-minute lifetime. The cache is refreshed for no
additional cost each time the cached content is used.

The lifetime is measured from the start of the request that writes or reads the cache
entry, not from the end of its response.
Time spent generating a response counts
against the lifetime.

Cache writes happen only at your breakpoint. … Because the hash is cumulative,
covering everything up to and including the breakpoint, changing any block at or before
the breakpoint produces a different hash on the next request.

Exact matching: Cache hits require 100% identical prompt segments.

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.15x on the prefix; one ping costs 0.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 X seconds the proxy re-sends its last request with
max_tokens: 1 and stream: false — a pure cache read, which refreshes the entry. Those two
fields sit outside the tools → system → messages hash, 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's lastUpStart). The provider's lifetime runs from request start, so an
anchor at completion silently spends the response's own duration out of the 20 s of margin X
leaves: upstream_ms is p50 8.9 s, p75 17.5 s, p90 33.4 s, so ~21% of first pings would land
after 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, not K·X. TestMaxPingsAndPingRestartsTheClock asserts 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 first
request AND its billed prefix (cache_read + cache_write) is ≥ 20,000 tokens.

policy pings ping cost converted saving net
X=280 K=2, gated (shipped) 912 $90.76 148 $215.84 +$125.08
X=280 K=2, blanket 8,915 $93.79 153 $221.05 +$127.26
X=280 K=1, gated 536 $53.51 96 $138.80 +$85.28
X=280 K=3, gated 1,226 $121.33 174 $252.13 +$130.80
X=240 K=2, gated 1,012 $102.19 134 $197.03 +$94.85
X=280 K=12, gated 3,307 $311.78 253 $370.12 +$58.35

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 the
prefix and the model's own read rate before anything is sent.

Guards

control default why
keepalive_idle_seconds (X) 280 refused at load if ≥ 300 — a ping past the lifetime writes
keepalive_max_pings (K) 2 net peaks at 2–3; a session that has ended is undetectable
keepalive_min_prefix_tokens 20,000 the gate above
keepalive_max_usd_per_ping $0.25 bounds the outlier ping, never the productive session
tenant limits AcquireSpare, 25% reserved a ping uses only slack and is skipped, never queued
CONTEXT_GURU_KEEPALIVE=off — operator kill switch; an env var so it works when the control plane is what is broken

Never adds or moves a breakpoint. TestPingBodyLeavesTheHashedPrefixByteIdentical asserts
the cache_control count is unchanged and that
model/tools/system/messages/thinking/tool_choice are byte-identical. A runtime
guard 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 requires max_tokens above a 32,000-token
budget, and altering thinking invalidates the message-level prefix. Exposure: 17 of 357
addressable misses, $14.29 of $732 = 2.0%. adaptive is 81% and unaffected.

Not gated on end_turn, and the data is why

end_turn reads 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 sit
behind 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 a
credential 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 the
better security posture, and it is why pingable() is separate from due().

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.yaml names no key), so without retention the mechanism cannot
exist 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:

control implementation
Hard deadline 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.
Zeroized zero() overwrites the bytes on every release path — next request, gate refusal, retirement, eviction, shutdown, panic. A dropped []byte sits in the heap until a collection that may never come.
Masked at rest the credential and the retained body, XOR under a crypto/rand per-process key. The asymmetry decides the body: a leaked key is rotatable, a transcript is not.
Consent per request record re-reads tn.Cache every request and retires what is already held when it is off. A stale flag from when the hold began cannot extend it.
Audit row per ping a durable requests row with tenant, session, ts, cost_usd, cache_read/cache_write — and unconditional: with no recorder to write one, nothing is retained. An audit control --dashboard can switch off is not a control.
Purged on revocation 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.
No output surface asserted against /stats, /metrics, KeepAliveStats, %+v of 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.
Kill switch CONTEXT_GURU_KEEPALIVE=off now stops retention, not merely pinging: record retires 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>/mem read or a strings pass over a snapshot yields
masked 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 map
holds 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 credential
store tenant.TestDeleteCascadesEveryCredential did 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() — leaving
it 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 serve used. 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 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.go ships implemented and disabled, purely so
the negative result is verifiable rather than folklore.

Why it cannot pay, three independent ways:

  1. Blanket 1h loses money. The 2.0x premium falls on all 14,499 cache-creating requests
    (−$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 (hit rows average cache_write 6,183) — the premium lands on 192.8 MTok of
    writes against 104 MTok of rescuable prefix.
  2. A predictor cannot rescue it. Gated on the best available signal: −$18.32,
    indistinguishable from blanket. Structural, not a tuning failure — premium and benefit
    scale with the same cache_write on the same requests, so a probability filter cannot
    flip a sign. (A dollar filter can: tokens_before ≥ 50k → +$48.81. Still not shipped,
    because of 3.)
  3. The tier does not arrive on the models we run. Zero 1h writes in 19,805 requests: of
    5,386 rows with cache_write > 1000, 3,615 match 1.25x and none match 2.0x. Bedrock
    announced 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). Probed
live, one request each with the head labelled 1h:

model ephemeral_1h_input_tokens ephemeral_5m_input_tokens verdict
aws/claude-haiku-4-5 36,251 323 1h GRANTED
aws/claude-sonnet-5 0 48,212 silently downgraded

Haiku 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 by
TestHeadTTLUpgradesTheHeadAndNotTheTail. 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.CacheWrite1h and a cache_write_1h column
now carry the provider's own per-tier breakdown, and Event.Price adds the
2.0x input − 5m write rate premium on exactly those tokens. A cost wrong in the flattering
direction argues for spending.

3. CLOSED AVENUE: parallel fan-out on cold_start — measured, not happening

The 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_start is $253.82
(8.1% of spend), and Claude Code fans out subagents, so it was worth checking.

test on the 1,626 cold_start rows n $
another cold_start in the same session within 10 s 34 9.53
another cold_start in the same tenant within 10 s 1,260 134.84
…and plausibly sharing a prefix (same model, cache_write within 5%) 2 0.66

The same-tenant number is a mirage. litellm is 886 of the 1,626 rows ($112.64) with mean
cache_write 0 — one-shot calls with no cacheable prefix at all, near-simultaneous because
they are a batch, with nothing to race for. Same for python-requests (276, write 0) and
anthropic (240, write 57). Only claude-cli cold starts carry real prefixes (219 rows, mean
cache_write 108,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 so

acted: 0 beside mutated: 755 is correct by design — the split moves tokens between
billing tiers rather than removing them. /stats now publishes a per-component verdict:
acted | moved | skipped | idle.

The credit is not raised. Recomputing the shipped gates over the snapshot:

gate applied cumulatively rows surviving
the split ran 2,039
+ a tail hash recorded 1,938
+ cache_read ≥ stable 1,733
+ cache_write < stable 1,332
+ the tail MOVED since the session's previous request 1
credited in the DB today 4 rows / $0.0381

32 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.go and docs/components/cacheinject.md both stated
(2.0−1.25)/(1−0.1) = 83.3%. That denominator assumes a lapsed entry re-bills at the 1.0x
fresh rate. It does not: those tokens still carry cache_control, so the provider creates a
new entry at 1.25x. Production ttl_expiry rows say so — cache_write averages 178,793
against fresh_input 1,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, against eba59a2)

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.Price
computed it from CacheRead unconditionally, so each 48k ping booked ~$0.13 of phantom
provider-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. TestPingsDoNotCreditProviderCacheSavings also asserts the ping's own cost survives
the guard and that an ordinary hit keeps its diagnostic.

On the three aggregates: COUNT(*), SUM(cache_read) and AVG(upstream_ms) all live in the
Overview query, which routes through Filter.where() — so the one-line exclusion reaches all
three. dash/api.go builds a single Filter and is covered by the same line. Nothing needed a
per-caller patch.

2. Kill switch stopped pinging, not retention. Fixed in commit 3: record calls retire
when keepAliveDisabled(). Test asserts nothing is held with the switch set.

3. AcquireSpare charged 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 at
Concurrent: 1, which is the exact outcome the doc comment forbids; a tenant with a budget of
one 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 TestReviewSkippedPingConsumesRPM now passes (before=1 after=1 over ten
refused pings) and TestReviewReservationFloorAtOne skips with "ping refused the only slot".

4. The consent copy promised an audit trail that did not render. Both halves now exist: a
keep-alive pill on the Requests tab in place of the cache-outcome pill (a one-token request
the user did not make, unlabelled, is worse than not showing it), and an Overview tile carrying
the net with pings · ping cost · misses avoided · saving as its subtitle — hidden until
the 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.md stated the invariant this falsifies. Updated. The reviewer's correction
is taken: authHeaders are forwarded, which is the caller-pays design, and only our own
minted 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 → messages sequence, so a ping that trimmed the body would
miss 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.go and config.go quoted +$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_1h had no read path. Row-level scan landed in commit 2; the Overview now
also 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 a ponytail: comment
naming the upgrade path (latch per session). Harmless while off, and a differing ttl does not
change 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 live now reported by the replay:

policy peak live sessions bound
blanket X=280 K=2 512 512 — saturated, and the source of the 8,961–8,969 ping wobble
gated (shipped) 11 512 — two orders of margin

No need to raise the bound. Money was identical to the cent across runs either way, as the
reviewer found.

Process and provenance

  • -count=1 from here on. The reviewer caught a cached ok .../proxy for a package that no
    longer compiled, because MaxUSDPerSession had been replaced mid-review. Fair, and the
    green-suite claim below is -count=1.
  • The e2e binary (00:39) predates the commit (01:02), and the ping row shows max_tokens: 0
    where committed record1 sets 1. The benign reading is the right one and the evidence supports
    it: the ping returned output_tokens: 1 with stop_reason: max_tokens, which is only possible
    if max_tokens: 1 was on the wire. What the binary lacked was the dashboard column for it —
    ev.MaxTokens = 1 was added after that run. The billed tiers, which are the claim, are
    unaffected.
  • My max_tokens: 1 justification was wrong and is rewritten. 0 is rejected alongside
    streaming 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.
  • MaxUSDPerSession was per-idle-span while documented per-session, and its test staged
    e.spent by hand against a keeper with no Prices, so the accumulation path never ran. It is
    gone; TestPerPingCostGuard drives the real projectedPingUSD path through an injected
    Pricer and asserts both the refusal and that the same traffic under a larger budget IS
    pinged.

Evidence

Live end-to-end, real gateway, nothing simulated

Two arms, byte-identical bodies, a real 48k-token Claude Code system + tools prefix on
aws/claude-sonnet-5, 330 s of idle across the 300 s lifetime. Per-arm nonce in the first
cache_control-marked system block — the cache is content-keyed, so without it the second arm
free-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:

turn 1               cold_start   read=      0  write= 48211  out=111  $0.092448
turn 2 (after 330s)  ttl_expiry   read=      0  write= 48335  out=128  $0.092812

Keep-alive ON — same script, same gap:

turn 1               cold_start   read=      0  write= 48211  out=127  $0.092569
PING at +280s        —            read=  48211  write=     0  out=  1  $0.007339   max_tokens=1
turn 2 (after 330s)  hit          read=  48211  write=   125  out=128  $0.008541
                                  keepalive_pings=1  keepalive_saved_usd=$0.084273
OFF ON
turn 2 ttl_expiry, 48,335 written hit, 48,211 read
turn 2 cost $0.092812 $0.008541
pings — $0.007339
turn-2 cost avoided, pings included — +$0.076932

The ping reported cache_read = 48,211 and cache_write = 0 — verified as the full prefix
and 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. /stats during 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. Credentials
read from ~/.claude/settings.json at call time and passed through the proxy's environment
only. (A purpose-built 2-turn driver rather than the shared drive.py, because the ping has
to fire between two turns against this branch's own binary and cache: block. It produces the
same before/after comparison the shared harness would.)

Projection from the SHIPPED decision function

TestKeepAliveOnProductionSnapshot replays the snapshot through the real keeper — real
due(), real pingable(), real K, real cost guard, real thinking gate, real record/arrive
lifecycle — and prices every ping through the same Pricer the request path uses. Not a
separate model.

CG_SNAPSHOT_DB=/tmp/cgwork/cg-snap.db MODEL_PRICES=/etc/context-guru/prices.yaml \
  CGO_ENABLED=1 go test -run TestKeepAliveOnProductionSnapshot -v ./proxy/

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 of cost_usd.

Do not annualise this. It is 13 tenants over 4.5 days and it scales with the opus share and
with ttl_expiry frequency. Both sides are priced from prices.yaml at current list rates
and never netted against historical cost_usd: a price cutover on 2026-08-19 01:00 UTC dropped
the 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:

  • Tenant limits. AcquireSpare reads the wall clock, which a synthetic clock cannot drive,
    so ping counts are an upper bound.
  • The provider's content-keyed cache. Another session sending an identical prefix would
    refresh the same entry for free, so some conversions credited here would have happened
    anyway. Same confound as the live credit, same direction.
  • Mode-A transcript growth. The live arms grow by scripted turns, not a full agent
    trajectory; the prefix still grows and still expires, which is what is under test.

The honest downside

policy sessions touched losing money worst session total losses winners
blanket X=280 K=2 3,809 3,773 (99.1%) −$0.95 −$13.10 36
gated (recommended) 119 85 (71.4%) −$2.42 −$13.59 34

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_reason and the tiers, not a modelled delta: ping rows must
show cache_read > 0 and cache_write == 0 before a dollar is credited. This is the
cross-session-prefix-repair lesson — that idea also looked right on paper and was a +5.5%
regression live. wrote_instead_of_read in /stats is the alarm.


Schema and shared files

schemaVersion is 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. All
four columns go in additiveColumns, applied idempotently by addColumns():

column type historical rows read
keepalive INTEGER NOT NULL DEFAULT 0 0 — honest: no pings were sent
keepalive_pings INTEGER NOT NULL DEFAULT 0 0 — same
keepalive_saved_usd REAL NOT NULL DEFAULT 0 0 — same
cache_write_1h INTEGER NOT NULL DEFAULT 0 0 — and true: zero 1h writes exist

A ping is a requests row with a flag, not its own table, because it is a real upstream
request 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 excludes keepalive = 1 by 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 keepalive so the UI
can badge it) and the keep-alive ledger itself. Spend figures deliberately still include pings:
the money was really spent on the caller's key.
TestPingsAreVisibleAsRowsAndExcludedFromAggregates pins both halves.

Shared files touched, for merge sequencing:

  • apply/apply.go (+24), apply/opts.go (+10) — purely additive: two Opts fields, two
    Trace fields, one call site beside the existing toolschema/toolfilter rewrites.
    Ctx.ColdCache, Ctx.IdleMs, cacheIsCold and cacheTTL are untouched (zero changed
    lines matching them). One interaction to note: with head_ttl_1h on,
    bodyAsksExtendedTTL becomes true, so cacheTTL returns 1h and cacheIsCold grows more
    permissive. 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.
  • The keep-alive uses its own idle tracking, not modes.Tracker. Deliberate: the tracker
    answers "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 additiveColumns entries.

Tests and lint

$ gofmt -l .
(no output)

$ CGO_ENABLED=1 go vet ./...
(no output)

$ CGO_ENABLED=1 go test -race ./...
ok  	all 25 packages

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: enabled refused while adaptive works; a disabled policy and a
refused request hold nothing; arrive cancels and reports; credential rules in both
directions; 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 with idle_seconds ≥ 300 refused at load; verdict distinguishing moved
from 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; Stop drops everything. Plus the output-surface test above, which fails if the
debug log carries no keep-alive line — so it cannot pass by never exercising the path.

Nothing in the live deployment was changed.

…, 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 OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer verdict: CHANGES-REQUIRED. Posted as a comment review because GitHub refuses REQUEST_CHANGES on 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

  1. The kill switch does not stop credential retention, and with the sweep dead nothing enforces the (K+1)·X bound 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.
  2. The recommended gate is missing. Through your own harness: turn>=1 AND prefix>=20k sends 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 (measured peak live sessions 512).
  3. AcquireSpare charges 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.
  4. MaxUSDPerSession is 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-48 and the K-curve in config/config.go as 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.

Comment thread proxy/keepalive.go
if k == nil {
return
}
if keepAliveDisabled() {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread proxy/keepalive.go
//
// 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,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. 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.
  2. 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.
  3. 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.

Comment thread proxy/limits.go
// event would make a healthy account look throttled on its own dashboard.
return func() {}, errNoSpare
}
t.count++

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread proxy/keepalive.go Outdated
// 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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread proxy/keepalive.go
// 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))

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread dash/ui/app.js
+ '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 '

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread config/config.go Outdated
//
// 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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread apply/headttl.go
if !explicitBreakpointProvider(provider) {
return body, false, 0 // no explicit breakpoints, so no TTL to state
}
if len(body)/4 < minTokens {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread dash/event.go
// 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 {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review at 11ce67d — verdict still CHANGES-REQUIRED

Posted as a comment review because GitHub refuses REQUEST_CHANGES on 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 = 0 in Filter.where(), with WithKeepAlive opted back in for the list and the ledger, and money deliberately retained in TenantSpend and 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

  • AcquireSpare rate-budget leak — unchanged; my test still fails (10 refused pings consume 10 of 100 req/min). The gate makes it 10× rarer, not fixed.
  • CacheSavedUSD still 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.

Comment thread proxy/keepalive.go
if k == nil {
return
}
if keepAliveDisabled() {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread proxy/keepalive.go

// 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() {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread proxy/keepalive.go
if status < 200 || status >= 300 {
return
}
pol := tn.Cache

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. It is still the stored account flag, not a per-request echo.
  2. Nothing retires what is already held. The entry keeps its record-time e.pol snapshot, and both due() (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.

Comment thread proxy/keepalive.go
break
}
}
if k.h.rec != nil {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread proxy/keepalive.go
// 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) &&

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. 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.
  2. 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.

Comment thread dash/event.go Outdated
@@ -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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread dash/ui/app.js
+ '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 '

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread proxy/limits.go
return func() {}, errNoSpare
}
t.count++
t.mu.Unlock()

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Correction: compliance re-checked at eb4bfaf — 6 of 7 met

eb4bfaf feat(cache): harden keep-alive credential retention landed while my previous review was being posted. The 0-of-7 table in that review is stale — please read this instead. Re-verified on a clean extraction of eb4bfaf: gofmt -l . empty, go vet ./... clean, CGO_ENABLED=1 go test -race -count=1 ./... → 25 packages ok, no races, exit 0.

# 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]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Final verification at fcfe962 — CHANGES-REQUIRED (two items, both small)

Branch confirmed frozen and clean. Verified on a clean extraction of fcfe962, -count=1 throughout: gofmt -l . empty, go vet ./... clean, CGO_ENABLED=1 go test -race -count=1 ./... → 25 packages ok, no races, exit 0 (and re-run for proxy/dash/config/apply with my own review arms removed, so that is the project's own suite).

Eight of the ten items check out. Two do not, and one of those has become worse than it was because the docs now assert it.

Still open

1. Requirement 5 — the audit row is still conditional, and the docs now claim it is not. proxy/keepalive.go:820 is unchanged: if k.h.rec != nil { k.h.rec.Record(ev) }. There is no compensating guard — record() has no h.rec == nil check, so with --dashboard off the keeper still retains credentials and still pings, and writes no audit row at all.

Meanwhile docs/how-to/cache-keepalive.md now states, in the seven-controls table: "Audit row per ping | every use is a durable requests row: tenant, session, timestamp, cost, and whether it read or wrote." That is true only when the dashboard is on. A security doc asserting a control the code makes optional is worse than the gap alone.

Either is a small fix — refuse to retain when there is nowhere to record (if k.h.rec == nil { return } in record, alongside the kill-switch check already at L464), or give the keeper a minimal always-on sink. The first is two lines and matches the posture the rest of this commit takes.

2. The purge path does not exist. grep 'func (k \*keeper) forget' → nothing; grep '\.forget(' → nothing. No route calls it, and TestDeleteCascadesEveryCredential is unextended.

The hook point is already sitting there: proxy/control.go:1926 calls h.opts.Tenants.Forget(target.ID) in ctlDeleteTenant, with the comment "nothing can authenticate as them now, so it is dead weight keyed by a live id" — which is exactly the argument for dropping the keeper's entry too. Checking all three routes as asked:

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]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Finding → commit map

Findings and fixes interleaved across five commits, so here is which commit closed what. Review verdicts were against eba59a2 and eb4bfaf; the branch is at d4bc4e6.

finding closed in
Ping rows credit cache_saved_usd (~$1,000 fabricated) fcfe962
AcquireSpare charges the rate window for refused pings fcfe962
reserved(1,·)=1 lets a ping take the only slot fcfe962
AcquireSpare headroom check races pings against each other fcfe962
Consent copy promises audit surfaces that do not render fcfe962
docs/hosted.md states the invariant this falsifies fcfe962
Retained body needs its own disclosure fcfe962
Stale +$170.08 / 9,234 / 182 in code comments fcfe962
"Net peaks at K=2" withdrawn (K=3 ties) fcfe962
Three comments repeat the refuted "LiteLLM strips ttl" fcfe962
cache_write_1h has no read path fcfe962 (row scan landed 11ce67d)
upgradeHeadTTL size gate flips mid-session fcfe962 (noted)
Requirement 5: audit row optional under --dashboard d4bc4e6
Purge path on delete / revoke / disable d4bc4e6
Retained body plaintext while credential is masked d4bc4e6
Stale "39 of 9,234" in dash/event.go d4bc4e6

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 (xorMask on the owned copy at keepalive.go:538, unmasked per-ping copy at :713, zeroized by fire), so the docs sentence became true rather than removed. TestRetainedBodyIsMaskedAtRest asserts both that the hold has no plaintext transcript and that the bytes on the wire are unchanged — the second is the load-bearing half, because a ping sending altered bytes writes a new entry at 12.5x instead of refreshing one at 0.1x.

2. The third purge route is a deliberate substitution, not a missed one. The finding named ctlRevokeSession; this purges ctlDeleteTenant, ctlRevokeToken and ctlPatchTenant instead. Revoking a browser session does not revoke the agent token, so the keeper's hold is still legitimately authorised at that point, whereas ctlPatchTenant is where disable happens and disable genuinely should drop it. Weigh it — if ctlRevokeSession should purge too it is one line. The ponytail: comment on keeper.forget records the fourth-path residual.

3. Requirement 5 took the "refuse to retain" half of the choice, not the unconditional-writer half. record returns early when k.h.rec == nil, so a deployment without --dashboard holds neither credential nor body. Three lines instead of a parallel writer, and it fails in the safe direction.

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 New(), leaving it half-wired, so the surfaces under test were not the ones a deployment serves. It now uses a real in-memory recorder through New() like the dashboard tests.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Final verification at d4bc4e6 — APPROVE-WITH-NITS

Branch confirmed at d4bc4e6, tree clean. All three items closed, and the two I'd have accepted as "bounded" were closed properly instead. One nit found, one test-suite observation, neither blocking.

One test failure, which I chased down and it is not yours

My first full run reported FAIL dash/TestEventsDerivesItsScopeFromTheResolver — "a manager's default live feed did not carry other accounts' events" (tenant_scope_test.go:555). Reporting it because I saw it, then the evidence it is unrelated:

  • d4bc4e6's only change to dash is a comment (the stale 9,234 sweep in event.go). It cannot reach /api/events.
  • The test passes 5/5 in isolation, and 30/30 under -count=30 -cpu=1.
  • The full dash package is green run on its own (317s).

The failure came from my own concurrent snapshot run competing with a 356-second package for CPU. It is a timing-sensitive SSE test that reads whatever has been flushed — worth its own issue and a synchronisation point, not something for this PR.

1. Requirement 5 — airtight

if k.h.rec == nil { k.retire(key); return } at keepalive.go:486, and the ordering is right: it precedes the body copy (owned :=, L537) and the credential capture (pingHeaders, L543), so nothing is even read before the check. It also retires any prior hold rather than merely declining to add one.

No bypass path exists. k.live[key] = e at L573 is the only write to the map, it is inside record, and record has exactly one caller (proxy.go:1184). I checked for a second entry point rather than assuming.

The docs row now states what the code guarantees: "Unconditional: with no dashboard recorder to write it, nothing is retained at all — an audit control a flag can switch off is not a control." Accurate.

Taking refuse-to-retain over a parallel writer was the better half to pick — three lines, no second sink to keep in sync, and it fails in the safe direction.

2. Leak arms re-run on the corrected fixture — and one weakness worth closing

TestRetainedMaterialReachesNoOutputSurface passes with the recorder wired through New(). Good catch on the half-wired fixture; the earlier PASS was indeed not evidence about a deployment's surfaces.

I did not just re-run yours, because on the load-bearing claim yours is weaker than the claim. TestRetainedBodyIsMaskedAtRest asserts bytes.Contains(sent, marker) — that proves the marker survives, not that the prefix is byte-identical — and TestPingBodyLeavesTheHashedPrefixByteIdentical tests pingBody in isolation, before masking exists. A single corrupted byte anywhere else in the prefix passes both, and that byte is a write at 12.5× instead of a refresh at 0.1×.

So I wrote the missing arm: assert the wire body equals pingBody(recorded) with bytes.Equal, then compare model / tools / system / messages / thinking / tool_choice field-by-field off the bytes that went out, plus the cache_control count. It passes — the mask round trip is byte-exact.

On your specific question: yes, the assertion does read the wire bytes. fakeSender.send(j, body) receives exactly what fire hands to sendPing, which posts it unmodified — so fs.calls[0].body is post-unmasking and post-rewrite. Not a copy taken before masking.

I'd suggest folding bytes.Equal(sent, want) into TestRetainedBodyIsMaskedAtRest; it is one line and it is the assertion that actually guards the 12.5× failure.

3. The purge path — and your reading of the substitution is correct

forget is right: prefix-scoped on tenantID + "\x00", and since a tenant id cannot contain NUL there is no cross-tenant match; it zeroizes through e.clear() (body, credential, timer), drops the turn counter, and corrects k.bytes. Wired at control.go 1320, 1556, 1940.

ctlPatchTenant over ctlRevokeSession is the better choice, and for the reason you gave. ctlRevokeSession calls EndWebSessionBySID — a browser cookie session. It does not touch the agent's token, so after it the keeper's hold is still legitimately authorized by a credential that still works; purging there would drop a hold the agent is entitled to. ctlPatchTenant is where Disabled *bool lands, and it purges unconditionally on any patch rather than only on disable, with the right justification (a configuration change invalidates the held policy, and releasing a few holds early beats reasoning about which fields matter). ctlRevokeSession leaves no exposure worth closing.

The nit — and it is the interesting one. I walked all four registry() mutation sites, not just the three wired. ctlUpdateMe (PUT /api/me, control.go:1259) does not purge, and that is the route the settings-page checkbox actually uses (app.js → ctl('/api/me', {method:'PUT'}) carrying body.config.cache.keepalive). So the primary consent-withdrawal path is the one unwired route — a manager unticking the box goes through ctlUpdateMe, not ctlPatchTenant.

Bounded, not a hole: record re-reads pol every request and retires when off, and the hard deadline caps it at ~14 minutes — the same ceiling requirement 4 already accepts for a session that goes quiet, and the docs' "retires what is already held on the account's next request" stays accurate. But ctlPatchTenant's own reasoning applies identically here, and it is one line: h.keeper.forget(t.ID) after L1259.

4. Body masked, wire bytes intact

Verified above. Worth noting the earlier docs inaccuracy — the body row saying "masked" when only the credential was — is resolved by making the code match the doc rather than by editing the doc down. That is the better direction, and it closes the asymmetry I raised: a leaked key is rotatable, a leaked transcript is not.

fire zeroizing the unmasked copy on every exit path is the right shape; the masked original stays the only long-lived copy.

5. Sweep confirmed

Stale figure now reads "53 of 912 at the shipped X=280s, K=2, gated" (event.go:741) — matches my own re-derivation. Peak live re-confirmed at 11 of 512 across K=2, K=3 and prefix≥50k, so it tracks the hold window rather than the arm. My earlier note stands for the comment you are adding: the byte bound is the effective ceiling at ~130 large sessions, not 512.

Verdict

APPROVE-WITH-NITS. Nothing blocking. Two one-line suggestions if you want them: wire keeper.forget into ctlUpdateMe, and add bytes.Equal to the masking test. Neither changes behaviour under the shipped defaults.

For the record on the numbers: two independently written harnesses landed 0.7% apart on dollars and identical on session count and worst case, the live e2e credit matched its measured counterfactual to 0.002%, and every figure in the body reproduced from the shipped decision function. That is a better evidence base than most of what goes into a billing path here.

Commands

cd /home/vpcuser/projects/cg-wt/cache && git archive d4bc4e6 | tar -x -C /tmp/cg-orch/r86e-tree
cd /tmp/cg-orch/r86e-tree
gofmt -l . && go vet ./... && CGO_ENABLED=1 go test -race -count=1 ./...

# the flake, isolated and under induced load
CGO_ENABLED=1 go test -race -count=5  -run TestEventsDerivesItsScopeFromTheResolver ./dash/
CGO_ENABLED=1 go test -race -count=30 -cpu=1 -run TestEventsDerivesItsScopeFromTheResolver ./dash/
CGO_ENABLED=1 go test -race -count=1 ./dash/          # green standalone

# reviewer arms (proxy/leak_review_test.go, proxy/limits_review_test.go — my tree only, not pushed)
CGO_ENABLED=1 go test -count=1 -v -run 'TestReview|TestRetainedBodyIsMaskedAtRest|TestRetainedMaterialReachesNoOutputSurface|TestNoAuditSinkMeansNoRetention|TestForgetReleases' ./proxy/

# R5 has no bypass: one writer, one caller
grep -n 'h.rec == nil\|k.live\[' proxy/keepalive.go
grep -rn 'k.record(' proxy/*.go | grep -v _test

# all four mutation routes, not just the three wired
grep -n 'registry()\.\(Delete\|RevokeToken\|Update\)' proxy/control.go
grep -rn 'keeper.forget' proxy/*.go | grep -v _test

CG_SNAPSHOT_DB=/tmp/cgwork/cg-snap.db MODEL_PRICES=/etc/context-guru/prices.yaml \
  CGO_ENABLED=1 go test -count=1 -run TestKeepAliveOnProductionSnapshot -v ./proxy/

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Close-out at d4bc4e6 — APPROVE

The wire-bytes seam is now closed end to end. Both corrections noted, and one of them was already reflected in my d4bc4e6 pass.

The wire-bytes question, answered properly

sendPing posts strings.NewReader(string(body)) — its parameter verbatim, no mutation — so the fake-seam assertion is sound by inspection. But inspection was not the answer to give here, because neither existing test covers the full chain:

  • TestRetainedBodyIsMaskedAtRest stops at the k.send fake, so it proves what fire hands to send, not what is posted.
  • TestSendPingHitsTheUpstream starts after masking — it passes a plaintext Authorization and pingBody() output directly, so it never exercises an unmask at all.

A mask bug between those two points is invisible to both, and it is the expensive one. So I drove the whole chain: masked hold → sweep unmask → fire → real sendPing over real HTTP to an httptest.Server, with k.send deliberately not overridden.

It passes, and it cannot pass vacuously — it fatals first if the hold is not actually masked, so the unmask is genuinely exercised:

  • received body bytes.Equal to pingBody(recorded) — full byte identity, not Contains
  • model / tools / system / messages / thinking / tool_choice compared field-by-field off the received bytes
  • cache_control count unchanged on the wire
  • Authorization on the wire is the caller's own plaintext key, i.e. it unmasks correctly and only there

That is the assertion the 12.5×-vs-0.1× claim rests on, and it now holds against bytes that actually left the process. Happy to hand over the file (proxy/wire_review_test.go, ~40 lines, no new deps) — it is worth having in the suite rather than in my tree, since it is the only thing covering that seam.

Leak arms re-established on the corrected fixture

Re-run at d4bc4e6 against the recorder wired through New(): TestRetainedMaterialReachesNoOutputSurface, TestNoAuditSinkMeansNoRetention, TestForgetReleasesOneTenantsMaterial, TestRetainedBodyIsMaskedAtRest all pass, alongside my four arms. The earlier half-wired PASS is discarded; this one stands on the fully-wired path.

Independently confirmed R5 rather than reading it: with no sink, k.Stats().Live == 0 after a record that would otherwise retain.

On the two corrections

The purge table — the "no" row was from my fcfe962 pass, where keeper.forget did not exist at all, so it was accurate when written. My d4bc4e6 review already reports all three routes wired at 1320 / 1556 / 1940 and calls the substitution correct. Nothing stale reached the final verdict; no cycles lost.

The masking inversion — agreed, and I said so in the d4bc4e6 pass: resolving it by making the code match the doc is the better direction than deleting the word. Fixing the weaker side of an asymmetry beats documenting it accurately.

My one nit is better answered than I proposed

I suggested a fourth keeper.forget call in ctlUpdateMe. The ponytail: comment on forget already records the residual and names a better upgrade path — "Move it inside TenantSource.Forget if revoke and disable ever start invalidating the cached tenancy too, which would make one hook cover all of them" — which consolidates instead of adding a fourth site to remember.

And the framing there is more precise than mine: the three wired routes are the ones that revoke authority. ctlUpdateMe is a consent change, not an authority change — the hold is still authorized by a working credential, and consent is already handled by the per-request pol re-read plus the hard deadline. So it is correctly not in that set. Withdrawing the nit.

Verdict: APPROVE

Nothing open. All 16 findings closed, the three judgement calls are right, and the two places I'd have accepted a bounded compromise were closed properly instead.

Recording the evidence base, since it is unusually good for a billing path: two independently written harnesses 0.7% apart on dollars and identical on session count and worst case; the live e2e credit matching its measured counterfactual to 0.002%; every body figure reproducible from the shipped decision function; and the load-bearing cache-read claim now verified on bytes that left the process. The --dashboard-off refusal, the record-time gate and the body masking each fail in the safe direction.

One unrelated item for a separate issue: dash/TestEventsDerivesItsScopeFromTheResolver flakes under CPU contention (5/5 and 30/30 clean in isolation, green standalone, and this PR's only dash change is a comment). It reads whatever the SSE feed has flushed and wants a synchronisation point.

Commands

cd /tmp/cg-orch/r86e-tree   # git archive d4bc4e6
CGO_ENABLED=1 go test -race -count=1 -v -run \
  'TestReview|TestRetainedMaterialReachesNoOutputSurface|TestRetainedBodyIsMaskedAtRest|TestNoAuditSinkMeansNoRetention|TestForgetReleasesOneTenantsMaterial|TestSendPingHitsTheUpstream' ./proxy/

# sendPing posts its parameter verbatim; the xorMask there is the auth header, not the body
sed -n '/func (k \*keeper) sendPing/,/^}/p' proxy/keepalive.go

…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]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Spot-check at 9721fc0 — one stale comment, otherwise clean

gofmt empty, go vet clean, proxy and config green (-race -count=1).

1. Keeping keeper.forget in ctlUpdateMe — endorsed, and I checked both failure modes you named

Keep it. My objection was maintainability, not correctness, and your counter holds. What I checked rather than assumed:

Does it drop a hold the agent is entitled to? Yes — it purges on any /api/me save, including a label change, an upstream switch or a capture toggle, not only a consent change. That is safe in every case: dropping a hold fails closed, the agent loses at most one idle span's refresh per live session, and the next request re-records. With peak 11 live sessions and ~$0.85 per conversion, the worst realistic cost is a few cents on a human-frequency action.

Is there a path where an unrelated save silently ends coverage in a way that matters? This was the real risk, and the thing that would have made it matter is an automatic or polling PUT — that would suppress the feature permanently rather than momentarily. There isn't one: both /api/me PUTs are inside explicit handlers (saveSettings at app.js:4756, setStoredConfig at :4484), and all four setIntervals are GET refreshes and countdown painters. Blast radius is bounded to deliberate human saves.

Placement is right too — the purge sits after a successful registry().Update, so a rejected configuration (which the code's own comment calls the common case here) does not purge.

The asymmetry settles it: dropping a hold costs cents, keeping one costs a consent window on the path users actually take. Nothing to remove.

The one finding: the ponytail: comment on forget is now stale

keepalive.go:627:

"called from the three control-plane paths that revoke authority; a fourth would have to remember."

Three things wrong now:

  • There are four sites (1274 / 1326 / 1562 / 1946).
  • "revoke authority" no longer describes the set. ctlUpdateMe is a consent path — the credential still works and the hold is still authorized; what changed is permission to use it. That distinction was the whole basis of the ctlRevokeSession substitution, so losing it here is a real loss of the reasoning.
  • Its own warning has already come true, unremarked. "A fourth would have to remember" — a fourth arrived, and the comment that predicted the cost is the thing that did not get updated.

One line: "called from the four control-plane paths that end a hold's authority or its consent; a fifth would have to remember." The TenantSource.Forget consolidation it suggests is still the right upgrade path.

2. bytes.Equal landed; my file did not — and it is no longer blocking

keepalive_test.go:920 compares against pingBody(body) with the right justification. Good.

wire_review_test.go is not in the tree, so the seam between "what fire hands to send" and "what is actually posted" is still uncovered. But I'll downgrade my own ask, because bytes.Equal covers the half that matters:

  • Body path — now covered. Byte-exactness of what fire hands to send is asserted, and sendPing posts its parameter verbatim (strings.NewReader(string(body)), no mutation). That was the silent failure: altered bytes write at 12.5× and nothing complains.
  • Credential path — still uncovered. sendPing's own xorMask(a.val) → the header on the wire has no test driving it from a masked hold (TestSendPingHitsTheUpstream passes a plaintext header, so it never unmasks). But a broken unmask sends a corrupted key: 401, markStopped, failed counter climbing, zero successful pings. Loud, not silent.

So: worth landing when convenient, not worth holding a merge for. If you do want it, it is at /tmp/cg-orch/wire_review_test.go — ~40 lines, no new deps, and it fatals if the hold is not actually masked so it cannot pass vacuously.

3. K justification — correct

config/config.go:79-93 carries all five points accurately: the $1.28/day against [$95, $237] and the 1.4× split-half swing, +34% pings against the 180 429s, worst session −$2.42 → −$3.63 with losses +41% against the 85-of-119 baseline, the hold window 14 → 18.7 min, and the dead-entry argument as the decisive one. The prefix-floor alternative is there with the right numbers (+$125.12 on 908 pings).

No stale "peaks at K=2" survives anywhere — grepped .go and .md, zero hits.

4. Byte-bound note — correct

maxKeepAliveBytes now leads with "THIS is the binding ceiling, not maxKeepAliveSessions — tune this one", the ~130-large-session figure, and the part that matters most: that the replay's peak-11 exercises the count bound and "says nothing about this one". That is the caveat I would have asked for.

Verdict

APPROVE. One stale comment, no code changes needed. My d4bc4e6 approval stands and this commit does not disturb it.

On issue #91 — agreed on folding in TestDashboardAddsNoRequestLatencyWithContentCapture; both are the same class (reading a surface before the thing under test has flushed) and one cause deserves one fix. A deadline-poll is the right shape; a longer sleep just moves the threshold.

Noted on the COMMENTED review state and the ruleset — nothing to change from my side.

…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]>
@OsherElhadad
OsherElhadad merged commit 50e3966 into main Aug 22, 2026
5 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Aug 22, 2026
OsherElhadad pushed a commit that referenced this pull request Aug 22, 2026
#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]>
OsherElhadad pushed a commit that referenced this pull request Aug 22, 2026
#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]>
OsherElhadad pushed a commit that referenced this pull request Sep 6, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant