Skip to content

feat(kvcache): budget keep-alive pings per conversation - #212

Merged
OsherElhadad merged 10 commits into
mainfrom
feat/kvcache-keepalive-budget
Sep 6, 2026
Merged

OsherElhadad merged 10 commits into
mainfrom
feat/kvcache-keepalive-budget

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Sep 5, 2026 •

Copy link
Copy Markdown
Collaborator

What this adds

A per-conversation keep-alive budget: instead of one MaxPings for the whole fleet, decide
how 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.PingBudgeter a one-method optional interface — PingBudget(o Observation) (int, bool) — that lets a strategy's per-conversation budget reach the ping loop
kvcache.BudgetPolicy the arm: a decision layer over the existing Predictor seam that turns reuse probabilities into a ping count
deploy/harbor/kv_ttl_keepalive_policy.py where the fit lives, plus the offline evaluation that produced the numbers below

PingBudgeter is optional and additive. Any strategy that does not implement it is budgeted by
Config.MaxPings exactly as before, which is every arm in the registry today —
TestUnbudgetedArmsAreUnaffectedByTheSeam asserts that none of them silently opted in.

Why the existing seams were not enough

Predictor was already the right shape and is used unchanged: BudgetPolicy asks it for a
cumulative ReuseProbability at several horizons and derives everything from that. No new model
interface.

What was missing was the ping count. Config.MaxPings is 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.10x read; a
rescue avoids the successor's 1.25x write, so it is worth 1.15x. Ping when the chance exceeds
0.10/1.15 = 8.70%. The model's per-token rate cancels, and so does the per-token part of the
prefix — which is why the arm reads a probability and never a token count, and why it is computed
from Observation.Pricing so that a deployment on other rates gets its own threshold and one with
no rates gets ok=false. What does not cancel is the ping's fixed overhead:
Pricing.KeepAliveCost's ping_input/ping_output terms 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 MinPrefix exists 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 mass
is 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.1x read rather than a 12.5x re-creation:

V_j = max(0, rescue×h_j − ping + s_j×V_(j+1)),   V_maxk = 0
budget = the FIRST j at which V_j is not positive

The first, not the last: with a non-monotone hazard, taking the last positive V double-counts
value 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.Observation or derived from Observation.Stats, the leak-free
accumulator 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:

feature set n dollar-weighted AUC off the bill vs unrestricted
unrestricted (adds agent, tools, …) 21 0.7051 6.11% —
Observation + Stats 13 0.7004 6.07% −0.04 pp
Observation alone 11 0.6916 5.71% −0.40 pp

stop_reason was one of the unrestricted set's features when this ran, and has since joined
the seam as Observation.StopReason — on the same footing as CachedTokens, and read by the
registry's stop-reason-gated arm. So the 13-feature column predates it and the comparison
above 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 Stats features is not — the historical accumulator is
doing 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 optimal reaches, with
per-ping efficiency indexed to a flat schedule — the same shape as the TTL page's results table.

arm pings off the bill of the ceiling net per ping
optimal (unreachable — reads the future) 5,826 11.72% 100.0% 27.7×
flat MaxPings=6 95,640 6.96% 59.4% 1.0×
flat MaxPings=5 80,404 6.91% 58.9% 1.2×
BudgetPolicy 9,248 6.07% 51.8% 9.0×
flat MaxPings=2 (DefaultMaxPings) 33,591 5.19% 44.3% 2.1×

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:

population share of stake AUC by row AUC by dollar
all spans 100% 0.93 0.635¹
top 20% by prefix 99.5% 0.76 0.615
top 5% by prefix 86.7% 0.58 0.566

¹ Unverified. A stake-weighted AUC decomposes as p²·AUC_in + (1−p)²·AUC_out + 2p(1−p)·AUC_cross
for a subgroup holding stake share p. The top-20% row (p=0.995, AUC=0.615) caps this cell at
0.995²·0.615 + 0.005²·1 + 2·0.995·0.005·1 ≈ 0.619 even granting the complement and every
cross-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.py twice, and this doc's own "Where
to 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. DefaultMaxPings stays 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:

family 3-seed mean verdict
day-of-week (numeric, categorical, is_weekend, × hour) +0.04 pp sign flips across seeds
last long pause via gap > 100s +0.05 pp sign flips; best dollar-AUC of any variant
trajectory gap history (max / mean / count) −0.15 pp sign flips
last human turn via stop_reason == end_turn −0.45 pp consistently worse on all 3 seeds

