Repository navigation
feat(kvcache): budget keep-alive pings per conversation - #212
Conversation
Review: comprehensive pass over #212I reviewed this across ten lenses (induction arithmetic, Go↔Python drift, the simulator seam, test adequacy, mutation testing, Python quality, docs accuracy, architecture, statistical method, ops/CI), adversarially verified every finding with two independent checks each, and pushed the subset that was unambiguously a fix as 1404676. 38 candidate findings, 34 survived verification, 4 were refuted — the refuted ones are listed at the bottom so nobody re-raises them. What I ranReviewed on the branch merged with current
The merge is clean and Blocking: rebase, and then re-derive two of the argumentsThe methodology section is arguing against a version of this repo that no longer exists. Since
This page says the opposite in three places:
I am not saying your measurement is wrong — gating whether to ping and budgeting how many are different questions, and −0.45 pp on a stake-weighted person-period fit is consistent with +1.54 pp on a rule. But as written, a future reader takes this table as licence not to retry the signal main just shipped, and the "13 features are exactly what the seam carries / the restriction is free" argument no longer holds as stated. Both need a paragraph reconciling them, and the feature table needs Two seams for one concernMain already has, at // PingCapper is an optional interface: a strategy that caps its OWN keep-alive schedule below
// the window's MaxPings. PingCap returns the cap, or 0 for "no cap of its own".
type PingCapper interface { PingCap() int }consulted at The arithmetic composes safely, but three assertive claims are false post-merge, all saying the same thing:
I hit this empirically: the stronger version of Fixed and pushed in 1404676Everything here is verified by a mutation that fails without the fix. 1. The arm mis-priced three reachable configurations and had no guard. Every window Measured on
All three losing rows are reachable:
2. "The break-even is 8.70%, the same number for every prefix size" is not true.
Measured by bisecting the real
A full point at 500 tokens is the same order as this arm's headline margins (0.89 pp) and larger than the option-value effect it claims (8.70% → 7.4%). 3. The seam's tests could not see the seam. Three holes, each confirmed by a surviving mutant:
4. The port. 5. Prose that was not true.
Still open — your call, I did not touch thesea. b. The dollar-AUC table at c. "Pings are at 290 s throughout" ( d. e. 64 f. A panicking g. h. i. j. Methodology, for the record. With a stated ±0.42 pp seed-noise floor over 3 seeds and 18 days, the headline 0.89 pp gap is only ~2× the floor, so "a constant beats this arm" is directionally supported but not comfortably outside noise either — which cuts the same way as "the restriction is free" being "not measurable" rather than "zero". k. Adjacent, pre-existing, not yours: Considered and refuted — please don't re-raise these
What held up under attackWorth saying, because a lot did:
Net: the arithmetic is sound and the writing-down of where it loses is the best part of this PR. What needs doing before merge is the rebase and the two arguments it invalidates ( |
Re-review at
|
| prefix | derived | documented |
|---|---|---|
| 500 | 0.097391 | 9.74% ✓ |
| 2,000 | 0.089565 | 8.96% ✓ |
| 20,000 | 0.087217 | 8.72% ✓ |
| 124,845 | 0.086999 | 8.70% ✓ |
| limit | 0.10/1.15 = 0.086957 | 8.70% ✓ |
All four figures and the limit reproduce from first principles, independently of the shipped bisection test. The results table is internally consistent too: 6.96 − 6.07 = 0.89 pp ✓, 59.4 − 51.8 = 7.6 pts ✓, every "of the ceiling" column against 11.72 ✓, 9248/80404 = 11.5% ≈ "11%" ✓, 6.07/6.91 = 87.8% ≈ "88%" ✓, and the net-per-ping column reconciles exactly when indexed to MaxPings=6.
Revert-verification — seven mutations, source only
| Mutation | Observed failure |
|---|---|
(a) hardcode ping := rescue*0.0869565 instead of deriving from Pricing.KeepAliveCost |
TestBudgetGateRisesOnASmallPrefixByTheFixedOverhead: prefix 500: measured gate 0.086957, want 0.097391 (×4) |
(b) drop /survive in Go Windows |
TestBudgetHazardIsConditionalOnStillBeingIdle fails — and the cross-language guard catches it too: case 0 window 2 survival Go 0.01 vs port 1.0 |
| (b′) drop the survivor divide on the Python side | TestKeepAliveBudgetAgreesWithThePort: case 7 window 2 hazard: Go 0.5000000000, port 0.0500000000 and Go budget 2, port 0 — matches the description's claimed numbers to the digit |
(c) take the LAST positive V instead of the FIRST |
TestBudgetScheduleEndsWhereTheValueDoes: far-thin window: budget = 5, want 1 |
(d) let a budget above Config.MaxPings raise the cap |
TestPingBudgeterBoundsTheSimulatedPings: budget=99 under MaxPings=2 fired 1221 pings, want 60 |
(e) drop the Semantics/Interval guard (pricable() → always true) |
TestBudgetDeclinesASchedulePricedOnTheWrongRate: all 4 bad configs report (1,true) and Decide=ping_5m instead of declining |
(f) register an arm implementing PingBudgeter |
TestUnbudgetedArmsAreUnaffectedByTheSeam: test-interloper implements PingBudgeter — fails before reaching the leak-check |
Two of these deserve specific credit. (c) uses a genuinely non-monotone fixture — the exact adequacy problem the fix commit admits its predecessor had, now closed rather than restated. And (e) is the guard standing between the arm and the +17.6% / +86.0% / +146.1% regressions the commit message measures; it is reachable in production (dash/kvcacheapi.go reads those three fields off the query string with no clamp), so declining rather than inventing a number is the right contract.
No mutation passed with its defect present.
The body is now stale, and this is the finding I would act on
Three claims in the description contradict the code as merged. The body is what a reviewer reads first, so a stale body is not cosmetic.
- Claim 1 still says "The prefix size cancels, and so does the per-token rate." The final commit is literally titled "stop claiming the prefix cancels", and the code and doc now say only the per-token part cancels — the gate runs 8.70% → 9.74% between 125k and 500 tokens, which is a full point in the region
MinPrefixexists to protect. The doc was fixed; the body was not. - The test list says "kvcache — 9 new" with 9 bullets. There are 13. Diffing
keepalive_test.goat35851b6against HEAD: 9 before, and14046765added four —TestBudgetDeclinesASchedulePricedOnTheWrongRate,TestBudgetGateRisesOnASmallPrefixByTheFixedOverhead,TestBudgetCoversItsRemainingBranches,TestAPerConversationBudgetReachesThePingLoop. Confirmed bygrep -c '^func Test'= 13 and by the 85=== RUNlines. The irony is worth naming: three of the four omitted tests are precisely the ones that close the body's own stale economic claims. The list undercounts by understating the work. - The
stop_reasonfeature-set sentence is false once this rebases (see above).
Minor · the measurement's stated ping interval is wrong in three places. kvcache/keepalive.go:87, deploy/harbor/kv_ttl_keepalive_policy.py:72 and docs/how-to/kv-cache-keepalive-budget.md:170 all say pings are at 290s. The code is consistently 280s: DefaultPingIdle = 280 * time.Second (kvcache/strategy.go:498), DEFAULT_INTERVAL_S = 280.0 (kv_ttl_keepalive_policy.py:112), and the self-test prints interval 280s. So this is not a code/prose disagreement to adjudicate — the code agrees with itself and the prose is simply wrong, in the sentence that states the parameters of the run that produced the headline table. Three call sites, consistent with each other and with nothing else.
From the earlier 22.7k-char comment: what 14046765 closed, and what did not move
Closed, and independently re-verified here: the three unpriceable-schedule regressions; the prefix-dependent break-even; the three test-adequacy holes; the Python max_k <= 0 convention mismatch; the five prose corrections.
Still open — confirmed by direct inspection, since 14046765's diff touches only six files (kv_ttl_cost_drift_test.go, kv_ttl_keepalive_drift_test.go, kv_ttl_keepalive_policy.py, kv-cache-keepalive-budget.md, keepalive.go, keepalive_test.go):
Interval-vs-PingIdleis still enforced by prose only, with no assertion.- The dollar-AUC table's internal impossibility is untouched. Worth stressing that this one needs no production data to see — it is a consistency defect within the published numbers, so the data boundary is not what is blocking it.
_run_fixture'sbe = break_even(...)is still assigned inside the per-case loop, so the fixture reports only the last case's break-even (the 5×-rate case). A drift guard whose reported intermediate is the wrong case's is weaker than it looks.TestOptimalStillBoundsABudgetedArmcannot fail through its named mechanism —optimal's cost floor is structural (cfg.MaxPingscaps both sides). Correct, but not load-bearing, so it should not be counted as coverage for the property it names.- No
Resultbudget-distribution counter; still 3 calls/sweep × 8 sweeps with a literal double-call acrossDecide+Simulateand no memoization; norecover()on thePredictorpath (confirmed absent by grep — worth weighing againstCLAUDE.md's fail-open rule, since a third-party predictor panicking should revert this component only);ZeroGenerationstill unguardable from the Python side.
Code quality
PingBudgeter has exactly two non-test call sites — keepalive.go:220 (Decide) and simulate.go:495-496 (the seam) — and both handle ok=false correctly. No constructible panic path: Windows' survive <= 0 check runs before the division, and a NaN alive fails both survive <= 0 and the later > 0 test, degrading to the zero-initialised default rather than propagating. Entry guards (nil Predictor, unknown Pricing, non-positive CachedTokens) all precede the arithmetic. The seam being additive-and-optional is genuinely verified by (f) above rather than asserted.
Not verified
mkdocs build --strict — mkdocs is not installed in this environment, so I am not claiming it passed. CI reports it clean; that is CI's evidence, not mine.
The measured tables (34,577 idle spans, 16.9 days, the AUC figures, the arm comparison) come from the hosted deployment's own capture and were not re-derived — that is outside the data boundary this review held to. Their internal arithmetic consistency was checked instead, and it holds, with the one exception noted above.
Cross-PR note (#212, #211, #196)
These three do not collide: merged onto main in order with zero conflicts, and on the merged tree gofmt/vet/build are clean with kvcache, components/offload, config, internal/extract and deploy/harbor all passing. #211 is the only one already based on current main; this PR is 70 behind and #196 is 20.
One structural observation across them, since it bears on this PR's design: CI runs no Python at all — ci.yaml has only build-test, purego and trivy. This PR is the only one of the three whose Python is nevertheless covered, because the Go drift guard under deploy/harbor/ runs inside make cover. That is the right pattern and worth keeping in mind as the reason the guard's own weaknesses (the loop-scoped break_even above) matter more than they would for a script nobody's CI touches.
|
Pushed
Real numbers from this run, on
Not changed: the |
|
Round 2: closed the "still open" list from the re-review. Pushed three more commits — 1. No 2. 3. 4. 5. The dollar-AUC table's internal impossibility. Re-derived independently (didn't just take the earlier review's word for it): The table's own "all spans" cell (0.635) exceeds the 0.619 ceiling implied by its own "top 20%" row — impossible, no production data needed. I could not determine from arithmetic alone which of the two numbers (0.635 vs. 0.615) is the transcription error — that needs the underlying per-span dollar values, outside this task's data boundary — so per the brief I flagged the cell as unverified with the derivation shown, rather than guess. Separately, "0.70" for the same quantity — repeated in four places, one more than named ( Verification on New finding this round: re-checked Commit granularity note: the two new tests for #1/#3 and the #4 rename landed in one contiguous diff hunk in PR body updated again to match (Tests section now lists 15, the AUC table has the unverified flag inline). |
Config.MaxPings is one number for the whole replay. That is the right shape for a hand-written arm and the wrong one for a learned arm, because the budget a conversation is worth depends on the conversation: on the measured window the chosen budget is 0 for 77.8% of idle spans and runs out to 8 for a long tail. PingBudgeter is a one-method optional interface that lets a strategy say so. It is additive — any arm that does not implement it is budgeted by Config.MaxPings exactly as before, and Config.MaxPings stays a ceiling a model cannot raise. convState carries an explicit `budgeted` flag rather than a zero sentinel, because "decided not to ping" and "no opinion" are different facts and reading the first as the second would restore the configured cap on exactly the spans a model asked to leave alone. BudgetPolicy is the arm, and it is a decision layer over the existing Predictor seam rather than a model of its own — the model stays in Python, where a fit belongs. Three things it gets right that a threshold does not: - the break-even comes out of the rates (read 0.10x, rescue 1.15x, so 8.70%) rather than a constant, so a deployment on other rates gets its own and one with no rates gets ok=false rather than an invented number - the hazard is conditional on the conversation having already gone quiet, which is the only population that ever faces the decision. Where 90% have already returned, 5pp of remaining mass is a 50% conditional hazard - the pings are not independent, so the budget is a backward induction ending at the FIRST window whose value is not positive, not the last positive one Nine tests, each pinning one of those claims rather than one code path, including that no registered arm silently opted into the new interface and that `optimal` still bounds a budgeted arm. Signed-off-by: itay nakash <[email protected]>
kv_ttl_survival_predictor.py answers "will this conversation return within five minutes?" from the instant a request is served. That is the right question for a TTL tier and the wrong one for a keep-alive, because a keep-alive fires only after the conversation has already been idle for one interval — so the decision is never faced by the ~92.5% of spans that close inside five minutes. The unconditional 5-minute return rate on this window is ~92%; the stake-weighted hazard among spans that reached 270s idle is 23.17%. So this module fits the conditional thing instead. person_periods() builds one row per (span, sweep it actually reached), which is the layout in which every row is a decision the policy will really face. Elapsed silence is not a feature in it — it is the sample definition. The 13 features are exactly what kvcache.Observation carries plus two derived from Observation.Stats, and that is a constraint rather than a preference: a model fitted on anything else cannot be wired in behind kvcache.Predictor. It costs almost nothing — the unrestricted 21-feature model takes 6.11% off the window's bill against these 13 at 6.07%, inside the window's +-0.42 pp seed-noise floor — while dropping the two Stats features costs 0.40 pp. Everything above the `-- the fit --` divider is stdlib-only and pure, so the drift guard runs in a plain CI container; numpy and sklearn are imported inside the fitting functions only. kv_ttl_keepalive_drift_test.go drives the real --fixture entry point across 11 cases chosen to sit on branches the two implementations could diverge on, and compares the budget AND both intermediate vectors — a budget that agrees for the wrong reason is a guard that has already stopped working. Confirmed it can fail: deleting the survivor divide from the Python reports port 0.05 against Go 0.50 and flips a budget from 2 to 0. Signed-off-by: itay nakash <[email protected]>
The derivation, the feature table, and both measurement tables — including the one that says a flat MaxPings=5 beats the learned arm by 0.89 pp of the bill while losing to it 9x on net per ping. Which of the two to pick turns on whether a tenant rate limit rather than money caps the ping budget, so the page says that plainly instead of quoting only the favourable column. Figures are shares of the window's bill and of what `optimal` reaches, with per-ping efficiency indexed to a flat schedule, following the same shape as the TTL page's own results table. Also records what was measured and did NOT work, so it is not retried blind: threshold tuning (the best threshold chosen in hindsight is worth +0.38 pp overall and -0.05 pp on the top 5% of prefixes, so there is no headroom) and four families of extra feature, every one of which came in under the +-0.42 pp seed-noise floor — day-of-week, last-human-pause, gap history, and a stop_reason marker that was consistently 0.45 pp worse. The one measured blocker is named as such: row AUC 0.93 against dollar AUC 0.70, falling to 0.57 on the spans holding 87% of the stake. Everything that failed above was an attempt to work around that. Signed-off-by: itay nakash <[email protected]>
…op claiming the prefix cancels
Two things the arm asserted that the arithmetic does not, plus the tests that would
have caught them.
**A ping is not always a 0.1x read.** Every window PingBudget prices is one
KeepAliveCost. simulatePings only extends the entry when Semantics.PingRefreshesTTL,
and a ping that lands on a lapsed entry is billed RecreateCost — a 1.25x write. The
arm took Semantics only for the zero-generation term and never for the two fields
that decide whether a ping is a read at all, and never compared Interval against the
lifetime it protects, which pricing.go already names as the pathology it is.
Measured on kvcache's replay fixture at MaxPings=6, one predictor throughout, against
a plain 5-minute write with no pings:
documented semantics -0.9% (saves)
HitRefreshesTTL off +17.6%
PingRefreshesTTL off +86.0%
Interval 400s +146.1%
All three losing rows are reachable: dash/kvcacheapi.go reads hit_refresh,
ping_refresh and the ping interval off the query string with no clamp. So PingBudget
now returns ok=false on them — Config.MaxPings governs, which is the operator's
number rather than a model's, and Decide writes 5m and fires nothing. That is the
type's existing "decline rather than invent a number" contract, not a new one. With
the guard, all three land on the no-ping baseline exactly.
A zero Semantics now means DefaultSemantics(), as it already does for Config and for
HistoricalProbability. Without that, the new guard would read an omitted field as
three falses describing no provider.
**8.70% is the limit, not the number at every prefix.** KeepAliveCost's ping_input
and ping_output terms do not scale with the prefix, so the gate is
0.0870 + (ping_input*input + ping_output*output) / (prefix * (write_5m - read))
= 8.70% at 125k tokens, 8.72% at 20k, 8.96% at 2k, 9.74% at 500. A full point at 500
is the same order as the margins this arm is chosen by, and MinPrefix exists because
of it. The claim was stated in four places, including the name of a test that probes
only 0.5x and 3x the break-even and so could not have caught it. The four figures are
now pinned by bisecting the real gate.
**The seam's own tests could not see the seam.** Three holes, each verified by
mutation:
- TestUnbudgetedArmsAreUnaffectedByTheSeam claimed a before/after comparison it never
made: it asserted only that no arm implements PingBudgeter and that Simulate returns
non-nil, which it always does. Replacing the budget lookup with a hardcoded
`0, true` — zeroing every arm's pings — passed this test. It now replays each arm
twice, once behind a wrapper that hides its type from Simulate's assertion (the
pre-seam path), and compares totals and ping counts. It also fails if the registry
stops resolving instead of going vacuously green.
- Nothing checked that a per-conversation budget reaches the PING LOOP. Freezing the
Observation Simulate hands to PingBudget — one budget for the whole replay — left
the entire package green. A budgeter that says 0 for half the conversations and the
cap for the other half must now land strictly between the two constant runs.
- Decide's no-ping branch, Name's Label branch, Windows' certain-return short-circuit
and its partial-decline path had no coverage at all. keepalive.go is now at 100%.
**The port.** max_k <= 0 meant DefaultBudgetMaxK in Go and "no windows, budget 0" in
Python; the fixture always sends 8, so the guard could not see it. Python now shares
Go's convention and a second fixture run pins it. The drift test checks vector lengths
before indexing them, so a short window vector fails the guard rather than panicking
it, and its cdfPredictor sorts its points the way _run_fixture does rather than
relying on the fixture happening to be written in order. keepAlivePythonBin is now
pythonBin's own probe with the module name as a parameter, which was the only thing
the two ever differed in.
**Prose that was not true.** The Python docstring advertised a --db/--prices entry
point argparse rejects, and did not say that fit()/person_periods() are not wired to
one — so the figures it quotes cannot be reproduced from the file. FitResult.hazard is
fitted and never read: cdf_for composes the survival model alone, so the h_j the
policy uses comes from the survival curve via windows(). Said where a reader will hit
it, along with the two properties of cdf_for the --fixture guard cannot reach
(F(t_1)=0 by construction, and F(life) interpolated across a whole interval). Neither
module claims BudgetPolicy is "what the dashboard reports from" any more. And the
docs' opening bullet mixed MaxPings=5's percentages with MaxPings=6's net-per-ping
index: against the MaxPings=5 it names, the ratio is 7.6x, not 9x.
Signed-off-by: Osher-Elhadad <[email protected]>
…90s) The three prose call sites describing the measured run all said 290s while DefaultPingIdle and DEFAULT_INTERVAL_S are both 280s, and the self-test output prints 280s too. Bring the prose in line with what the code actually does; no behavior changes. Signed-off-by: Osher-Elhadad <[email protected]>
….Interval against Config.PingIdle Predictor is injectable, and CLAUDE.md's fail-open rule means a third-party implementation panicking must revert to Config.MaxPings (ok=false) rather than take down the caller. PingBudget is the one seam both real callers (Decide and the simulator) go through, so the recover() lives there. Also add the assertion BudgetPolicy.Interval's doc comment promised but never checked: Simulate now panics if a BudgetPolicy's Interval disagrees with Config.PingIdle, instead of silently pricing windows that are not the windows actually pinged. Signed-off-by: Osher-Elhadad <[email protected]>
_run_fixture assigned break_even inside its per-case loop and printed a single scalar, so the JSON only ever carried the LAST case's value. It went unnoticed here because every case in the shipped fixture derives its rates from the same multiples, so the ratio doesn't move with input_rate — but a fixture mixing rate shapes would have silently reported the wrong case's number. Report one break-even per case instead, and check every one against the rates' own value on the Go side rather than just the fixture's last row. Signed-off-by: Osher-Elhadad <[email protected]>
…stop repeating 0.70 The per-population AUC table's 'all spans' row claims dollar-weighted AUC 0.635, which is mathematically impossible given the same table's own top-20%-by-prefix row: a stake-weighted AUC decomposes as p^2*AUC_in + (1-p)^2*AUC_out + 2p(1-p)*AUC_cross for a subgroup holding stake share p, and the top-20% row (p=0.995, AUC=0.615) caps the all-spans cell at ~0.619 even granting the complement and every cross-pair a perfect 1.0 - below the 0.635 claimed. Which of the two rows is mis-transcribed isn't recoverable from the published figures alone, so the cell is now flagged unverified rather than left asserting a number that fails its own consistency check. A second figure for the same quantity, 0.70, was independently repeated in keepalive.go, kv_ttl_keepalive_policy.py (twice) and this doc's own 'Where to look next' section - impossible by the same arithmetic with an even wider margin. All four are corrected to stop asserting either number for the whole population. Signed-off-by: Osher-Elhadad <[email protected]>
…mismatch The panic added for the Interval-vs-PingIdle invariant contradicted the fail-open fix just made to PingBudget: Simulate is reachable from an HTTP handler (dash/kvcacheapi.go -> dash/kvcachesim.go) and package dash has no recover() of its own, so a panic here would turn a config mismatch into a dead connection instead of an answer. Simulate now overrides BudgetPolicy.Interval to Config.PingIdle before running, the same way NewStrategy already wires cfg.PingIdle into every registry arm at construction. This makes the two fields incapable of disagreeing rather than merely checked, with no new panic and no change to Simulate's signature. Signed-off-by: Osher-Elhadad <[email protected]>
…redates it main added Observation.StopReason (strategy.go:151, "on the same footing as CachedTokens or SinceLastMs") and a registered stop-reason-gated arm after this branch forked, so the feature-set table's "unrestricted (adds stop_reason, ...)" row described a seam that no longer excludes it. Drop it from the excluded examples and record that the 13-feature column predates the wider seam and was not re-run, rather than implying these numbers were measured against it. Signed-off-by: Osher-Elhadad <[email protected]>
bd8a27b to
f60029f
Compare
|
The branch is now rebased onto Everything closed across three roundsRound 1 — the body no longer matched the code:
Round 2 — the review's "still open" list:
Round 3 — the panic contradicted the fail-open fix:
The rebase
Post-rebase verification — the real numbers, on
|
What this adds
A per-conversation keep-alive budget: instead of one
MaxPingsfor the whole fleet, decidehow many pings each idle conversation is worth from what was knowable when its last request was
served.
Three pieces, and the first is the one to review:
kvcache.PingBudgeterPingBudget(o Observation) (int, bool)— that lets a strategy's per-conversation budget reach the ping loopkvcache.BudgetPolicyPredictorseam that turns reuse probabilities into a ping countdeploy/harbor/kv_ttl_keepalive_policy.pyPingBudgeteris optional and additive. Any strategy that does not implement it is budgeted byConfig.MaxPingsexactly as before, which is every arm in the registry today —TestUnbudgetedArmsAreUnaffectedByTheSeamasserts that none of them silently opted in.Why the existing seams were not enough
Predictorwas already the right shape and is used unchanged:BudgetPolicyasks it for acumulative
ReuseProbabilityat several horizons and derives everything from that. No new modelinterface.
What was missing was the ping count.
Config.MaxPingsis one number for the whole replay,which is the right shape for a hand-written arm and the wrong one for a learned arm, because the
budget a conversation is worth depends on the conversation: on the measured corpus the chosen
budget is 0 for 77.8% of idle spans and runs out to 8 for a long tail. Collapsing that to a
single K is most of the difference between the two.
The method, in three claims
1. The break-even comes out of the rates, not a config file. A ping costs a
0.10xread; arescue avoids the successor's
1.25xwrite, so it is worth1.15x. Ping when the chance exceeds0.10/1.15 = 8.70%. The model's per-token rate cancels, and so does the per-token part of theprefix — which is why the arm reads a probability and never a token count, and why it is computed
from
Observation.Pricingso that a deployment on other rates gets its own threshold and one withno rates gets
ok=false. What does not cancel is the ping's fixed overhead:Pricing.KeepAliveCost'sping_input/ping_outputterms don't scale with the prefix, so 8.70%is the gate only in the limit — it rises to 8.72% at 20k tokens, 8.96% at 2k, and 9.74% at 500,
a spread
MinPrefixexists to protect against.2. The decision is conditional on having already gone quiet. A keep-alive fires only after one
interval of idleness, so the decision is never faced by the ~92.5% of spans that close inside five
minutes. Unconditional 5-minute return rate on this corpus is ~92%; the stake-weighted hazard
among spans that reached 270s idle is 23.17%. The practical form: elapsed silence is not a
feature, it is the sample definition. Hence the divide by the survivor share in
BudgetPolicy.Windows— on a distribution where 90% have already returned, 5pp of remaining massis a 50% conditional hazard, not 5%.
3. Pings are not independent, so the budget is an induction. Each ping keeps the entry alive so
the next is a
0.1xread rather than a12.5xre-creation:The first, not the last: with a non-monotone hazard, taking the last positive
Vdouble-countsvalue the induction has already propagated backwards. This lowers the effective bar at the first
sweep to ~7.4% and is worth ~6% of the arm's net.
The 13 features are exactly what the seam carries
Every feature is on
kvcache.Observationor derived fromObservation.Stats, the leak-freeaccumulator the simulator already advances as gaps close. That is a hard constraint: a model
fitted on anything else cannot be wired in behind
Predictor.Measured cost of that restriction, 3-seed means, 5-fold rolling origin:
agent,tools, …)Observation+StatsObservationalonestop_reasonwas one of the unrestricted set's features when this ran, and has since joinedthe seam as
Observation.StopReason— on the same footing asCachedTokens, and read by theregistry's
stop-reason-gatedarm. So the 13-feature column predates it and the comparisonabove was not re-run against the wider seam; the numbers are the ones measured, not the ones a
rerun would produce.
The restriction is free. Dropping the two
Statsfeatures is not — the historical accumulator isdoing most of the work the excluded request-shape features would have done, which says the seam
was designed with the right things on it.
What it measured, including where it loses
The hosted deployment's own capture: 34,577 idle spans over 16.9 days, 5-fold rolling origin,
pings at 280s, at
/etc/context-guru/prices.yaml. Figures are shares of the window's total bill(of which 87.1% is the prefix portion a keep-alive can move) and of what
optimalreaches, withper-ping efficiency indexed to a flat schedule — the same shape as the TTL page's results table.
optimal(unreachable — reads the future)MaxPings=6MaxPings=5BudgetPolicyMaxPings=2(DefaultMaxPings)On money a constant beats this arm by 0.89 pp of the bill — 7.6 points of the ceiling — and
this says so rather than burying it. The measured reason:
¹ Unverified. A stake-weighted AUC decomposes as
p²·AUC_in + (1−p)²·AUC_out + 2p(1−p)·AUC_crossfor a subgroup holding stake share
p. The top-20% row (p=0.995,AUC=0.615) caps this cell at0.995²·0.615 + 0.005²·1 + 2·0.995·0.005·1 ≈ 0.619even granting the complement and everycross-pair a perfect 1.0 — below the 0.635 claimed here, so the two rows cannot both be right.
Which one is mis-transcribed isn't recoverable from the published figures alone, and re-deriving
it needs the underlying per-span dollar values — outside this page's data boundary. Read it as
"high 0.6x, exact value unconfirmed." (A "0.70" for this same quantity floated around three other
places in this PR —
keepalive.go,kv_ttl_keepalive_policy.pytwice, and this doc's own "Whereto look next" — and is impossible by the same arithmetic with a wider margin; all four are now
fixed to stop repeating it.)
It ranks conversations almost perfectly and dollars barely above chance, degrading toward the tail
where the money is — so its mistakes land on the large-prefix spans where a mistake costs most,
and at 11.5:1 that is decisive.
Where it wins is net per ping, by 9×: 88% of
MaxPings=5's saving for 11% of its pings.That matters where a tenant rate limit rather than money caps the budget, which on the live
deployment it plausibly does — ping coverage sits at 3.7% of candidates. But that is a rate-limit
question, not a modelling one, and it is the question to settle before choosing.
This PR therefore changes no default.
DefaultMaxPingsstays at 2. Raising it to 5 is worth+1.72 pp of the bill on this window and is a one-constant change, but it alters production ping
volume and belongs in its own PR with the rate-limit question answered.
Two things measured that did not work
Recorded in the doc so they are not retried blind.
Threshold tuning has no headroom. The best threshold chosen in hindsight is worth +0.38 pp across
all spans, +0.02 pp on the top 20% of prefixes, and −0.05 pp on the top 5%. Isotonic recalibration
collapsed to pinging nothing.
Four families of extra feature came in under the noise floor. The same model varies
±0.42 pp of the bill on the RNG seed alone:
is_weekend, × hour)gap > 100sstop_reason == end_turnThe last is instructive: those features are absent on 86.7% of rows but present on 87.8% of the
stake. Sparse in rows and concentrated in dollars is the worst shape for a stake-weighted fit.
Tests
kvcache— 15 new, each asserting one claim above rather than one code path:what
MinPrefixexists to protectMaxK=1declines a far window too thin to pay for the pings that reach it
ok=false;MinPrefixreturns(0, true)becausedeclining to ping is a decision
Semantics/Intervalthe arm cannot price (no TTL refresh, or an intervalpast the lifetime it protects) is declined rather than priced at the wrong rate
Name(), a schedule that resolves before the second sweep, and a predictor that answers somehorizons but not all, are all covered
ok=falsefalls back toConfig.MaxPings; a budget abovethe cap does not raise it
PingBudgeterthan collapsing to one number
Simulate, and is asked for once perconversation rather than once for the whole replay
optimalstill runs correctly alongside a strategy that implementsPingBudgeter(the ceilingcomparison itself can't fail through
BudgetPolicy's own arithmetic —Config.MaxPingsboundsboth sides identically — so this is a seam-composition check, not evidence the economics are
sound; the mutation-tested cases above are what pin that)
PredictordegradesPingBudgettook=falserather than propagating — requiredby
CLAUDE.md's fail-open rule, sincePredictoris injectableSimulateoverrides aBudgetPolicy'sIntervaltoConfig.PingIdlerather than trusting aseparately-set value that used to be able to drift from it (enforced by a doc comment only) —
a wrong
Intervalon the input now produces the identicalResulta correct one woulddeploy/harbor— a drift guard driving the Python's real--fixtureentry point across 11 caseschosen to sit on branches the two implementations could diverge on: either side of the break-even
to within 2 basis points, a lean-then-rich pair, a worthless tail, a far-but-reachable window, a
distribution where most have already returned, a small prefix where the ping's fixed overhead
matters, and a rate scale 5× different to prove the threshold does not move. It compares the budget
and both intermediate vectors, because a budget that agrees for the wrong reason is a guard
that has already stopped working.
Everything above the
── the fit ──divider in the Python is stdlib-only and pure, so the guardruns in a plain CI container. Verified the guard can fail: deleting the survivor divide from the
Python makes it report
port 0.05againstGo 0.50and flips a budget from 2 to 0._run_fixturenow reports one break-even per case rather than one for the whole fixture —it used to assign the value inside the per-case loop, so the JSON only ever carried the last
case's. That happened to go unnoticed here because every case's rates come from the same
multiples (the break-even ratio doesn't move with
input_rate), but a fixture that mixed rateshapes would have silently reported the wrong case's number. The Go side now checks every
case's break-even against the rates' own value, not just the fixture's last one.
Verification
No route is added, so
docs/reference/routes.mdneeds no row.BudgetPolicyis not inRegistry(), so nothing indash/needs updating —KVCacheArms()probes the registry ratherthan carrying a list, and an arm that needs a
Predictorcannot be built from a name.Docs
docs/how-to/kv-cache-keepalive-budget.md, added to the mkdocs nav next to Choose a cache TTLand cross-linked from it. It carries the derivation, the feature table, both measurement tables,
the negative results, and a "where to look next" that names the one measured blocker: the model
cannot rank dollars, and everything that failed above was an attempt to work around that.