The 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:

  • the gate is the rates' break-even, and gives the same answer at 2k, 125k and 2M tokens
  • the gate holds only in the per-token limit — it rises to 9.74% at a 500-token prefix, which is
    what MinPrefix exists to protect
  • the option value pings through a lean first window, and does not with MaxK=1
  • the schedule ends on a worthless tail, holds through a dead stretch to a rich window, and
    declines a far window too thin to pay for the pings that reach it
  • every reason to have no opinion returns ok=false; MinPrefix returns (0, true) because
    declining to ping is a decision
  • a schedule priced on Semantics/Interval the arm cannot price (no TTL refresh, or an interval
    past the lifetime it protects) is declined rather than priced at the wrong rate
  • the hazard is conditional — same unconditional mass, 10× different conditional hazard
  • Name(), a schedule that resolves before the second sweep, and a predictor that answers some
    horizons but not all, are all covered
  • a budget bounds the simulated pings; ok=false falls back to Config.MaxPings; a budget above
    the cap does not raise it
  • no registered arm implements PingBudgeter
  • the budget fires fewer pings than pinging everything, and varies across conversations rather
    than collapsing to one number
  • a per-conversation budget reaches the ping loop through Simulate, and is asked for once per
    conversation rather than once for the whole replay
  • optimal still runs correctly alongside a strategy that implements PingBudgeter (the ceiling
    comparison itself can't fail through BudgetPolicy's own arithmetic — Config.MaxPings bounds
    both sides identically — so this is a seam-composition check, not evidence the economics are
    sound; the mutation-tested cases above are what pin that)
  • a panicking Predictor degrades PingBudget to ok=false rather than propagating — required
    by CLAUDE.md's fail-open rule, since Predictor is injectable
  • Simulate overrides a BudgetPolicy's Interval to Config.PingIdle rather than trusting a
    separately-set value that used to be able to drift from it (enforced by a doc comment only) —
    a wrong Interval on the input now produces the identical Result a correct one would

deploy/harbor — a drift guard driving the Python's real --fixture entry point across 11 cases
chosen 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 guard
runs in a plain CI container. Verified the guard can fail: deleting the survivor divide from the
Python makes it report port 0.05 against Go 0.50 and flips a budget from 2 to 0.

_run_fixture now 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 rate
shapes 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

go vet ./...                                       clean      (make lint)
gofmt -l .                                         clean      (make lint)
go test -race ./kvcache/ ./deploy/harbor/ ./dash/  pass       (dash 441s)
go build ./...                                     clean
mkdocs build --strict                              clean      (docs CI job)
python3 kv_ttl_keepalive_policy.py --self-test     pass

No route is added, so docs/reference/routes.md needs no row. BudgetPolicy is not in
Registry(), so nothing in dash/ needs updating — KVCacheArms() probes the registry rather
than carrying a list, and an arm that needs a Predictor cannot be built from a name.

Docs

docs/how-to/kv-cache-keepalive-budget.md, added to the mkdocs nav next to Choose a cache TTL
and 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.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Review: comprehensive pass over #212

I 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 ran

Reviewed on the branch merged with current origin/main, because the merge-base here is c863519 (2026-08-26) and main has moved a long way since. Both configurations verified:

branch alone merged with origin/main
go build ./... clean clean
gofmt -l . / go vet ./... clean clean
go test -race ./kvcache/ ./deploy/harbor/ pass pass
go test -race ./dash/ — pass, 473 s (you said 441 s)
mkdocs build --strict clean clean
python3 kv_ttl_keepalive_policy.py --self-test pass (on 3.9) pass

The merge is clean and PingCapper (main) composes with PingBudgeter to min() rather than overriding it, so nothing is broken by landing this. The problems below are all things the green suite does not see.


Blocking: rebase, and then re-derive two of the arguments

The methodology section is arguing against a version of this repo that no longer exists. Since c863519, main landed:

  • kvcache.Observation.StopReason, StopReasonCluster, ClusterOf (kvcache/kvcache.go, kvcache/strategy.go:148)
  • StopReasonGated — a registered, dashboard-visible arm (kvcache/registry.go:75,100,150; dash/kvcachesim.go:78,144)
  • docs/results/kv-ttl-predictor-features.md: "The headline feature: stop_reason … populated on every row", band rates 0.0–0.6% / 2.9–6.1% / 11.7–43.3% across 66,779 of 66,779 rows
  • docs/how-to/cache-keepalive.md: stop-reason-gated ships as a manager-selectable predictor, measured +1.54% vs fixed-5m, CI95 [0.60%, 2.79%], "statistically indistinguishable from a trained logistic regression on the same window, which is why it ships as a rule … rather than a model"

This page says the opposite in three places:

  • :131 — stop_reason is listed in the unrestricted 21-feature set, i.e. as something the seam does not carry. Observation.StopReason now carries it.
  • :202 — "last human turn via stop_reason == end_turn | −0.45 pp | consistently worse on all 3 seeds", recorded "so they are not retried blind".
  • :204 — "those features are absent on 86.7% of rows". Main measures the column populated on 100%.

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 stop_reason moved out of the "not available behind Predictor" column.

Two seams for one concern

Main already has, at kvcache/strategy.go:184:

// 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 simulate.go:381, implemented by KeepAlive (registry.go:205), so keepalive-5m-once and keepalive-1h-once are registered arms that already cap themselves. PingBudgeter strictly generalises it — any PingCapper is a PingBudgeter returning (cap, true) unconditionally.

The arithmetic composes safely, but three assertive claims are false post-merge, all saying the same thing:

  • keepalive.go:18 — "a strategy that does not implement it is budgeted by Config.MaxPings exactly as before, which is every arm that exists today"
  • the docs' "Any arm that does not implement the interface is budgeted by Config.MaxPings exactly as before"
  • and ### Implementing PingBudgeter on your own arm gives a reader no way to choose between the two

I hit this empirically: the stronger version of TestUnbudgetedArmsAreUnaffectedByTheSeam I first wrote — bypassing Simulate's type assertion to get the pre-seam path — fails on rebase with keepalive-5m-once: with the seam $23.103992 over 33 pings, with it bypassed $22.842408 over 60, because hiding PingBudgeter also hides PingCapper. That is the cleanest available proof that the invariant as stated is not true any more. I rewrote the test to assert something portable instead (below), but the seam question is yours: fold one into the other, or document the precedence.


Fixed and pushed in 1404676

Everything 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 PingBudget prices is one KeepAliveCost — a 0.1x read that carries the entry another lifetime. simulatePings only extends the entry when Semantics.PingRefreshesTTL, and a ping landing on a lapsed entry is billed RecreateCost, a 1.25x write. BudgetPolicy read Semantics only for the zero-generation term, never for the two fields that decide whether a ping is a read at all, and never compared Interval against the 300 s lifetime — the thing pricing.go itself calls "the pathology of a schedule whose interval exceeds the lifetime it is protecting".

Measured on dataset(t) at MaxPings=6, one predictor throughout, against a plain 5-minute write with no pings:

config pings billed as re-creations arm vs no-ping after the fix
documented semantics 60 0 −0.9% −0.9%
HitRefreshesTTL off (?hit_refresh=0) 60 7 +17.6% 0.0%
PingRefreshesTTL off (?ping_refresh=0) 60 27 +86.0% 0.0%
PingIdle=400s (?x=400) 51 51 +146.1% 0.0%

All three losing rows are reachable: dash/kvcacheapi.go:271-276 reads hit_refresh/ping_refresh off the query string and PingIdle from ?x=<seconds> through secondsParam, with no clamp anywhere. HitRefreshesTTL is the one the arm structurally cannot model — Observation carries no hit flag by design, so it cannot know whether this span's entry got a fresh lifetime.

PingBudget now returns ok=false on all three, which is the type's existing contract ("no opinion, use Config.MaxPings"), and Decide then writes 5m and fires nothing. A zero Semantics now means DefaultSemantics(), matching Config.withDefaults and HistoricalProbability.withDefaults — without that the guard would read an omitted field as three falses describing no provider.

2. "The break-even is 8.70%, the same number for every prefix size" is not true.

KeepAliveCost's ping_input/ping_output terms do not scale with the prefix, so

gate(prefix) = 0.0870 + (ping_input×input + ping_output×output) / (prefix × (write_5m − read))

Measured by bisecting the real PingBudget at MaxK=1, input=3.0e-6:

prefix claimed actual error
500 8.6957% 9.7391% +1.04 pp
900 8.6957% 9.2754% +0.58 pp
2,000 8.6957% 8.9565% +0.26 pp
20,000 8.6957% 8.7217% +0.026 pp
124,845 8.6957% 8.6998% +0.004 pp

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%). TestBudgetGateIsTheRatesBreakEvenAndIgnoresPrefixSize probes only 0.5× and 3× the break-even, so it would pass with the gate off by a point — the test named for the property could not have caught it. MinPrefix's own doc comment and Rates.ping_cost's docstring both already say the overhead doesn't scale, so the code knew and the prose didn't. The four figures are now pinned.

3. The seam's tests could not see the seam. Three holes, each confirmed by a surviving mutant:

  • TestUnbudgetedArmsAreUnaffectedByTheSeam's comment claimed "Every registered arm is replayed and compared against the same arm before PingBudgeter existed". Nothing was compared: 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. The comment now says what the test does, and the test additionally replays a budgeted stub between two runs of each arm and requires them identical to the cent — which is the failure the new mutable convState.pendingBudget/budgeted fields actually invite. It also fails if the registry stops resolving instead of going vacuously green (13 of 14 arms build; replay legitimately doesn't).
  • 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 kvcache package green. TestBudgetPolicyRunsThroughSimulateAndVariesPerConversation calls PingBudget directly and never runs Simulate(reqs, varying, cfg), so its name is only half earned. Added TestAPerConversationBudgetReachesThePingLoop: a budgeter saying 0 for half the conversations and the cap for the other half must land strictly between the two constant runs. It fails on the frozen mutant.
  • 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% statements.

4. 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. Verified: Go answers budget 1 where the port answers 0. Python now shares Go's convention and a second fixture run pins it (it fails if you revert the fallback). Also: the drift test checks vector lengths before indexing them, so a short window vector fails the guard rather than panicking it; its cdfPredictor sorts its points the way _run_fixture does rather than relying on the fixture happening to be hand-written in order; and keepAlivePythonBin is now pythonBin's own probe with the module name as a parameter, which was the only thing the two ever differed in — Group.Valued's comment in simulate.go makes the general argument better than I can.

5. Prose that was not true.

  • The module docstring advertised --db /var/lib/context-guru/cg.db --prices /etc/.../prices.yaml. argparse rejects it: error: unrecognized arguments. Both sibling harbor modules support exactly those flags with exactly those defaults (kv_ttl_cost_model.py:1660, kv_ttl_predictor_arms.py:696).
  • fit(), person_periods(), _state_frame(), FitResult, cdf_for() — ~180 of 482 lines — have no caller anywhere in the repo. So no figure quoted in this PR is reproducible from it. Said so, in the docstring, where a reader hits it.
  • FitResult.hazard is fitted (a second full HistGradientBoostingClassifier) and never read: cdf_for composes self.survival alone. So the h_j the policy actually uses is derived from the survival curve by windows(), not from the hazard model, and the docstring's "Reconstructed from the two hazards" describes something that doesn't happen. Documented rather than deleted.
  • cdf_for sets F(t_1) = 0 by construction and then asks np.interp for F(300) on a grid whose neighbouring keys are 280 and 560 — so h_1 is scaled by a pure interpolation artifact, (300−280)/(560−280) = 7.1% into the first survival step. The --fixture guard never reaches this function (it feeds a step CDF), so the drift test you are rightly proud of does not touch the code path that would run in production. Documented.
  • The 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.6×, not 9×. (9.0/1.2, or 7.637 from the raw counts.) Fixed, with the index named.
  • Neither module claims BudgetPolicy is "what the dashboard reports from" any more.

Still open — your call, I did not touch these

a. BudgetPolicy.Interval vs Config.PingIdle is enforced by prose alone. keepalive.go:99 and the docs both say in bold that they MUST match; nothing checks. With cfg.PingIdle=150s and BudgetPolicy{...} leaving Interval at its zero default (→ 280 s), the same predictor fires 63 pings / $24.84 where the matched policy fires 114 pings / $25.99 — an 81% difference in ping count presented as the same budget decision. Every BudgetPolicy literal in the tree sets Interval: cfg.PingIdle explicitly, so the mismatched path is never exercised. The clean fix threads the interval through the seam (PingBudget(o Observation, interval time.Duration)), which is a signature change I did not want to make inside someone else's design — especially with the PingCapper question above unsettled.

b. The dollar-AUC table at :171 is mathematically impossible. Dollar-weighted AUC is a weighted Mann–Whitney statistic, so for a subgroup holding stake share p the whole-population value decomposes as p²·AUC_in + (1−p)²·AUC_out + 2p(1−p)·AUC_cross. Top-20%-by-prefix holds 99.5% of the stake at AUC 0.615, so even granting the complement and every cross-pair a perfect 1.0 the ceiling on "all spans" is 0.995²·0.615 + 0.005² + 2·0.995·0.005 = 0.6188 — below the claimed 0.635. And the same document at :279, keepalive.go:89 and kv_ttl_keepalive_policy.py:66 quote 0.70 for that same quantity, where the top-5%/86.7% row caps it at 0.6738. So the table is internally inconsistent and the prose quotes a second, higher number. Either the weighting is not what "dollar-weighted AUC" normally means (in which case say what it is) or one of these was mis-transcribed.

c. "Pings are at 290 s throughout" (:148, and both module docstrings). DefaultPingIdle is 280 s, DEFAULT_INTERVAL_S is 280.0, the drift fixture uses 280, and docs/how-to/kv-cache-ttl.md:276 — cross-linked from this page — describes the default schedule as "a refresh every 280 s". 290 appears nowhere in the code. Either the results describe a configuration the shipped defaults cannot produce, or it is a typo; I couldn't tell which, so I left it. Two cross-linked pages currently give different cadences for the same corpus.

d. Result gains no budget counter. "the chosen budget is 0 for 77.8% of idle spans and runs out to 8" — the headline distribution — cannot be measured from a Go replay. Result.Pings conflates "budgeted 0" with "budgeted 3, span closed after one ping". StatsLevels and ObservedCoverage are the in-package precedent for exactly this decision-provenance counter.

e. 64 Predictor calls per pinging request, vs ≤2 for Custom and HistoricalProbability. Measured: BudgetPolicy over 40 requests made 2,560 ReuseProbability calls. Two causes: the deliberate double call (Decide → PingBudget, then Simulate → PingBudget again — verified at exactly 2×, with no memoisation anywhere despite the comment recommending it), and Windows computing ReuseProbability(o, tj+iv) for fNext and then recomputing the identical value as the next sweep's alive — 8 of 32 calls per budget are redundant. dash/kvcache.go:61 caps a read at kvCacheMaxRows = 200_000 and notes "several seconds at the cap"; 12.8 M inferences is a plausible timeout the day this arm is wired in. The redundant fNext is free to fix; the double call is a design choice worth revisiting alongside (a).

f. A panicking Predictor takes down the whole replay. No recover() anywhere on the Simulate/Predictor path, against CLAUDE.md's "Fail open, always". Pre-existing — Custom.Decide has the same exposure — but Windows calls the predictor up to 32 times per decision instead of twice, on the one arm explicitly framed as hosting a ported Python fit, so this widens the blast radius rather than creating it. Worth a recover() at the seam, or an explicit note that arms own their own robustness.

g. Semantics.ZeroGeneration is unguardable. It is a real pricing input on the Go side (pingOutput) with no analogue in the Python Rates, so the drift test structurally cannot exercise ZeroGeneration=true — reachable via ?zero_gen=1. A zero_generation: bool = False field on Rates, honoured in ping_cost, plus one fixture case, closes it. I left it because it changes the fixture wire format and you may want to do that with the rebase.

h. _run_fixture's be is assigned inside the case loop, so the reported break_even is only the last case's value. The guard's headline assertion therefore tests one row, and the "a rate scale 5× different proves the threshold does not move" claim holds only by accident of that case being last. Returning one break-even per case would make it real.

i. TestOptimalStillBoundsABudgetedArm passes whether or not the ceiling is enforced — optimal reads the future and can use up to cfg.MaxPings, so with a budget that can only lower, the bound is structural and the test cannot fail. Not wrong, just not load-bearing; worth saying so in the comment or making it adversarial (a budgeter that tries to exceed the cap).

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". weights = 1e-9 + stake/stake.mean() on a distribution where the top 5% carry 86.7% of the stake gives a very small effective sample size on exactly the segment that decides the outcome, and nothing reports it. And person_periods labels y_survival as all-zero for k == max_k (nxt = np.inf) while sweep_k is a model feature, which injects a stratum of guaranteed negatives into a pooled fit. None of this changes your conclusion — I think "don't change DefaultMaxPings, settle the rate-limit question first" is right — but the numbers deserve the caveats.

k. Adjacent, pre-existing, not yours: Config.withDefaults maps a zero Semantics to DefaultSemantics(), so ?hit_refresh=0&ping_refresh=0&zero_gen=0 silently yields Anthropic defaults on the dashboard — the one Semantics combination an operator cannot express. And ?x=<seconds> accepts any value with no check against the lifetime it protects. Mentioning, not touching.


Considered and refuted — please don't re-raise these

  • "BudgetPolicy is unreachable, and the 'like Custom' analogy is false." It isn't. dash/kvcachesim.go says of KVCacheSimConfig.Predictor: "There is no way to set this from an HTTP request and that is deliberate: a predictor is code, not a query parameter." kvCacheConfigFrom never sets it, so in production Custom runs with a real predictor exactly as often as BudgetPolicy does: never. Both need an in-process caller, which is precisely what the how-to shows. The analogy is accurate. (I did still correct "what the dashboard reports from", which was separately false.)
  • "Dropping - CacheRead from rescue survives the test suite." It survives ./kvcache/ alone, but make test/make cover/CI all run ./..., and budgetDriftFixture's ±2 bp bracket — commented "the row that catches a rate mistake" — catches it by design, not by luck. My new gate test now pins it in-package too.
  • "'pings rate-limited → this policy' is unhedged." The hedge ("that is a rate-limit question, not a modelling one, and it is the question to settle before choosing") is in the same paragraph, two sentences later, and the short version leads with the opposite emphasis.
  • "65.22% uses a strawman baseline (a keep-alive-free 5m write)." Correcting it moves the bar up, not down, since an optimal ping schedule can never cost more than no pings (V_j is floored at 0) — so it strengthens "don't offer the 1h tier". And the derivation is the repo's established one (sticky.go's sticky1hBreakeven, kv-cache-ttl.md:431).

What held up under attack

Worth saying, because a lot did:

  • The backward induction is correct. I re-derived it independently. h_j's marginal window (d_j, t_j+life] is exactly what ping j and only ping j buys, consecutive windows are disjoint, and the 20 s by which t_j+life overshoots t_{j+1} does not double-count: a conversation returning in that sliver is credited once in h_j, and the ping j+1 it wastes is charged inside V_{j+1} with no hazard credit. "First positive V, not last" is right, and max(0, …) makes v[j] <= 0 exactly == 0.
  • The falsifiability claim is exact. Deleting the survivor divide from windows() gives h[1] = 0.05 against Go's 0.50 and flips the budget 2 → 0, precisely as the docs say — and it trips the module's own self-test too.
  • optimal is still a bound. stepCost/openSpanCost pass cfg.MaxPings, a budget can only lower, so optimal's option set still dominates.
  • convState.pendingBudget/budgeted lifecycle is correct on every path I could construct, including the open-span pass. The explicit budgeted bool rather than a zero sentinel is the right call and the comment explaining why is the best one in the diff.
  • Derived and confirmed: 65.22% = (2.00−1.25)/(1.25−0.10); 8 × 280 s = 37.3 min for DefaultBudgetMaxK; the results table's "of the ceiling" column reconciles on every row (6.96/11.72 = 59.4, 6.07/11.72 = 51.8, 5.19/11.72 = 44.3); 0.89 pp, 7.6 points, +1.72 pp, 88%/11% all check out; MaxK <= 0 → default and Interval <= 0 → default follow the package's own convention.
  • Nothing sensitive. No credentials, no tenant identifiers, no captured content. Now: 1_786_967_311_185 and CachedTokens: 124_845 match the existing fixtures' style.

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 (stop_reason, PingCapper), the AUC table, and a decision on (a). The 290 s/280 s discrepancy is the cheapest thing on the list and the most likely to embarrass the page later.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Re-review at 14046765: arithmetic re-derived from first principles, seven mutations, and the merge against 70 commits of drift

Reviewed in a dedicated worktree. Verdict: approve with nits. The economics hold up under independent re-derivation, and every claim the fix commit makes is backed by a mutation that reproduces the original failure. What is left is bookkeeping — and the bookkeeping is where the risk now sits, because the PR body no longer describes the code.

Real run results

gofmt -l . / go vet ./... / go build ./...            all clean
go test -count=1 ./...                                 all 29 packages ok
go test -v -run . ./kvcache/...        | grep -c RUN    85
go test -v -run . ./deploy/harbor/...  | grep -c RUN     8
go test -race ./kvcache/... ./deploy/harbor/...         pass
go test -race ./dash/...                                pass, 473.127s
python3 kv_ttl_keepalive_policy.py --self-test
  self-test OK   break-even 8.70%   13 features   interval 280s / life 300s / max_k 8

The merge against current main is clean — this branch is 70 commits behind, so its green CI was earned on a stale base and that had to be checked. On the merged tree: no conflicts, gofmt/vet clean, kvcache + deploy/harbor tests pass. Two specific interactions with what landed on main after the fork:

  • PingCapper composes correctly with PingBudgeter via an effective min(): simulate.go:381-385 lowers cfg.MaxPings from PingCap(), and :745 then clamps the per-span budget to that already-lowered cap. No interaction bug.
  • One real rebase item: main now has Observation.StopReason / a registered StopReasonGated arm, while this PR's doc still lists stop_reason as not on the seam. The feature-set argument (13 features, "the restriction is free") is unaffected in substance, but the sentence is now false on main.

"stdlib-only above the divider" verified properly — not by grep alone, but by blocking numpy/sklearn/pandas through an importlib meta-path hook and then importing the module and running --self-test. Both succeeded. That is the claim that makes the drift guard runnable in CI, so it is worth having tested rather than asserted.

The arithmetic, re-derived rather than trusted

From Pricing.KeepAliveCost's own terms:

gate(cached) = CacheRead/(Write5m − CacheRead)
             + (PingInputTokens·Input + PingOutputTokens·Output) / (cached·(Write5m − CacheRead))
             = 0.086957 + 5.2174/cached
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.

  1. 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 MinPrefix exists to protect. The doc was fixed; the body was not.
  2. The test list says "kvcache — 9 new" with 9 bullets. There are 13. Diffing keepalive_test.go at 35851b6 against HEAD: 9 before, and 14046765 added four — TestBudgetDeclinesASchedulePricedOnTheWrongRate, TestBudgetGateRisesOnASmallPrefixByTheFixedOverhead, TestBudgetCoversItsRemainingBranches, TestAPerConversationBudgetReachesThePingLoop. Confirmed by grep -c '^func Test' = 13 and by the 85 === RUN lines. 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.
  3. The stop_reason feature-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-PingIdle is 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's be = 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.
  • TestOptimalStillBoundsABudgetedArm cannot fail through its named mechanism — optimal's cost floor is structural (cfg.MaxPings caps both sides). Correct, but not load-bearing, so it should not be counted as coverage for the property it names.
  • No Result budget-distribution counter; still 3 calls/sweep × 8 sweeps with a literal double-call across Decide+Simulate and no memoization; no recover() on the Predictor path (confirmed absent by grep — worth weighing against CLAUDE.md's fail-open rule, since a third-party predictor panicking should revert this component only); ZeroGeneration still 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.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Pushed 9b75723 fixing the bookkeeping nits from the re-review — the code was already right, only the prose had drifted:

  1. PR body's Claim 1 ("The prefix size cancels, and so does the per-token rate") was the pre-fix claim 14046765 corrected in the code but not in the description. Rewrote it to say what the code says: the model's per-token rate cancels and so does the per-token part of the prefix, but the ping's fixed overhead does not — the gate is 8.70% only in the limit, rising to 9.74% at a 500-token prefix.
  2. Test count: body said "9 new"; keepalive_test.go has 13 func Test... (confirmed by grep -c '^func Test', real 4 added by 14046765). Updated the count and added the 4 missing bullets (and one that was already missing before 14046765, for TestBudgetPolicyRunsThroughSimulateAndVariesPerConversation) so the list is 13-for-13 against the file.
  3. 290s → 280s: fixed the three call sites named in the review — kvcache/keepalive.go:87, deploy/harbor/kv_ttl_keepalive_policy.py:72, docs/how-to/kv-cache-keepalive-budget.md:170 — and the same stale figure in the PR body's "What it measured" section, which had the identical error.

Real numbers from this run, on 9b75723:

gofmt -l .                                              clean
go vet ./...                                            clean
go build ./...                                          clean
go test -count=1 ./...                                  27/27 tested packages ok (2 have no test files)
go test -v -run . ./kvcache/...      | grep -c '^=== RUN'   85
go test -v -run . ./deploy/harbor/...| grep -c '^=== RUN'    8
CGO_ENABLED=1 go test -race -count=1 ./kvcache/...      ok, 1.3s
python3 deploy/harbor/kv_ttl_keepalive_policy.py --self-test
  self-test OK   break-even 8.70%   13 features   interval 280s / life 300s / max_k 8

git merge-tree --write-tree HEAD origin/main — clean, no conflicts. The branch is currently 90 commits behind main and 4 ahead of the merge-base; per the task scope I did not rebase, only verified mergeability.

Not changed: the stop_reason feature-set sentence the review flagged as "false once this rebases" — on this branch, unrebased, it's still accurate, so changing it now would make it wrong rather than right. Leaving it for whoever rebases. Everything else in the "Still open" section of the re-review (loop-scoped break_even, the dollar-AUC table note, Interval-vs-PingIdle assertion, recover() on the Predictor path, etc.) is unchanged — the verdict was approve-with-nits and those weren't in the nits I was asked to close.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Round 2: closed the "still open" list from the re-review. Pushed three more commits — d9a5979, b62788b, a2073a3 — on top of 9b75723.

1. No recover() on the Predictor path. Confirmed by grep there was none, and that both real call sites (Decide and the simulator seam) route through BudgetPolicy.PingBudget, so that's the one place to guard. Added a defer recover() there that degrades to ok=false — the path both callers already handle correctly — plus TestPingBudgetDegradesRatherThanPropagatingAPredictorPanic with a deliberately panicking Predictor fixture. Revert-verified: with the guard removed, the panic propagates and names its own subject:

panic: predictor exploded [recovered, repanicked]
...
kvcache.BudgetPolicy.Windows(...)     keepalive.go:298
kvcache.BudgetPolicy.PingBudget(...)  keepalive.go:241
kvcache.TestPingBudgetDegradesRatherThanPropagatingAPredictorPanic(...)  keepalive_test.go:647

2. _run_fixture's loop-scoped break_even. Confirmed real: it reassigned a scalar inside the per-case loop, so the JSON reported only the last case's. It went unnoticed because every case's rates come from the same fixed multiples, so the value happens to be identical across cases regardless — but a fixture with mixed rate shapes would have silently reported the wrong case's number. Now reports one break-even per case; Go's budgetPyResult.BreakEven is []float64, checked per-case. Revert-verified: with the scalar restored, TestKeepAliveBudgetAgreesWithThePort fails with json: cannot unmarshal number into Go struct field budgetPyResult.break_even of type []float64.

3. Interval-vs-PingIdle enforced by prose only. Added the missing assertion: Simulate now panics if a BudgetPolicy.Interval disagrees with Config.PingIdle, naming both values. Checked every existing call site first — the one place BudgetPolicy is passed to Simulate in the test suite already sets Interval: cfg.PingIdle, so nothing broke. New test TestSimulateRejectsABudgetPolicyIntervalThatDisagreesWithConfig, revert-verified (fails with Simulate did not panic on a BudgetPolicy.Interval that disagrees with Config.PingIdle when the check is removed).

4. TestOptimalStillBoundsABudgetedArm couldn't fail through its named mechanism. Verified independently: optimal shares the same MaxPings cap as the arm it's compared against, and reads the future, so no strategy under that same cap — buggy or correct — can ever cost less than it. The comparison is unfalsifiable through BudgetPolicy's own arithmetic. Renamed to TestOptimalStillRunsCorrectlyAlongsideAPingBudgeter with a comment pointing at the mutation-tested TestBudget* cases as where the real economics coverage lives. No assertion changed.

5. The dollar-AUC table's internal impossibility. Re-derived independently (didn't just take the earlier review's word for it):

AUC_union = p²·AUC_in + (1−p)²·AUC_out + 2p(1−p)·AUC_cross
ceiling(p=0.995, AUC_in=0.615) ≈ 0.619   # from the "top 20%" row
ceiling(p=0.867, AUC_in=0.566) ≈ 0.674   # from the "top 5%" row

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 (keepalive.go, kv_ttl_keepalive_policy.py twice, and this doc's own "Where to look next") — exceeds both ceilings, so that one I could and did fix outright; all four now point at the flagged table cell instead of asserting a number that fails its own consistency check.

Verification on a2073a3: gofmt/vet/build clean. go test -count=1 ./... — 27/27 tested packages ok. CGO_ENABLED=1 go test -race ./kvcache/... ./deploy/harbor/... clean. grep -c '^func Test' kvcache/keepalive_test.go → 15 (was 13: +2 new, 1 renamed). === RUN count in ./kvcache/... → 87 (was 85). Python self-test unchanged: break-even 8.70% 13 features interval 280s / life 300s / max_k 8.

New finding this round: re-checked git merge-tree --write-tree HEAD origin/main (main has moved further since round 1). It's no longer clean — CONFLICT (content) in kvcache/simulate.go, because main added a PingCapper check at the exact same anchor line in Simulate() where this round's BudgetPolicy.Interval check also landed. Both insertions are additive and unrelated (PingCapper caps MaxPings; mine validates Interval), so it's a textual collision a rebase resolves by keeping both blocks — not a design conflict. Did not rebase or resolve, per instructions; flagging for whoever does the rebase, alongside the already-noted 90-commit lag and the stop_reason sentence from round 1.

Commit granularity note: the two new tests for #1/#3 and the #4 rename landed in one contiguous diff hunk in keepalive_test.go, so git add -p couldn't split them — d9a5979 covers #1, #3, and #4's rename together; b62788b is #2; a2073a3 is #5.

PR body updated again to match (Tests section now lists 15, the AUC table has the unverified flag inline).

itay-nakash and others added 10 commits September 6, 2026 14:59
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]>
@OsherElhadad
OsherElhadad force-pushed the feat/kvcache-keepalive-budget branch from bd8a27b to f60029f Compare September 6, 2026 15:08
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

The branch is now rebased onto main at cc4754d (0 behind, 10 commits ahead) — final tip is f60029fd36040eaa77f6d990a3fc3ceccd3dcbf3. gh pr view reports MERGEABLE. Everything below is verified fresh on that tip; earlier numbers in this thread are superseded.

Everything closed across three rounds

Round 1 — the body no longer matched the code:

  • Claim 1's "the prefix size cancels" rewritten to match what 14046765 actually shipped (per-token part cancels; the fixed overhead does not, so the gate is 8.70% only in the limit).
  • Test count corrected (body said 9, branch had 13 at the time).
  • 290s → 280s fixed at the three cited call sites plus the identical error in the PR body itself.

Round 2 — the review's "still open" list:

  • No recover() on the injectable Predictor path — added one at the single real seam (BudgetPolicy.PingBudget), degrading a panic to ok=false.
  • _run_fixture's loop-scoped break_even — now reports one value per case; the Go side checks every case, not just the last.
  • Interval-vs-PingIdle enforced by prose only — added the missing invariant (see round 3 for the final mechanism).
  • TestOptimalStillBoundsABudgetedArm couldn't fail through its named mechanism — renamed to TestOptimalStillRunsCorrectlyAlongsideAPingBudgeter, verified independently that the comparison is structurally unfalsifiable through BudgetPolicy's own arithmetic (optimal shares the same MaxPings cap and reads the future).
  • The dollar-AUC table's internal impossibility — re-derived the stake-weighted-AUC decomposition independently, confirmed the table's own "all spans" row is impossible given its own "top 20%" row. Could not determine which of the two is the transcription error (needs per-span data, outside this task's boundary), so flagged the cell unverified with the derivation shown rather than guess. The separately-resolvable "0.70" figure (repeated in 4 places) was fixed outright since it fails the check under both possible ceilings.

Round 3 — the panic contradicted the fail-open fix:

  • The Interval-vs-PingIdle check from round 2 used panic(...), in the same round as a recover() added on the grounds that a panic must not escape this package. Checked the call path: Simulate's only non-test callers are dash/kvcachesim.go, reached via an HTTP handler, and dash/ has zero recover() anywhere (confirmed by grep, unlike apply/components/proxy/internal/extract/modes, which all have at least one). One correction to the initial framing, checked rather than assumed: BudgetPolicy specifically isn't constructible via any current HTTP path (NewStrategy never returns one), but the inconsistency was real regardless of live reachability.
  • Fixed by overriding instead of panicking: Simulate now sets bp.Interval = cfg.PingIdle before running, the same authority-assignment NewStrategy already does for every registry arm. This makes the two fields structurally incapable of disagreeing rather than merely checked — stronger than a panic, and with no signature change.
  • Flagging separately, not fixing: dash/ having zero panic containment at all is a real gap relative to the rest of this codebase and is worth its own issue for whoever owns dash/.

The rebase

  • Two conflicts, both in kvcache/simulate.go, both from main's new PingCapper check landing at the same anchor line as this PR's Interval override. Resolved by keeping both blocks, PingCapper first. Independently confirmed the ordering is inert: only KeepAlive implements PingCapper (registry.go:205); BudgetPolicy does not, so no single Strategy value can ever trigger both branches.
  • stop_reason fix (f60029f): main added Observation.StopReason and a registered stop-reason-gated arm since this branch forked, so the feature table's "unrestricted (adds stop_reason, ...)" row was false — stop_reason is now on the seam, not excluded from it. Fixed the row and added a note that the shipped 13-feature comparison predates the wider seam and wasn't re-run against it. Read it closely: it neither overclaims (doesn't say a rerun would change the numbers) nor underclaims (doesn't hide that a new seam-eligible feature now exists).
  • Re-confirmed, at their current locations post-rebase, that all five round-2 fixes and round 3's override are still present and still doing their job — none of them are line-number- or string-match-fragile, so a hand-resolved rebase couldn't have quietly dropped one without breaking a test.

Post-rebase verification — the real numbers, on f60029f

gofmt -l .                                              clean
go vet ./...                                            clean
go build ./...                                          clean
go test -count=1 ./...                                  28 packages ok, 3 pre-existing
                                                         "[no test files]" — includes
                                                         internal/adjudicate, new on main
                                                         since this branch forked, passing
CGO_ENABLED=1 go test -race -count=1 ./kvcache/... ./dash/...
  kvcache   ok   1.306s
  dash      ok   482.738s
python3 deploy/harbor/kv_ttl_keepalive_policy.py --self-test
  self-test OK   break-even 8.70%   13 features   interval 280s / life 300s / max_k 8
grep -c '^func Test' kvcache/keepalive_test.go            15
grep -c '^=== RUN' ./kvcache/...                           95  (was 87 pre-rebase — the +8 are
                                                            main's own new kvcache tests from
                                                            the 90-commit gap, not this PR's)
grep -c '^=== RUN' ./dash/...                             538

PR body

Caught a real gap while finishing: round 2's body update was drafted but the gh pr edit push was never actually made, so the live body had been sitting on round 1's version this whole time. Fixed now — the body is caught up with all three rounds (the AUC footnote, the 15-item Tests list with the current override-not-panic wording, the per-case break_even note, and the stop_reason fix mirrored into the PR body's own copy of the feature table, which carried the identical stale row).

Nothing else is open from this review that was in scope for these three rounds. The dash/-has-no-recover() gap is flagged above for a separate issue, out of scope here.

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.

2 participants