Documentation
¶
Overview ¶
Package kvcache is the KV-cache TTL domain: the per-request analysis dataset the dashboard's KV-cache page reads, the pricing model for the six things a prompt-cache policy can spend money on, the Strategy interface a TTL policy (or a future learned predictor) implements, and the historical replay simulator that scores one strategy against another.
It is a PLAIN domain package, importable from anywhere, and it is deliberately not inside `dash`:
- A strategy is a decision the PROXY will eventually have to make on the request path, not a thing the dashboard owns. Defining it inside the observability layer would mean the request path had to import the dashboard to ask what to do.
- Nothing here touches SQL, HTTP or the DOM. `dash` reads the rows and hands them over; this package does the arithmetic. That is the same split the rest of this repo keeps — see the "NO ARITHMETIC HERE" rule at the top of the keep-alive tab's renderer, which this package is the server-side other half of.
Units, and they are stated once ¶
Every timestamp is epoch MILLISECONDS and every instant is UTC. Every duration in a struct field is milliseconds and says so in its name; every duration in an argument is a time.Duration. Every price is USD PER TOKEN (the operator's price list is per million tokens and is converted before it reaches here — see internal/modelinfo.Table).
There is no per-user timezone anywhere in the store, so "time of day" is UTC and every label that carries it says UTC. Inventing a local timezone from a tenant id would be a fabricated measurement, which is the failure this repo has hit repeatedly.
The one rule the simulator exists to hold shut ¶
A strategy sees an Observation, and an Observation carries NO future information. The next request's timestamp is not on it, its idle duration is not on it, and the historical statistics attached to it are accumulated from gaps that had ALREADY CLOSED at the decision instant. The real next-request time is used exactly once — to SCORE the decision after it has been made. TestStrategiesCannotSeeTheFuture is the assertion.
Index ¶
- Constants
- Variables
- func Derive(reqs []*Request)
- func ForcedMiss(reason string) bool
- func KeepAlivePingsOf(name string) (int, bool)
- func PingsPerSpan(gap, idle time.Duration, max int) int
- func StrategyNames() []string
- type Action
- type Bucket
- type BudgetPolicy
- type Config
- type Conversation
- type Coverage
- type Custom
- type Describer
- type Extend1h
- type Fixed
- type Group
- type HistoricalProbability
- type History
- type KeepAlive
- type Latency
- type Load
- type Multipliers
- type NoCache
- type Observation
- type Observed
- type Optimal
- type Override
- type PingBudgeter
- type PingCapper
- type Predictor
- type PriceList
- type Pricing
- func (p Pricing) HoldCost(cached int64, tier TTL, pings int, s Semantics) float64
- func (p Pricing) KeepAliveCost(cached int64, s Semantics) float64
- func (p Pricing) RecreateCost(cached int64, tier TTL, s Semantics) float64
- func (p Pricing) RequestCost(input, read, write, output int64, tier TTL) float64
- func (p Pricing) UncachedCost(input, prefix, output int64) float64
- type Replay
- type Request
- type Result
- type ReuseCategory
- type ReuseLevel
- type ReuseModel
- type ReuseTerm
- type Savings
- type Semantics
- type Stats
- type StickySession1h
- type StopReasonCluster
- type StopReasonGated
- type Strategy
- type StrategySpec
- type TTL
Constants ¶
const ( Horizon5m = modelinfo.AnthropicCacheTTL5m Horizon1h = modelinfo.AnthropicCacheTTL1h )
The two horizons the whole page is about: the provider's default lifetime, and the long tier. Named constants because they appear in a histogram edge, a summary card, a strategy threshold and a cost formula, and four literals would eventually disagree.
const ( TTLSourceConfigured = "configured" TTLSourceObserved = "observed" TTLSourceUnknown = "unknown" )
TTLSource values.
const ( // DefaultCacheReadMultiple is a cache hit's rate as a multiple of base input: the standard // 0.1x. The simulator knows the model of each row, so FromPrice fills a blank read rate with // modelinfo.CacheReadFracFor(model) unless the caller set Multipliers.CacheRead. This constant // stays the answer for a caller with no model and the value Multipliers.WithDefaults reports. DefaultCacheReadMultiple = modelinfo.AnthropicCacheReadFrac // DefaultWrite5mMultiple is a 5-minute cache write as a multiple of base input. DefaultWrite5mMultiple = modelinfo.AnthropicCacheWrite5mFrac // DefaultWrite1hMultiple is a 1-hour cache write as a multiple of base input. DefaultWrite1hMultiple = modelinfo.AnthropicCacheWrite1hFrac // DefaultPingOutputTokens is the smallest generation Anthropic's Messages API accepts. DefaultPingOutputTokens = 1 // DefaultPingInputTokens is the fresh input a ping carries beyond the cached prefix — // the one-token user turn that makes it a legal request. DefaultPingInputTokens = 1 )
The documented Anthropic-family multiples, as named defaults rather than literals spread across a cost function. Overridable per deployment through Multipliers.
const ( StrategyNoCache = "no-cache" StrategyFixed5m = "fixed-5m" StrategyFixed1h = "fixed-1h" StrategyKeepAlive5m = "keepalive-5m" StrategyKeepAlive1h = "keepalive-1h" // StrategyKeepAlive5mOnce and StrategyKeepAlive1hOnce hold at their tier and refresh with // exactly ONE keep-alive per idle span, then let the entry lapse. See KeepAlive.Once and // PingCapper. StrategyKeepAlive5mOnce = "keepalive-5m-once" StrategyKeepAlive1hOnce = "keepalive-1h-once" // StrategyKeepAlive5mPingsPrefix names the 5-minute keep-alive arm with an exact ping budget per // idle span: "keepalive-5m-x1" .. "keepalive-5m-x11" (see KeepAlive5mPings). The flat arms above // fix the budget at 1 (once) or at the window's MaxPings; a per-cell sweep needs every count in // between, because the measured best count differs by account and hour. StrategyKeepAlive5mPingsPrefix = "keepalive-5m-x" // StrategyExtend1h writes at the cheap tier and extends to an hour only when a // conversation actually goes quiet. StrategyExtend1h = "keepalive-5m-to-1h" StrategyObserved = "observed-policy" StrategyHistorical = "historical-probability" // StrategyStopReasonGated writes the five-minute tier on every request but only pings // while idle when the request just served's own stop_reason clusters as // ClusterActuallyDone. See StopReasonGated and // docs/results/kv-ttl-predictor-arms.md — measured +1.54% vs fixed-5m (CI95 [0.60%, // 2.79%]), not distinguishable from a trained logistic regression on the same window. StrategyStopReasonGated = "stop-reason-gated" // StrategyStickySession1h commits a whole conversation to the 1-hour or the 5-minute // tier at its first request and never revisits the choice. See StickySession1h. StrategyStickySession1h = "sticky-session-1h" StrategyOptimal = "optimal" StrategyReplay = "replay" )
The canonical arm names. Strings, because they are a wire contract: they appear in a query parameter, in a JSON key, in the offline evaluator's own table and on the page.
const ( LevelUserBucket = "user+model+bucket" LevelUserModel = "user+model" LevelUser = "user" LevelModel = "model" LevelGlobal = "global" LevelNone = "none" )
The fallback levels, most specific first. LevelNone means nothing at all was known — not "zero probability".
const ( DefaultP5m = 0.5 DefaultP1h = 0.5 DefaultMinPrefix = 20000 // NOTE (#435, #719): the shipped config default is now 240 s / 80k floor (20k except for a main thread that waits for a person or for an unknown cause), but this simulator (and the // suggester built on it) still scores at 280 s / 20k: its hazard windows are fixed at the W1 // clock and cannot represent the W3 cliff. Moving it needs a re-fit, not a constant edit. // DefaultPingIdle and DefaultMaxPings are the shipped keep-alive schedule for a // FIVE-MINUTE entry: a ping every 280 s, at most 2 per idle span. 280 rather than 300 so // the refresh lands before the lifetime, not on it. DefaultPingIdle = 280 * time.Second DefaultMaxPings = 2 // DefaultPingIdle1h is the same margin against the one-hour lifetime: 56 minutes rather // than 60. A one-hour entry therefore needs one twelfth as many refreshes to be held for // the same wall-clock span, which is the ping-count half of the 5m-vs-1h trade. DefaultPingIdle1h = 3360 * time.Second )
The shipped defaults for HistoricalProbability. 0.5 on both is the honest reading of a probability threshold: act when the outcome is more likely than not. MinPrefix follows the keep-alive tab's own shipped gate.
const DefaultBudgetMaxK = 8
DefaultBudgetMaxK is how far the induction looks ahead.
Eight, because at DefaultPingIdle that is ~37 minutes of holding, and on the measured corpus 34.3% of the stake sits on spans that return LATER than that — unreachable at any budget, since holding a five-minute entry that long costs more than the write it avoids. Looking further therefore adds cost and no reachable rescues.
const LatencyMinN = 20
LatencyMinN is how many of each population the differential needs. 20 is small, and it is stated rather than assumed: below it the difference of two means is not a measurement.
const MaxKeepAlivePings = 11
MaxKeepAlivePings is the largest per-span budget a K-ping arm is registered for. It matches the live strategy bound (proxy's maxOverridePings), so every registered arm can be enforced.
const OverrideAll = "*"
OverrideAll is the overrides key that applies to EVERY model before its own entry.
It exists for the two fields that are provider facts rather than model rates — the ping's minimum input and output — which a caller would otherwise have to repeat once per model in the window, and would then get wrong for the thirteenth.
const SourcePriceList = "price_list"
SourcePriceList is what a rate the deployment's own Pricer answered is labelled.
It deliberately does not name WHICH pricer: the chain is assembled by the proxy (operator price list first, then the public LiteLLM map) and this layer is handed the composed Pricer, so claiming "operator_table" here would be a guess. The label says the rate came from the configured price list; "override" says a person typed it.
const StrategyKeepAliveBudget = "keepalive-budget"
StrategyKeepAliveBudget is this arm's default label, in the registry's hyphenated wire style. It is deliberately NOT in the registry: like Custom, this arm cannot be built from a name alone — it needs a Predictor — so a caller constructs it and passes it to Simulate, and the registry keeps its promise that every name in it resolves.
Variables ¶
var Actions = []Action{ActionExpire, ActionWrite5m, ActionWrite1h, ActionPing5m, ActionPing1h, ActionWrite5mPing1h}
Actions is every action, in escalating cost order.
var Buckets = []Bucket{BucketNight, BucketMorning, BucketAfternoon, BucketEvening}
Buckets is every bucket in clock order, for a filter control or a group-by.
var ReuseModelV1 = &ReuseModel{ Version: "v1", TrainedOn: "2026-08-17 11:48 -> 2026-09-04 21:45 UTC", IntervalS: 280.0, LifeS: 300.0, MaxK: 8, Intercept: 5.018342744954828, Numeric: []ReuseTerm{ {Name: "log_prefix", Coef: -2.0617767376699336, Center: 4.146090828434305, Scale: 4.7037498066187835}, {Name: "log_prev_gap", Coef: -0.051073693614662456, Center: 0.8069032678784968, Scale: 1.7739566028829084}, {Name: "turn", Coef: 0.17222201868549095, Center: 93.21953452687274, Scale: 539.4799156608967}, {Name: "hour_sin", Coef: -0.11807319204324197, Center: -0.03876981083782035, Scale: 0.698196684692585}, {Name: "hour_cos", Coef: 0.05351815398273302, Center: -0.12480005679454068, Scale: 0.7038772883647778}, {Name: "dow_sin", Coef: -0.044776344705750655, Center: 0.5289808564926407, Scale: 0.5991648136759256}, {Name: "dow_cos", Coef: 0.06955802004724103, Center: -0.27736442403982214, Scale: 0.5331507814789217}, {Name: "stat_p", Coef: 0.3068298285865256, Center: 0.8669557007725781, Scale: 0.13350760774270665}, {Name: "log_stat_n", Coef: -0.028663327452458465, Center: 5.707126141180795, Scale: 1.7859544188184382}, }, Categorical: []ReuseCategory{ {Name: "model", Levels: []ReuseLevel{ {Level: "", Coef: 0.044073416904029585}, {Level: "aws/claude-haiku-4-5", Coef: 0.01059219829200029}, {Level: "aws/claude-opus-5", Coef: 0.5891045430667132}, {Level: "aws/claude-sonnet-5", Coef: 0.4672028093860629}, {Level: "azure/gpt-4o", Coef: 0.04754489687167924}, {Level: "azure/gpt-5.5", Coef: 0.43532292998608124}, {Level: "claude-haiku-4-5", Coef: 0.05693310295387887}, {Level: "claude-opus-4-6", Coef: 0.8914374258675521}, {Level: "claude-opus-4-7", Coef: 0.20280481953179896}, {Level: "claude-opus-4-8", Coef: 0.5671313782762598}, {Level: "claude-opus-5", Coef: 0.759769916393038}, {Level: "claude-sonnet-4-6", Coef: 0.6687443839651331}, {Level: "claude-sonnet-5", Coef: 0.24100295418844414}, }}, {Name: "sweep", Levels: []ReuseLevel{ {Level: "", Coef: 0.0}, {Level: "1", Coef: -0.8103139873353238}, {Level: "2", Coef: -0.04573723713715996}, {Level: "3", Coef: 0.6255276686681279}, {Level: "4", Coef: 0.8279466337110583}, {Level: "5", Coef: 0.35705180846007445}, {Level: "6", Coef: 0.6740656989771248}, {Level: "7", Coef: 1.8645461417180886}, {Level: "8", Coef: 1.4885780486208022}, }}, }, }
ReuseModelV1 is the fitted, frozen reuse model the `keepalive-budget` arm reads.
See reusemodel.go for what the fields mean and for the CDF this composes. The numbers are a logistic survival fit on the corpus named above; the Python that produced them, the feature arithmetic they assume, and this table are pinned together by TestReuseModelV1AgreesWithThePort.
Functions ¶
func Derive ¶
func Derive(reqs []*Request)
Derive fills the chronological half of the dataset in place: NextTS, NextID, HasNext, IdleMs, Within5m and Within1h.
Three properties, each of which is a way this has been got wrong before:
- Grouped by CONVERSATION, which is (user, session). A later request from another conversation is never the successor of this one, whatever its timestamp, because the provider's entry it would reuse is a different entry. The one exception the data model would allow — a shared, byte-identical prefix across sessions — is not recorded anywhere in the store, so it is not assumed here.
- Sorted by (ts, id). Timestamps tie: on the production corpus 9 of 12,635 consecutive pairs share a millisecond. The id breaks the tie deterministically, so the same window derives the same dataset twice, and a zero-length gap stays zero rather than becoming negative.
- The LAST request of a conversation gets HasNext=false and a nil IdleMs. It is not a request with an idle time of zero, and it is not a request that was never followed — it is a request whose successor is outside the window (or has not happened yet), and every aggregate below counts it in its own bucket.
Requests is sorted in place.
func ForcedMiss ¶ added in v0.5.3
ForcedMiss says whether a recorded miss reason is one no TTL could have rescued: the content moved (prefix_change), there was no entry (cold_start), or the dashboard could not explain the miss (unknown). A miss we cannot explain is never counted as rescuable. Treating it as a live entry would turn every unexplained miss into a simulated hit and raise every arm's hit rate.
func KeepAlivePingsOf ¶ added in v0.5.3
KeepAlivePingsOf reports k for an arm named StrategyKeepAlive5mPingsPrefix + k, 1 <= k <= MaxKeepAlivePings.
func PingsPerSpan ¶
PingsPerSpan is how many keep-alives one idle span of `gap` attracts under (idle, max).
The first fires at `idle` after the last activity, each subsequent one `idle` after the last, and `max` caps the count. A span no longer than `idle` attracts none.
This is the same arithmetic as dash.PingsPerSpan, which serves the keep-alive tab's own calculator. It is restated here because the dependency runs the other way: dash imports this package, so this one cannot import dash to reuse it.
The two ARE pinned against each other, by TestPingScheduleMatchesTheKeepAliveTab in package dash — the only package that can import both — over a 12x4x5 grid of (gap, idle, K) chosen to straddle the boundaries where they could differ: dash's takes float64 SECONDS and floor-divides those, this takes a time.Duration and floor-divides integer nanoseconds. The Python port is pinned separately by four guards in deploy/harbor/kv_ttl_cost_drift_test.go.
An earlier version of this comment said the Go/Go guard did not exist. It does; a comment that denies a guard sends the next reader to write a second one.
func StrategyNames ¶
func StrategyNames() []string
StrategyNames is the arm names in the same order.
Types ¶
type Action ¶
type Action string
Action is what a strategy decides to do about a conversation's cached context for the idle span that starts now.
Six actions, and they are the whole set of things a caller can actually buy from a prompt-caching provider. "Do nothing" is ActionExpire — an entry nobody pays to keep lapses on its own — and saying so explicitly is what makes a no-cache baseline a strategy rather than an absence.
const ( // ActionExpire writes no cache_control at all: this request's prompt is billed as fresh // input and nothing is held afterwards. ActionExpire Action = "expire" // ActionWrite5m writes/retains the prefix at the 5-minute tier. ActionWrite5m Action = "write_5m" // ActionWrite1h writes/retains the prefix at the 1-hour tier. ActionWrite1h Action = "write_1h" // ActionPing5m writes/retains at 5 minutes AND keeps refreshing it with keep-alive // reads while the conversation is idle. ActionPing5m Action = "ping_5m" // ActionPing1h holds the entry at the 1-hour tier and refreshes it with keep-alive // reads while the conversation is idle. ActionPing1h Action = "ping_1h" // ActionWrite5mPing1h writes at the CHEAP tier and buys the long hold only if the // conversation actually goes quiet: the request itself creates a 5-minute entry at 1.25x // input, and if a keep-alive comes due before that lapses, THAT keep-alive extends the // context by an hour — a 1-hour write of the prefix at 2.0x, after which the entry is // hourly and needs refreshing twelve times less often. // // It is a distinct arm from ActionPing1h and not a variation of it. ActionPing1h pays the // 2.0x creation premium on EVERY request; this pays 1.25x on every request and 2.0x only // on the rare span that outlives five minutes. On traffic where 92.5% of gaps close inside // five minutes that is a different bill entirely, which is the whole reason it exists. // // The upgrade is priced as a 1-hour WRITE rather than a read, and that is a measurement // rather than a guess: the deployment's own capture shows a request asking for ttl:"1h" // over an already-warm prefix returning 36,251 of 36,574 written tokens on the 1h // creation tier (see the cache_write_1h column in dash/schema.go). If some provider bills // it as a read instead, this arm is CHEAPER than reported here, never dearer. ActionWrite5mPing1h Action = "write_5m_ping_1h" )
func (Action) PingTier ¶
PingTier is the tier this action's keep-alives hold the entry at, which is what a ping has to pay to reach. TTLNone for an action that never pings.
type Bucket ¶
type Bucket string
Bucket is a coarse time-of-day label, in UTC.
const ( BucketNight Bucket = "night" // 00:00–05:59 UTC BucketMorning Bucket = "morning" // 06:00–11:59 UTC BucketAfternoon Bucket = "afternoon" // 12:00–17:59 UTC BucketEvening Bucket = "evening" // 18:00–23:59 UTC )
The four buckets. Six-hour bands rather than 24 hours: the per-user statistics a strategy leans on need enough requests per cell to mean anything, and on the production corpus 24 cells per user leaves most of them empty. The hour itself is still on every row (Request.HourUTC) for anyone who wants the finer view.
func BucketOf ¶
BucketOf places one UTC hour in its bucket. An hour OUTSIDE 0..23 lands in night rather than in whichever band its arithmetic happens to fall into: the input comes from strftime and from a JSON query parameter, so an out-of-range value is a caller error, and quietly filing hour 99 under "afternoon" would be a fabricated label.
type BudgetPolicy ¶ added in v0.2.0
type BudgetPolicy struct {
// Label is the name the dashboard groups by. Defaults to StrategyKeepAliveBudget.
Label string
// Predictor answers the reuse question. Required: with none, this arm has no opinion on
// any observation and every budget falls back to Config.MaxPings.
Predictor Predictor
// Interval is the keep-alive cadence this policy assumes when it reasons about windows.
// It matters when PingBudget/Windows/Decide are called directly, outside Simulate.
// Simulate itself always overrides this to Config.PingIdle before running — the windows
// priced must be the windows actually pinged, and PingIdle is Simulate's own authority on
// that, so a caller cannot let the two drift by setting this to something else. Defaults
// to DefaultPingIdle.
Interval time.Duration
// MaxK caps the induction's horizon. Defaults to DefaultBudgetMaxK.
MaxK int
// MinPrefix is the prefix below which this arm does not bother pinging. A ping's fixed
// overhead (ping_input, ping_output) does not scale with the prefix, so on a small enough
// entry the arithmetic above is dominated by it. 0 disables the gate.
MinPrefix int64
// Semantics must match the Config's: a ping's cost depends on whether the provider
// accepts a zero-generation request, and whether a ping refreshes the entry at all
// decides whether this arm has an opinion — see pricable. The zero value means
// DefaultSemantics(), as it does for Config and for HistoricalProbability, so a caller
// who omits the field is priced against the documented behaviour rather than against
// three falses that describe no provider.
Semantics Semantics
// contains filtered or unexported fields
}
BudgetPolicy is the LEARNED keep-alive arm: it asks a Predictor how likely the conversation is to come back in each window a ping would protect, and buys the pings that pay for themselves.
It is deliberately a decision layer over Predictor rather than a model of its own. The model is Python (deploy/harbor/kv_ttl_keepalive_policy.py), because that is where a fit belongs; what was missing on the Go side, and what this is, is the arithmetic that turns probabilities into a ping count. Handing it a stub Predictor is how it is tested.
THE GATE ¶
One ping costs Pricing.KeepAliveCost — a cache read over the prefix, plus the fresh input and the one output token a ping cannot avoid. A ping that lands while the entry is alive and is followed by the conversation actually returning converts the successor's cache WRITE into a cache READ, so it avoids
rescue = prefix × (write_5m_rate − cache_read_rate)
Ping if the chance of that exceeds its cost, i.e. if rescue×h > ping. On the documented Anthropic multiples (read 0.1×, write 1.25× of base input) the PER-TOKEN part of the prefix term cancels and leaves 0.1/1.15 = 8.70%, the same number for every model — which is why this reads a probability and not a token count. It is computed from o.Pricing rather than written down because a deployment whose rates differ has a different threshold, and one that has no rates at all has none.
What does NOT cancel is the ping's fixed overhead. KeepAliveCost carries ping_input and ping_output terms that do not scale with the prefix, so the true gate is
0.0870 + (ping_input×input + ping_output×output) / (prefix × (write_5m − cache_read))
which is 8.70% only in the limit. At the documented multiples and one token each way it is 8.70% at 125k tokens, 8.72% at 20k, 8.96% at 2k and 9.74% at 500 — a spread of the same order as the margins this arm is decided by. MinPrefix exists for exactly that reason, and nothing below the tens of thousands of tokens should be read as 8.70%.
WHY IT IS NOT THAT SIMPLE ¶
8.70% is the MYOPIC bar, and it is too high. A ping does two things: it may rescue this window, and it keeps the entry alive so that the NEXT ping is still a cheap read rather than a 12.5× re-creation. The second is worth paying for on its own. So the budget is a backward induction over the windows a ping would protect,
V_j = max(0, rescue×h_j − ping + s_j×V_(j+1)), V_(MaxK) = 0
and the budget is the first j at which V_j is not positive — the FIRST, not the last, because the hazard is not monotone in j on real traffic and taking the last positive one buys a run of pings across a dead stretch to reach a live one. That option value lowers the effective bar to about 7.4% at the first sweep and is worth ~6% of the arm's net on the measured corpus.
WHAT IT IS WORTH ¶
Measured on the hosted deployment's capture: 34,577 idle spans over 16.9 days, 5-fold rolling origin, pings at 280s. Given as a share of the window's bill and of what `optimal` reaches, with per-ping efficiency indexed to flat MaxPings=6:
arm pings off the bill of the ceiling net per ping optimal (unreachable) 5,826 11.72% 100.0% 27.7x flat MaxPings=6 95,640 6.96% 59.4% 1.0x flat MaxPings=5 80,404 6.91% 58.9% 1.2x BudgetPolicy 9,248 6.07% 51.8% 9.0x flat MaxPings=2 (dflt) 33,591 5.19% 44.3% 2.1x
So this is NOT the cheaper policy where pings are free: a constant beats it by 0.89 pp of the bill, 7.6 points of the ceiling, because the model ranks conversations well (AUC 0.93) and DOLLARS much worse, falling to 0.57 on the largest prefixes, which carry 87% of the stake. (Not 0.70 for the whole population: kv-cache-keepalive-budget.md's own AUC-decomposition arithmetic rules that out; its table flags the whole-population dollar-AUC cell unverified rather than assert a number that fails the check.) What it is, is 9x more efficient PER PING, which is what matters where a tenant rate limit rather than money is what caps the budget. docs/how-to/kv-cache-keepalive-budget.md has the derivation and says plainly which to pick.
func NewKeepAliveBudget ¶ added in v0.3.1
func NewKeepAliveBudget(cfg Config) BudgetPolicy
NewKeepAliveBudget builds the learned keep-alive arm from the model compiled into this binary.
This constructor is why `keepalive-budget` is IN the registry, and the reason is worth stating because the arm's own doc comment says the opposite. BudgetPolicy was excluded on the grounds that it "cannot be built from a name alone — it needs a Predictor", and while the only Predictor was an injected one that was exactly right: a name in the registry has to resolve, and one that resolved to an arm with a nil Predictor would resolve to an arm that never pings — a silently different policy wearing the right label.
ReuseModelV1 removes the premise rather than the promise. The model is a fixed table of coefficients in this binary, so the name resolves to the same arm on every process, in every replay, without anything being handed in. Nothing else about the exclusion argument changes: a caller with its OWN predictor still constructs BudgetPolicy directly and hands it to Simulate, exactly as before, and gets its own label.
MinPrefix is deliberately left at 0 — no small-prefix gate. The arithmetic does not need one: PingBudget's ping cost is Pricing.KeepAliveCost, which already carries the fixed ping_input/ping_output terms that do not scale with the prefix, so the break-even it compares against is the true one at 500 tokens as much as at 125k. MinPrefix is an operator dial for a deployment that wants a floor anyway, not a correction for a bias, and choosing a number here would be inventing one.
func (BudgetPolicy) Decide ¶ added in v0.2.0
func (b BudgetPolicy) Decide(o Observation) Action
Decide holds the prefix at five minutes, and pings only when the budget it would choose is at least one.
It does not offer the 1-hour tier. That is not an omission: on this corpus the share of spans that close inside an hour but outside five minutes exceeds the share closing inside five minutes by 2.35 percentage points, and the 1-hour tier needs 65.22 points to break even against a 5-minute write. HistoricalProbability is the arm that reasons about tiers; this one reasons about ping counts.
func (BudgetPolicy) Describe ¶ added in v0.2.0
func (b BudgetPolicy) Describe() string
func (BudgetPolicy) Name ¶ added in v0.2.0
func (b BudgetPolicy) Name() string
func (BudgetPolicy) PingBudget ¶ added in v0.2.0
func (b BudgetPolicy) PingBudget(o Observation) (budget int, ok bool)
PingBudget is the backward induction described on the type.
It returns ok=false — "no opinion, use Config.MaxPings" — when there is no predictor, when the model declines the observation, when the rates are unknown so no break-even exists, or when the schedule is one this arm cannot price (see pricable). Every one of those is a case where a number invented here would be worse than the configured default. MinPrefix is the one gate that is NOT in that list: it reports (0, true), because declining to ping is a decision.
func (BudgetPolicy) Windows ¶ added in v0.2.0
func (b BudgetPolicy) Windows(o Observation) (h, s []float64, ok bool)
Windows converts the Predictor's CUMULATIVE answers into the two per-sweep quantities the induction needs, both conditional on the conversation still being idle when the ping fires.
Exported for one reason: deploy/harbor/kv_ttl_keepalive_drift_test.go pins these two vectors against the Python port alongside the budget itself, because a budget that agrees for the wrong reason — a hazard scaled wrong and a survival scaled inversely wrong — is a guard that has already stopped working. It is also the honest way to inspect why the policy chose what it chose. ok=false where the predictor declines, matching PingBudget.
Ping j (1-based) fires at j×interval after o.Now and refreshes the entry to j×interval+lifetime, so the window it and it alone protects is
(deadline standing before it, j×interval + lifetime]
where that deadline is lifetime for the first ping and (j−1)×interval+lifetime after. Then with F(x) = ReuseProbability(o, x), the CONDITIONAL quantities are
h_j = (F(t_j + life) − F(d_j)) / (1 − F(t_j)) this ping rescues s_j = (1 − F(t_(j+1))) / (1 − F(t_j)) reaches the next sweep
Dividing by the survivor share is the whole reason this is not just a lookup: the decision at sweep j is only ever faced by a conversation that has ALREADY stayed idle that long, so an unconditional probability answers a question nobody asks. A predictor whose F is not monotone would produce a negative h; that is clamped rather than trusted.
type Config ¶
type Config struct {
// Prices is the rate table. A model with no rates leaves its requests UNPRICED — counted,
// never valued.
Prices *PriceList
// Semantics is the provider's cache behaviour. Zero value means DefaultSemantics().
Semantics Semantics
// PingIdle is the keep-alive interval for a FIVE-MINUTE entry and PingIdle1h the interval
// for a ONE-HOUR one; MaxPings caps either. Both default a little inside the lifetime they
// protect, so a refresh lands before the deadline rather than on it. Zero values mean the
// shipped defaults.
PingIdle time.Duration
PingIdle1h time.Duration
MaxPings int
// WindowEnd bounds the OPEN idle span at the end of a conversation, in epoch ms.
//
// A conversation whose last request is inside the window has an idle span whose length
// nobody knows — its successor may be outside the window, or may never come. Its pings and
// its retention are therefore billed only up to here, and that is not a rounding-down: a
// keep-alive policy cannot know a conversation is over either, so it really does spend up
// to MaxPings on the last request of every dead session, and charging that is what stops
// the ping arms looking cheaper than they are. What the bound does is stop the charge
// running past the data.
//
// The pings it produces are counted apart (Result.PingsOnOpenSpans) because their NUMBER
// depends on where the window happens to end whenever the remaining span is shorter than
// MaxPings intervals, which is an assumption the closed spans do not need.
//
// 0 means the last timestamp in the dataset. Never time.Now(): the same historical window
// has to replay to the same answer twice.
WindowEnd int64
}
Config is everything the replay needs beyond the strategy itself.
type Conversation ¶
type Conversation struct {
User string
Conversation string
// Model is part of the key, and leaving it out was a bug rather than a simplification. A
// cache entry does not transfer between models, so an opus request cannot read a sonnet
// request's entry. Without the model here, Derive links the two as successor and the replay
// grants the second a hit at 0.1x on an entry it could never have matched — measured at 46%
// understatement on a two-request trajectory, and the bias is one-directional: every arm
// looks cheaper and hits more often than it can.
//
// It reaches 5.7% of this deployment's corpus (101 of 1,772 trajectories use more than one
// model), and this repo's own predictor said so before the simulator did: the
// compatibility-columns note in deploy/harbor/kv_ttl_survival_predictor.py keys on the model
// for exactly this reason and spells out the consequence of not doing it. The Python was
// right and the Go was wrong.
Model string
}
Conversation identifies one trajectory, and it is a PAIR.
A session id is client-supplied, so two accounts can present the same one — by accident or on purpose. Keying a conversation on the session id alone would splice two accounts' requests into one interleaved trajectory and derive idle gaps across the join, which is both a wrong measurement and a cross-account read. The store's own indexes and its tool-inventory GC trigger are tenant-leading for exactly this reason.
type Coverage ¶
Coverage is "how much of this arm is a measurement": decisions that rested on a recorded fact against decisions that rested on an assumed default.
type Custom ¶
type Custom struct {
// Label is the name the dashboard groups by. Defaults to "custom".
Label string
// Predictor, when set, answers the two horizon questions instead of Stats.
Predictor Predictor
// Decider, when set, replaces the whole rule. The last resort seam: a policy that is not
// expressible as two thresholds plugs in here and still gets scored identically.
Decider func(Observation) Action
// Thresholds and gates, as HistoricalProbability's.
P5m float64
P1h float64
MinPrefix int64
Semantics Semantics
PingIdle time.Duration
MaxPings int
// AlwaysPing forces the long hold to use pings rather than the cheaper of the two, for
// an operator who wants to measure the ping path specifically.
AlwaysPing bool
}
Custom is the configurable arm: thresholds, or a Predictor, or both.
It exists so a new idea can be evaluated against the same baseline without a new type and without touching the simulator. With a Predictor set it asks that; with none it falls back to the same historical thresholds HistoricalProbability uses, so a partially-configured Custom is still a working strategy rather than a no-op.
func (Custom) Decide ¶
func (c Custom) Decide(o Observation) Action
type Describer ¶
type Describer interface {
Describe() string
}
Describer is an optional interface: a strategy that can explain itself in one sentence gets that sentence rendered beside its results instead of just its name.
type Extend1h ¶
type Extend1h struct{}
Extend1h writes every prefix at the CHEAP five-minute tier and buys the long hold only if the conversation actually goes quiet.
It is the arm the other two keep-alive arms bracket, and on traffic like this deployment's it is the one worth having: 92.5% of gaps close inside five minutes, so KeepAlive1h pays the 2.0x creation premium on nearly every request for a hold nearly none of them needs, while this pays 1.25x on every request and 2.0x only on the rare span that outlives five minutes. See ActionWrite5mPing1h for what the upgrading keep-alive costs and why it is priced as a write.
func (Extend1h) Decide ¶
func (Extend1h) Decide(Observation) Action
type Fixed ¶
type Fixed struct{ TTL TTL }
Fixed always chooses one tier, and never pings. The two rungs everybody compares against.
func (Fixed) Decide ¶
func (f Fixed) Decide(Observation) Action
type Group ¶
type Group struct {
Key string `json:"key"`
Requests int64 `json:"requests"`
TotalUSD float64 `json:"total_usd"`
Hits int64 `json:"hits"`
Misses int64 `json:"misses"`
HitRate float64 `json:"hit_rate_pct"`
Pings int64 `json:"pings"`
PingUSD float64 `json:"ping_usd"`
Writes5m int64 `json:"writes_5m"`
Writes1h int64 `json:"writes_1h"`
Unpriced int64 `json:"unpriced"`
// Valued is whether ANY request in this group could be priced, exactly as Result.Valued is
// for the whole replay — and it is here because omitting it forced the consumer to spell the
// predicate a second time as `unpriced < requests` on every per-user and per-model row. Two
// spellings of one predicate is how they come to disagree the day one of them gains a caveat,
// which is the argument for Result.Valued and applies unchanged one level down.
Valued bool `json:"valued"`
}
Group is one strategy's result restricted to one user or one model.
type HistoricalProbability ¶
type HistoricalProbability struct {
// P5m and P1h are the probability thresholds. Zero means the shipped default.
P5m float64
P1h float64
// MinPrefix is the prefix below which nothing is cached at all: a small prefix cannot
// repay a write, and on the production corpus the 10th percentile prefix is 0 tokens.
MinPrefix int64
// Semantics is needed for the cost comparison in step 2.
Semantics Semantics
// PingIdle and MaxPings define the keep-alive schedule the long hold would use.
PingIdle time.Duration
MaxPings int
}
HistoricalProbability is the simple learned-from-your-own-history arm: choose the cheapest action whose horizon the account's own gaps say the conversation will probably come back inside.
The rule, in the order it is evaluated:
- If P(next request within 5 minutes) >= P5m, a plain 5-minute write is enough: the entry survives on its own and a ping would be pure waste.
- Otherwise, if P(within 1 hour) >= P1h, hold it for an hour. Whether that is a 1h WRITE or a 5m write plus keep-alive pings is decided by which is cheaper on THIS prefix — the arithmetic is in cheaperLongHold, and it is the whole reason a strategy needs the rates rather than a token count.
- Otherwise let it expire.
Both thresholds are fields, and the fallback chain is Stats's: a user with too little history of their own is decided on their model's statistics, then on the service's, and the level that was used is recorded per decision so the results can say how much of the arm was actually personalised.
func (HistoricalProbability) Decide ¶
func (h HistoricalProbability) Decide(o Observation) Action
func (HistoricalProbability) Describe ¶
func (h HistoricalProbability) Describe() string
func (HistoricalProbability) Name ¶
func (h HistoricalProbability) Name() string
type History ¶
type History struct {
// contains filtered or unexported fields
}
History is the leak-free Stats implementation the simulator uses.
It is EMPTY at the start of a replay and gains one observation per gap AS THAT GAP CLOSES — that is, when the successor request arrives, not when the predecessor is decided. So a decision made at time T can only ever see gaps that ended at or before T. That is the whole mechanism by which the replay is honest, and it is why History is a mutable accumulator rather than a precomputed table: a precomputed table over the window would carry the future into every early decision.
func (*History) MedianIdle ¶
MedianIdle implements Stats.
type KeepAlive ¶
type KeepAlive struct {
TTL TTL
// Once caps this arm's OWN schedule at exactly one keep-alive per idle span, refreshing
// the entry once and then letting it lapse rather than pinging it for as long as
// cfg.MaxPings allows. See PingCap.
Once bool
// Pings, when > 0, caps this arm's own schedule at exactly that many keep-alives per idle span.
// It generalises Once (Pings 1 is the same schedule) and is what KeepAlive5mPings sets.
Pings int
}
KeepAlive is a fixed arm that holds every prefix at one tier AND refreshes it with keep-alives while the conversation is idle.
Separate from Fixed because the difference is not the tier: it is whether anything is spent to hold the entry past its own lifetime. On the production corpus this is the only hand-written arm that beats the shipped 5-minute policy, and it does so without consulting any statistics at all — which is the measurement any learned arm has to be compared with.
func KeepAlive1h ¶
func KeepAlive1h() KeepAlive
func KeepAlive1hOnce ¶
func KeepAlive1hOnce() KeepAlive
func KeepAlive5m ¶
func KeepAlive5m() KeepAlive
KeepAlive5m and KeepAlive1h are the two shipped keep-alive arms.
func KeepAlive5mOnce ¶
func KeepAlive5mOnce() KeepAlive
KeepAlive5mOnce and KeepAlive1hOnce are the same two arms, capped to a single keep-alive per idle span — the cheap end of "does pinging help at all" against the repeated-ping arms above, at whatever the window's MaxPings is otherwise configured to.
func KeepAlive5mPings ¶ added in v0.5.3
KeepAlive5mPings is the 5-minute keep-alive arm with exactly k pings per idle span.
func (KeepAlive) Decide ¶
func (k KeepAlive) Decide(Observation) Action
type Latency ¶
type Latency struct {
PerMissMs float64 `json:"per_miss_ms"`
HitN int64 `json:"hit_n"`
MissN int64 `json:"miss_n"`
HitMeanMs float64 `json:"hit_mean_ms"`
MissMean float64 `json:"miss_mean_ms"`
Known bool `json:"known"`
}
Latency is the window's own measured cost of a cache miss, in milliseconds, and the two populations it was measured over.
Derived from the selected rows and nothing else: the mean upstream time of the requests that really hit, against the mean of the ones that really missed. Known=false where either population is too small to mean anything, and then no latency figure is reported at all rather than a difference of two noisy means.
func MeasureLatency ¶
MeasureLatency computes the window's own hit/miss latency differential from the rows.
type Load ¶
type Load struct {
// InFlight is concurrent upstream requests at the decision instant.
InFlight int `json:"in_flight"`
// UpstreamMs is the recent mean upstream latency, in milliseconds.
UpstreamMs float64 `json:"upstream_ms"`
}
Load is optional system-load information, for a strategy that wants to back off when the deployment is busy. A POINTER on the Observation, and nil on every deployment that does not measure it: a strategy that reads a zero as "idle" would behave differently on a deployment that simply has no gauge, which is the failure mode a bool-plus-value pair cannot express.
type Multipliers ¶
type Multipliers struct {
CacheRead float64 `json:"cache_read"`
Write5m float64 `json:"write_5m"`
Write1h float64 `json:"write_1h"`
}
Multipliers are the deployment-wide fractions used to fill in a rate a price list does not state. Zero means "use the default", so a partially filled struct is safe.
func DefaultMultipliers ¶
func DefaultMultipliers() Multipliers
DefaultMultipliers is the shipped set.
func (Multipliers) WithDefaults ¶
func (m Multipliers) WithDefaults() Multipliers
WithDefaults returns the multipliers with every zero replaced by its default. Exported because the dashboard reports the multiples a simulation actually used, and reporting the caller's partially filled struct would show zeros where the defaults were applied.
type NoCache ¶
type NoCache struct{}
NoCache is the baseline: never write cache_control, so every prompt is billed as fresh input and nothing is ever held.
It is the honest denominator for "what does caching earn", and it is also the arm that makes a bad strategy visible: a policy whose total exceeds this one is charging the caller for a cache that never pays for itself, and that has to be reportable rather than clamped away.
func (NoCache) Decide ¶
func (NoCache) Decide(Observation) Action
type Observation ¶
type Observation struct {
// Who and what. User is the tenant, Conversation the trajectory.
User string
Conversation string
Model string
// RequestID identifies the request just served. Present-tense identity, not a
// prediction: it is here so an arm that replays a recorded per-request decision — and a
// future predictor that keys features per request — needs no side channel.
RequestID int64
// Now is the decision instant: epoch ms, UTC. It is the timestamp of the request just
// served, which is when the cache_control header has to be chosen.
Now int64
HourUTC int
Bucket Bucket
// CachedTokens is the prefix that exists after this request — the thing a TTL protects
// and a ping refreshes, and the number every cost below is proportional to.
CachedTokens int64
// SinceLastMs is how long this conversation had been idle BEFORE the request just
// served, i.e. the gap that has already closed. 0 on a conversation's first request.
// Past information, and the single most useful past fact a strategy has.
SinceLastMs int64
// TTL is the tier the entry is currently held at and ExpiresAt when it would lapse if
// nothing touched it. Both describe the state entering the decision, not its outcome.
TTL TTL
ExpiresAt int64
// Turn is how many requests this conversation has served so far, including this one.
Turn int
// StopReason is the request just served's own terminal stop reason — present tense,
// not a prediction: it belongs to the request that already happened, the same
// footing as CachedTokens or SinceLastMs. See StopReasonCluster/ClusterOf.
StopReason string
// Stats is the historical view, or nil where a caller has none. Every number it serves
// is accumulated from gaps that closed strictly before Now.
Stats Stats
// Pricing is the model's rates, so a strategy can compare what an action costs with
// what it might avoid rather than acting on a token count alone.
Pricing Pricing
// Load is system-load information where the deployment has it, nil where it does not.
Load *Load
}
Observation is everything a strategy is allowed to see, and it is defined by what is ABSENT from it.
There is no next-request timestamp on it, no idle duration, and no field derived from either. That is not an oversight to be fixed by a future field — it is the invariant the whole simulator exists to hold, because a predictor that can see how long the gap turned out to be will "predict" it perfectly and every saving it reports will be unreachable in production. TestStrategiesCannotSeeTheFuture asserts it by handing every strategy an Observation whose future is a trap.
Everything here was knowable at Now: the request that has just been served, the state of the entry it leaves behind, the account's rates, and statistics accumulated from gaps that had already CLOSED.
type Observed ¶
type Observed struct {
// Fallback is the tier used where nothing was recorded.
Fallback TTL
// contains filtered or unexported fields
}
Observed replays THE POLICY THAT ACTUALLY RAN, reconstructed from each row's own recorded tier.
It is the arm that answers "is any of this better than what we already do", and it is the only strategy that reads a field of the request rather than deciding from the Observation — which is legitimate precisely because it is not predicting anything: the tier is a header the client already sent, i.e. a fact about the present request.
Where the tier could not be reconstructed (TTLSourceUnknown, which is every row written before the cache_ttl column existed) it falls back to Fallback and the simulator counts those decisions, so the arm's coverage is reportable rather than assumed. The default fallback is the provider's own default tier, because a request that reached a prompt-caching provider with breakpoints in it got 5 minutes whether or not we recorded the header.
func NewObserved ¶
NewObserved builds the arm from the dataset. Reading the tiers from the rows here, once, keeps Observation free of a field only one strategy could use.
func (*Observed) Covered ¶
Covered reports how many of the arm's decisions rested on a recorded tier.
func (*Observed) Decide ¶
func (o *Observed) Decide(ob Observation) Action
Decide reads the tier recorded on the request being served, by its Observation.RequestID.
type Optimal ¶
type Optimal struct {
// contains filtered or unexported fields
}
Optimal is the cheapest action sequence that exists, and it is a BOUND, not a policy.
Why a dynamic program and not a greedy rule ¶
The action chosen at turn t decides two things at once: whether turn t itself may READ from cache (ActionExpire writes no cache_control, so the whole prefix is billed as fresh input however warm the entry was) and whether turn t+1 hits. A rule that looks only at the gap ahead therefore gets the current turn wrong. The first version of this in the offline evaluator was exactly that greedy rule, and it scored BELOW a plain keep-alive — which is impossible for a ceiling, and is how the error was caught.
The exact optimum is cheap because the state is small. Everything about the entry entering turn t — its size, its tier, its deadline, the keep-alives that fired during the span — is a function of the PREVIOUS action alone, given the two rows' timestamps. So the cost decomposes as a sum of f(action[t-1], action[t]) along the chain and one Viterbi pass per trajectory settles it: len(Actions) states, len(Actions) transitions each, so O(len(Actions)^2 * n) — six actions today, and the bookkeeping is linear (see back[] below).
Every surface that shows this must label it unreachable (see StrategySpec.Unreachable).
func NewOptimal ¶
NewOptimal solves each trajectory. Deterministic: the action order is the `Actions` slice, never a map range, so the same dataset yields the same plan twice.
func (*Optimal) Decide ¶
func (o *Optimal) Decide(ob Observation) Action
type Override ¶
type Override struct {
Input *float64 `json:"input,omitempty"`
Output *float64 `json:"output,omitempty"`
CacheRead *float64 `json:"cache_read,omitempty"`
Write5m *float64 `json:"write_5m,omitempty"`
Write1h *float64 `json:"write_1h,omitempty"`
PingInputTokens *int64 `json:"ping_input_tokens,omitempty"`
PingOutputTokens *int64 `json:"ping_output_tokens,omitempty"`
}
Override is one model's edited rates, as the page sends them back. Every field is a POINTER so that "not edited" and "edited to zero" are different facts: a rate of zero is a legitimate thing to experiment with, and a sentinel could not say so.
type PingBudgeter ¶ added in v0.2.0
type PingBudgeter interface {
// PingBudget is how many keep-alives to allow on the idle span starting at o.Now.
// Config.MaxPings still caps the result: this can ask for fewer, never for more.
PingBudget(o Observation) (budget int, ok bool)
}
PingBudgeter is an optional interface a Strategy may implement to choose the keep-alive budget per conversation instead of accepting Config.MaxPings for all of them.
The (value, ok) shape is Predictor's, for the same reason: a policy with no opinion on a particular observation must be able to say so and fall back, rather than return a zero that reads as "never ping". ok=false means "use Config.MaxPings", not "use 0".
type PingCapper ¶
type PingCapper interface {
PingCap() int
}
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 Predictor ¶
type Predictor interface {
ReuseProbability(o Observation, horizon time.Duration) (p float64, ok bool)
}
Predictor is the seam a LEARNED model plugs into.
It answers exactly the question a TTL decision needs — will this conversation come back within `horizon`? — and it receives the same Observation every strategy does, so a model trained on features the Observation does not carry cannot be wired in by accident. A predictor that has no opinion returns ok=false and Custom falls back to its thresholds.
Nothing in the simulator or the dashboard needs to change to adopt one: build a Custom{Predictor: yourModel} and it appears beside the hand-written strategies with the same costs, the same baseline and the same savings arithmetic.
type PriceList ¶
type PriceList struct {
Multipliers Multipliers `json:"multipliers"`
Models []Pricing `json:"models"`
// contains filtered or unexported fields
}
PriceList is the whole priced surface of one analysis: a row per model in the window, plus the multipliers the derived rates came from. This is what the page renders in its pricing panel and what it posts back edited.
func NewPriceList ¶
func NewPriceList(ctx context.Context, models []string, p modelinfo.Pricer, m Multipliers, overrides map[string]Override) *PriceList
NewPriceList builds the list for a set of models from a Pricer, then applies overrides.
models is used as given (deduped and sorted) so a model with no rates still gets a ROW — saying "this model has no rates" is the answer, and omitting it would leave the reader unable to tell an unpriced model from one that has no traffic.
overrides[OverrideAll] is applied to every row first, then the row's own entry, so a per-model rate always wins over a blanket one.
type Pricing ¶
type Pricing struct {
Model string `json:"model"`
// Input is fresh, uncached input. Output is completion. CacheRead is a cache hit.
Input float64 `json:"input"`
Output float64 `json:"output"`
CacheRead float64 `json:"cache_read"`
// Write5m and Write1h are the two cache-CREATION rates.
Write5m float64 `json:"write_5m"`
Write1h float64 `json:"write_1h"`
// PingInputTokens and PingOutputTokens are the request overhead a keep-alive ping
// cannot avoid: the fresh input it must carry past the cached prefix, and the smallest
// generation the provider will accept.
//
// A ping's job is to touch the cached prefix and generate nothing. Where a provider
// accepts a zero-generation request that is free; where it does not — Anthropic's
// Messages API requires max_tokens >= 1 — the smallest supported request still bills
// one output token, and the assumption is EXPOSED rather than rounded to zero. See
// Semantics.ZeroGeneration.
PingInputTokens int64 `json:"ping_input_tokens"`
PingOutputTokens int64 `json:"ping_output_tokens"`
// Source names where these rates came from, so nobody reads a typed number as a
// configured one: SourcePriceList (the deployment's own price list answered),
// "override" (edited in the page), or "" when the model has no rates at all.
Source string `json:"source"`
// Known is false when the model has NO rates. Then every dollar figure derived from it
// is absent rather than zero — an unpriced model is not a free one, and this project has
// shipped that particular lie five times.
Known bool `json:"known"`
}
Pricing is one model's rates for the SIX things a prompt-cache policy can spend money on, plus the two assumptions a keep-alive ping forces anyone to state out loud.
Why this is not modelinfo.Price ¶
modelinfo.Price is what the operator's price list and the public map publish: four tiers (input, output, cache read, cache creation). A TTL strategy needs two creation rates, because a 1-hour write is 2.0x base input where a 5-minute write is 1.25x, and pricing one as the other understates a 1h request by 0.75x of its whole written prefix. No gateway publishes a second creation rate, so Write1h is DERIVED from the documented multiplier — and the multiplier is a field, not a literal, so an operator whose provider charges differently can say so.
Nothing here is hardcoded in a UI component ¶
Every rate on this struct is served to the page and editable in it, and every edit comes back as an override that lands here. The page renders what it was given; it never carries a rate of its own. That is the same rule the keep-alive tab keeps, for the same reason: the browser has twice duplicated a table the server owns and drifted from it.
func FromPrice ¶
FromPrice derives a model's six rates from whatever the deployment's Pricer published.
Only Write1h is ever invented, and only from the multiplier: it is the one rate no gateway publishes. The rest are passed through untouched, so an operator price list that disagrees with the public map wins — which is the whole reason internal/modelinfo.Table exists.
A Price with no rates at all yields Known=false, and every dollar figure downstream is then omitted rather than computed as zero.
func (Pricing) HoldCost ¶
HoldCost is what it costs to hold a prefix of `cached` tokens at `tier` from nothing: the creation of the entry, plus `pings` keep-alives to carry it further.
This is the figure the pricing panel shows beside each configured rate — "what would another five minutes of this cost me, and what would another hour" — so the reader sees a dollar amount on their own median prefix rather than a per-token rate to multiply in their head. pings=0 is the plain write.
func (Pricing) KeepAliveCost ¶
KeepAliveCost is what ONE keep-alive costs on a prefix of `cached` tokens.
keep_alive_cost = cached×cache_read_rate + ping_input×input_rate + ping_output×output_rate
It is the same arithmetic whether the entry is held at five minutes or at an hour — a refresh is a cache read at 0.1x either way — and that is worth saying out loud, because the obvious guess is that a "1-hour ping" costs more. The difference between a 5-minute and a 1-hour keep-alive is not the price of one ping. It is (a) the CREATION tier that had to be paid to put the entry there, 1.25x against 2.0x of base input, and (b) how OFTEN a ping is needed: a five-minute entry has to be touched roughly twelve times as often as a one-hour one to be held for the same wall-clock span. Charging two different per-ping rates would be inventing a price no provider publishes.
func (Pricing) RecreateCost ¶
RecreateCost is what a keep-alive costs when it arrives TOO LATE: the entry has already lapsed, so the "refresh" is a cache write, at 12.5x a read for the 5-minute tier and 20x for the one-hour tier.
recreate_cost = cached×write_rate(tier) + ping_input×input_rate + ping_output×output_rate
This is the pathology of a schedule whose interval exceeds the lifetime it is protecting, and pricing it as a read is the arithmetic error that would hide it completely.
func (Pricing) RequestCost ¶
RequestCost prices one request's four billed tiers at a chosen write tier.
request_cost = input×input_rate + read×cache_read_rate + write×write_rate(tier) + output×output_rate
The write rate is the tier's, never a blend: that is the whole reason Pricing carries two.
func (Pricing) UncachedCost ¶
UncachedCost is the same prompt with no prompt cache at all: every prefix token billed as fresh input. The denominator of the "incremental cache premium", and the No-cache baseline's own arithmetic.
uncached_cost = (input + prefix)×input_rate + output×output_rate
type Replay ¶
type Replay struct {
// Label is the name results are grouped under. Defaults to "replay".
Label string
// Fallback is used for a request the list does not mention. ActionExpire by default,
// because it is the arm that cannot flatter anything.
Fallback Action
// contains filtered or unexported fields
}
Replay scores an action list decided somewhere else.
This is how a policy that this package cannot run gets compared on equal terms: an offline learned predictor (deploy/harbor/kv_ttl_survival_predictor.py drives one), a hand-written experiment, or a recorded production decision. It receives the same replay, the same rates, the same baseline and the same savings arithmetic as every built-in arm, which is the whole point — an evaluation whose scorer differs from the product's is not an evaluation of the product.
func (*Replay) Decide ¶
func (r *Replay) Decide(o Observation) Action
Decide reads the supplied action for the request being served.
func (*Replay) Unanswered ¶
Unanswered is how many requests the list did not mention. Reported rather than silently defaulted: an action list that covers half the window is not a policy, and a total that hid the fact would be the flattering half of one.
type Request ¶
type Request struct {
// Identity. User is the owning tenant and ConversationID the session/trajectory.
ID int64 `json:"id"`
User string `json:"user"`
ConversationID string `json:"conversation_id"`
ThreadID string `json:"-"` // the request's thread within its session ("" = the main thread, or recorded before threads)
TS int64 `json:"ts"` // epoch ms, UTC
HourUTC int `json:"hour_utc"`
Bucket Bucket `json:"bucket"`
Model string `json:"model"`
Provider string `json:"provider"`
Agent string `json:"agent"`
// The billed token tiers, exactly as the provider reported them.
InputTokens int64 `json:"input_tokens"` // fresh, uncached input
OutputTokens int64 `json:"output_tokens"`
CacheRead int64 `json:"cache_read_tokens"`
CacheWrite int64 `json:"cache_write_tokens"`
// CacheWrite1h is the part of CacheWrite the provider billed at the one-hour tier. It
// is the ONLY evidence that a requested 1h was honoured rather than silently
// downgraded, which on this gateway depends on the model.
CacheWrite1h int64 `json:"cache_write_1h_tokens"`
// CachedContext is the billed prefix: read + write. The size of the entry that exists
// after this request, and the number every ping and every re-creation is priced on.
// NOT tokens_before, which is message text only and runs a median 3.4x low.
CachedContext int64 `json:"cached_context_tokens"`
// TTL is the tier this request asked for, and TTLSource says how that was known:
// "configured" when the row recorded its own cache_ttl, "observed" when the tier was
// reconstructed from the provider's 1h write counter on a row written before that
// column existed, "unknown" when neither could answer. A page that cannot tell those
// apart reports "everything is 5m" over history that recorded no tier at all.
TTL TTL `json:"ttl"`
TTLSource string `json:"ttl_source"`
// Hit is whether the provider served this request's prefix from cache, and MissReason
// its own classification (cold_start|ttl_expiry|prefix_change|unknown|hit).
Hit bool `json:"hit"`
MissReason string `json:"miss_reason"`
// StopReason is this request's own terminal stop reason
// (end_turn|tool_use|stop_sequence|max_tokens|...), the strongest single feature found
// for predicting whether the NEXT request in this conversation lands in the 5m-1h
// keep-alive band — see docs/results/kv-ttl-predictor-features.md and
// StopReasonCluster. Known at decision time (it belongs to the request just served,
// not a future one), so a Strategy may read it from Observation with no future leakage.
StopReason string `json:"stop_reason"`
// The derived half. NextTS is the next request IN THE SAME CONVERSATION, chronologically;
// HasNext is false on the last request of a conversation and IdleMs is then nil.
NextTS int64 `json:"next_ts,omitempty"`
NextID int64 `json:"next_id,omitempty"`
HasNext bool `json:"has_next"`
IdleMs *int64 `json:"idle_ms"`
Within5m bool `json:"within_5m"`
Within1h bool `json:"within_1h"`
// UpstreamMs is how long the provider took, in milliseconds. 0 means NOT RECORDED, and
// the latency differential below skips such rows rather than averaging a zero in. It is
// the only field here that is used for anything but money: a cache miss re-reads a whole
// prefix, and the window's own hit/miss means are what turns an avoided miss into an
// avoided delay.
UpstreamMs float64 `json:"upstream_ms"`
// CostUSD is what this request was billed, priced at write time from the rates that
// were in force. CostKnown is false where the row's token accounting was incomplete —
// then the cost is UNKNOWN, never zero.
CostUSD float64 `json:"cost_usd"`
CostKnown bool `json:"cost_known"`
// Rejected marks a row whose upstream status was not 2xx (or never reached upstream). The
// provider read no prefix for it, so a replay leaves the cache entry untouched.
Rejected bool `json:"-"`
// KeepAlive marks a row that IS a ping context-guru sent on its own initiative. Such
// rows are excluded from the dataset by default (they are not the user's traffic and
// they would break every idle gap they sit inside); the field is here so a caller that
// asks for them can see which ones they are.
KeepAlive bool `json:"keepalive,omitempty"`
}
Request is one historical request as the analysis dataset sees it: what was billed, what tier it asked for, and — derived, never stored — when the same conversation came back.
The JSON names are the wire contract of /api/kvcache/rows. Idle is a POINTER: a request with no successor has no idle time, and 0 would read as "it came back instantly", which is the single most misleading value this dataset could carry. `null` is the only honest encoding, and HasNext is the flag a filter uses so nobody has to test a pointer.
type Result ¶
type Result struct {
Strategy string `json:"strategy"`
Description string `json:"description,omitempty"`
Requests int64 `json:"requests"`
Conversations int64 `json:"conversations"`
// NoOps is requests the replay did not touch the cache for: no token accounting and nothing
// cached (a 4xx/5xx the provider rejected before it read a prefix). They bill nothing and
// leave the provider's entry exactly as it was, so replaying them as a cache event ("this
// request cached 0 tokens") erased a live entry and billed the next request a full rewrite.
// On the production snapshot that was +$1.0k (2.7%) of the fixed-5m replay's gap to the bill.
NoOps int64 `json:"-"` // not on the wire: wire_test.go pins the key set
// The cost decomposition. TotalUSD is their sum and is the figure a comparison uses.
TotalUSD float64 `json:"total_usd"`
FreshInputUSD float64 `json:"fresh_input_usd"`
CacheReadUSD float64 `json:"cache_read_usd"`
CacheWriteUSD float64 `json:"cache_write_usd"`
OutputUSD float64 `json:"output_usd"`
PingUSD float64 `json:"ping_usd"`
// UncachedUSD is the same traffic with no prompt cache at all. TotalUSD − UncachedUSD is
// the INCREMENTAL CACHE PREMIUM: what the caching machinery itself cost or earned,
// separate from the bill it sits inside. Negative means the cache paid for itself.
UncachedUSD float64 `json:"uncached_usd"`
CachePremium float64 `json:"cache_premium_usd"`
Hits int64 `json:"hits"`
Misses int64 `json:"misses"`
HitRate float64 `json:"hit_rate_pct"`
// MissRate is reported as well as HitRate rather than left to the reader's subtraction,
// because Unpriced rows are in neither and the two would not sum to 100 for a reader who
// assumed they did.
MissRate float64 `json:"miss_rate_pct"`
// ForcedMisses are the rows whose own recorded reason (prefix_change, cold_start) no TTL
// policy could have rescued. The ceiling on every arm, reported so it is not implied.
ForcedMisses int64 `json:"forced_misses"`
Pings int64 `json:"pings"`
PingsThatRewrote int64 `json:"pings_that_rewrote"`
// PingsThatUpgraded are keep-alives that DELIBERATELY paid a longer tier's creation
// rate to extend a LIVE entry — ActionWrite5mPing1h's whole mechanism. Counted apart from
// PingsThatRewrote because the two mean opposite things: one is a policy buying a hold it
// chose, the other is a schedule repairing damage it caused. One counter for both would
// make a working arm and a broken one look identical.
PingsThatUpgraded int64 `json:"pings_that_upgraded"`
// PingsOnOpenSpans are pings billed into an idle span whose end is unknown, bounded by
// Config.WindowEnd. Counted apart because they rest on an assumption the closed spans
// do not need.
PingsOnOpenSpans int64 `json:"pings_on_open_spans"`
Writes5m int64 `json:"writes_5m"`
Writes1h int64 `json:"writes_1h"`
Expires int64 `json:"expires"`
// AvoidedRecomputations is the simulated hits, and AvoidedTokens the prefix tokens they
// served from cache instead of re-creating.
AvoidedRecomputations int64 `json:"avoided_recomputations"`
AvoidedTokens int64 `json:"avoided_tokens"`
// RetainedMs is the UNION of the intervals during which this strategy held a live cache
// entry, summed over conversations and clipped to the window. A union rather than a sum
// of lifetimes: overlapping refreshes would otherwise count the same second twice.
RetainedMs int64 `json:"retained_ms"`
// Unpriced is requests whose model has no rates. They are counted in Requests and in the
// hit/miss split, and contribute NOTHING to any dollar figure — an unpriced request is
// not a free one.
Unpriced int64 `json:"unpriced"`
// Valued is whether ANY of these requests could be priced at all.
//
// False means every dollar figure on this Result is zero because nothing had RATES — not
// because nothing was spent. Derivable from Unpriced == Requests, and stated anyway,
// because a consumer that has to derive it is a consumer that will forget to: the price
// map is fetched in the background, so the first load after a restart genuinely has no
// rates for a few seconds, and in that window every arm costs 0.00 and the exact ceiling
// degenerates to "never cache anything, 0%% hit rate" — a fabricated recommendation
// rendered in the style reserved for the cheapest plan that exists.
//
// Nothing here refuses to produce a plan when it cannot price one; refusing would trade a
// misleading answer for a missing panel, and the caller is better placed to choose. What
// this guarantees is that the caller cannot MISS the condition. Anything that renders a
// cost, a saving or a ceiling must check it first.
Valued bool `json:"valued"`
// Decisions counts each action the strategy chose.
Decisions map[Action]int64 `json:"decisions"`
// StatsLevels counts which fallback level the account's own statistics could answer at,
// at each decision instant. How much of an arm was actually personalised, rather than
// decided on the service-wide average.
StatsLevels map[string]int64 `json:"stats_levels"`
// ObservedCoverage is how many decisions the observed-policy arm could base on a
// RECORDED tier. Absent (nil) for every other arm.
ObservedCoverage *Coverage `json:"observed_coverage,omitempty"`
ByUser []Group `json:"by_user"`
ByModel []Group `json:"by_model"`
Latency Latency `json:"latency"`
}
Result is one strategy's whole replay.
type ReuseCategory ¶ added in v0.3.1
type ReuseCategory struct {
Name string
Levels []ReuseLevel
}
ReuseCategory is one one-hot feature and its levels.
type ReuseLevel ¶ added in v0.3.1
ReuseLevel is one one-hot level's coefficient. The empty Level is the CATCH-ALL: a level the fit never saw scores as that rather than as zero, because zero is not "unknown" — it is "exactly the reference level", which is a different and much stronger claim.
type ReuseModel ¶ added in v0.3.1
type ReuseModel struct {
// Version and TrainedOn are provenance, and they are on the type rather than only in a
// comment so that a result can carry them: a saving attributed to "the model" is not
// checkable unless the reader can tell WHICH model produced it.
Version string
TrainedOn string
// IntervalS, LifeS and MaxK are the schedule the model was FITTED on. The grid the
// conditionals live on is a property of the fit, not of the caller — see grid().
IntervalS float64
LifeS float64
MaxK int
Intercept float64
Numeric []ReuseTerm
Categorical []ReuseCategory
}
ReuseModel is a frozen discrete-time survival model over the keep-alive sweep grid.
Immutable after construction and safe for concurrent use: every method takes the model by pointer but writes nothing through it, which matters because one *ReuseModel is shared by every dashboard request and every live ping sweep.
func (*ReuseModel) Describe ¶ added in v0.3.1
func (m *ReuseModel) Describe() string
Describe is the one-sentence provenance a result carries beside the arm's numbers.
func (*ReuseModel) ReuseProbability ¶ added in v0.3.1
func (m *ReuseModel) ReuseProbability(o Observation, horizon time.Duration) (float64, bool)
ReuseProbability implements Predictor: P(this conversation has returned within horizon).
CUMULATIVE, as the interface promises, composed forwards from the fitted conditionals:
F(t_(j+1)) = 1 - prod_(i<=j) s_i
on the grid {t_j} u {t_j + life}, linearly interpolated between knots and CLAMPED outside it. Two properties of that are worth stating because BudgetPolicy depends on both:
- F(t_1) = 0 by construction. This CDF is already conditioned on having reached the first sweep, which is exactly the population `Windows` divides by — so the conditioning is not applied twice.
- the grid is the FIT's, not the caller's. A caller replaying on a different interval gets the model's own knots interpolated to its horizons rather than a silent re-fit, which is the honest failure mode: the numbers degrade visibly instead of the model pretending to have been trained on a schedule it was not.
ok is false only when there is no model to consult. Everything else a decision needs to be refused — unknown rates, no prefix, a schedule the arm cannot price — is BudgetPolicy's own business and is already checked there; duplicating it here would put the same policy in two places and let them disagree.
func (*ReuseModel) Validate ¶ added in v0.3.1
func (m *ReuseModel) Validate() error
Validate refuses a model this code cannot evaluate exactly.
It exists because the failure it prevents is silent. A generated table naming a feature this build does not implement would otherwise score that coefficient against zero, which is not an error and not a crash — it is a slightly different model, producing slightly different budgets, with nothing to notice. TestReuseModelV1IsValid calls this on the shipped table, so a re-fit that adds a feature fails the build's tests rather than the deployment.
type ReuseTerm ¶ added in v0.3.1
ReuseTerm is one numeric feature's coefficient and the standardisation the fit applied.
Center/Scale are on the wire because the coefficient is meaningless without them: the fit standardised every numeric column, so Go has to apply the identical transform or a coefficient of -1.0 means something different on each side. A Scale of 0 is read as 1, which is the same guard the fit applies — see the zero-variance note in the generated file.
type Savings ¶
type Savings struct {
Strategy string `json:"strategy"`
Baseline string `json:"baseline"`
// BaselineUSD and StrategyUSD are the two totals.
BaselineUSD float64 `json:"baseline_usd"`
StrategyUSD float64 `json:"strategy_usd"`
// AbsoluteUSD = baseline − strategy. NEGATIVE where the strategy costs more, and it is
// reported that way: clamping it to zero is how a comparison stops being one.
AbsoluteUSD float64 `json:"absolute_usd"`
// PercentUSD = absolute / baseline × 100, and Known is false when the baseline is zero —
// a percentage of nothing is not 0%, it is undefined.
PercentUSD float64 `json:"percent_usd"`
Known bool `json:"percent_known"`
// HitDelta is simulated hits gained (or lost) against the baseline.
HitDelta int64 `json:"hit_delta"`
// LatencyAvoidedMs is HitDelta × the window's own measured per-miss latency cost. Absent
// where that differential could not be measured.
LatencyAvoidedMs float64 `json:"latency_avoided_ms"`
LatencyKnown bool `json:"latency_known"`
}
Savings is one strategy against one baseline. Nothing here is clamped.
type Semantics ¶
type Semantics struct {
HitRefreshesTTL bool `json:"hit_refreshes_ttl"`
PingRefreshesTTL bool `json:"ping_refreshes_ttl"`
ZeroGeneration bool `json:"zero_generation"`
}
Semantics is the provider's cache behaviour, made explicit and configurable because it is not the same everywhere and because getting it wrong silently changes every result.
Anthropic's documented behaviour is the shipped default:
- "the cache is refreshed for no additional cost each time the cached content is used" — so a plain cache HIT resets the entry's lifetime. HitRefreshesTTL=true.
- a keep-alive read is just a use, so it refreshes the entry for its OWN tier's lifetime. PingRefreshesTTL=true.
- refreshing does not change the tier an entry was created at, so a refresh buys another lifetime OF THAT TIER — five minutes for a 5-minute entry, an hour for a one-hour one.
- max_tokens must be >= 1, so a ping cannot generate nothing. ZeroGeneration=false.
func DefaultSemantics ¶
func DefaultSemantics() Semantics
DefaultSemantics is Anthropic's documented behaviour.
type Stats ¶
type Stats interface {
// ReuseWithin is the share of this cell's already-closed gaps that were no longer than
// d. level is one of the Level* constants.
ReuseWithin(user, model string, b Bucket, d time.Duration) (p float64, n int, level string)
// MedianIdle is this cell's median already-closed gap.
MedianIdle(user, model string, b Bucket) (idle time.Duration, n int, level string)
}
Stats is the historical view a strategy may lean on, with an explicit FALLBACK LEVEL on every answer.
The level matters as much as the number: "62% of this user's afternoon gaps closed within five minutes, over 340 gaps" and "62%, over 3 gaps, actually the service-wide average because this user is new" are different facts, and a strategy that cannot tell them apart will act confidently on nothing. Every method therefore returns (value, n, level).
type StickySession1h ¶
type StickySession1h struct {
// contains filtered or unexported fields
}
StickySession1h commits ONCE PER CONVERSATION — at the first request it ever sees for a given (user, conversation, model) key — to holding that whole session at either the 1-hour tier or the 5-minute tier, and never revisits the choice afterward.
Why sticky, and not HistoricalProbability run every turn ¶
A session that switches tiers mid-stream is not something a real deployment can do faithfully: once a conversation has committed to a tier, the entry it is holding was created at that tier, and every later request in it can only ever be served against that same entry — there is no operation that downgrades or upgrades an existing hold in place. A strategy that re-decides on fresher statistics every turn is answering a question this deployment cannot actually act on. This arm is the one-shot decision that models that constraint: whatever it chooses at turn one is what every later turn in that conversation gets, however much the account's own statistics move in the meantime.
The decision itself ¶
It reuses the same write-versus-recreate comparison this repo already derives in two other places rather than inventing a third: components/reformat/cacheinject.go's own TTL doc comment ("only pays when p = P(gap > 5 min) exceeds (2.0-1.25)/(1.25-0.1) = 65.2%") and dash/kvcachesim.go's Raise5mTo1h/SavedPerMiss. Committing to the 1-hour tier costs (Write1h-Write5m) extra on THIS write; the 5-minute tier's alternative, if the gap turns out to exceed five minutes, is not a cheap read but a full RECREATE at the Write5m rate — so the per-token amount at stake is (Write5m-CacheRead), and the two ratios give a break-even probability rather than a hand-picked threshold:
breakeven = (Write1h - Write5m) / (Write5m - CacheRead)
The account's own P(return within 1h) — Stats.ReuseWithin at Horizon1h, with Stats's usual fallback ladder — is compared against it. Below minCell observations at every level (LevelNone) or with no priced rates, the decision defaults to the 5-minute tier: the least surprising action, and what the traffic would have got with no strategy in play at all.
func NewStickySession1h ¶
func NewStickySession1h() *StickySession1h
NewStickySession1h builds an arm with no sessions decided yet.
func (*StickySession1h) Decide ¶
func (s *StickySession1h) Decide(o Observation) Action
Decide looks up this conversation's standing commitment, making it now if this is the first request seen for the key — which, since Simulate never calls Decide out of chronological order, is exactly Observation.Turn == 1.
func (*StickySession1h) Describe ¶
func (s *StickySession1h) Describe() string
func (*StickySession1h) Name ¶
func (s *StickySession1h) Name() string
type StopReasonCluster ¶
type StopReasonCluster string
StopReasonCluster is the three-way split of Request.StopReason that docs/results/kv-ttl-predictor-features.md and kv-ttl-predictor-arms.md found: not every "the turn ended" reason predicts the same thing, and a naive two-way split ("did the turn end, yes/no") gets a third of the reasons backwards.
const ( // ClusterStillWorking is a request the agent is mid-loop after: tool_use, stop_sequence, // and their OpenAI-dialect equivalents. Measured band rate (the next request landing in // the 5m-1h keep-alive window): 0.0-0.6%, far under the ~8% one-ping break-even. ClusterStillWorking StopReasonCluster = "still_working" // ClusterLooksDoneIsnt is `stop`/unset: reads like end-of-turn and isn't one. Measured // band rate 2.9-6.1%, still under break-even. ClusterLooksDoneIsnt StopReasonCluster = "looks_done_isnt" // ClusterActuallyDone is end_turn, max_tokens, refusal: the turn is genuinely over. // Measured band rate 11.7-43.3%, clearing break-even with real margin — this is the // cluster proxy/keepalive.go's pingable() already keeps pinging on (commit 50e3966), // and StopReasonGated's whole job is excluding the other two. ClusterActuallyDone StopReasonCluster = "actually_done" )
func ClusterOf ¶
func ClusterOf(stopReason string) StopReasonCluster
ClusterOf classifies a stop_reason into its measured cluster.
type StopReasonGated ¶
type StopReasonGated struct{}
StopReasonGated writes the five-minute tier on every request, and pings while idle only when the request JUST SERVED — the one this decision is made after, present tense, not a prediction — has a stop_reason that clusters as ClusterActuallyDone.
Every one of the keep-alive arms above pings unconditionally: KeepAlive5m spends on tool_use/stop_sequence turns just as readily as on end_turn ones, even though docs/results/kv-ttl-predictor-features.md measured those turns landing in the addressable 5m-1h band only 0.0-0.6% of the time — 20x under the ~8% one-ping break-even. This arm is that gate, and nothing else: same tier, same schedule, the only difference is whether a ping fires at all on a given idle span.
It extends, rather than revisits, proxy/keepalive.go's pingable() and its own recorded decision (commit 50e3966) not to exclude end_turn from pinging — end_turn is exactly where this arm KEEPS pinging. What pingable() never finished is excluding the two low-value clusters (ClusterStillWorking and ClusterLooksDoneIsnt) it currently pings on too. Measured on the live deployment (kv_ttl_predictor_arms.py, docs/results/kv-ttl-predictor-arms.md): +1.54% vs fixed-5m pooled (CI95 [0.60%, 2.79%]), not statistically distinguishable from a trained logistic regression on the same window — the free rule, not the model, is the one worth shipping.
func (StopReasonGated) Decide ¶
func (StopReasonGated) Decide(o Observation) Action
func (StopReasonGated) Describe ¶
func (StopReasonGated) Describe() string
func (StopReasonGated) Name ¶
func (StopReasonGated) Name() string
func (StopReasonGated) PingCap ¶ added in v0.5.3
func (StopReasonGated) PingCap() int
PingCap implements PingCapper: the gate pings at most DefaultMaxPings times per span, the budget its live strategy runs (campaign.ArmFor's config.DefaultKeepAliveMaxPings). Without it a replay with a raised Config.MaxPings — a sweep that also scores many-ping arms — would score the gate at a budget it never runs with.
type Strategy ¶
type Strategy interface {
// Name is the label the dashboard groups results by. Stable, because it is a key.
Name() string
// Decide chooses the action for the idle span starting at o.Now.
Decide(o Observation) Action
}
Strategy is a KV-cache management policy: given only what was knowable at the decision instant, choose what to do with the cached context for the span that starts now.
Deliberately one method. A strategy that needs to learn from outcomes does so through Stats, which the simulator advances as gaps close — not through a callback the simulator would have to invoke with the future in hand.
func NewStrategy ¶
NewStrategy builds one arm by name.
reqs is required by the arms whose spec says NeedsDataset (they precompute a per-request answer over the whole set) and ignored by the rest. `replay` cannot be built here — it needs the action list itself — so it is an error, with the constructor named.
type StrategySpec ¶
type StrategySpec struct {
Name string `json:"name"`
Description string `json:"description"`
// Unreachable marks an arm that reads the FUTURE. It is a bound on what any policy could
// achieve, never a result, and every surface that shows it must say so — a ceiling
// rendered beside real arms in the same style is a promise the product cannot keep.
Unreachable bool `json:"unreachable"`
// NeedsDataset marks an arm that cannot be built from a name alone because it is
// constructed from the whole trajectory set (it precomputes a per-request answer).
NeedsDataset bool `json:"needs_dataset"`
// Baseline marks the arm that is the honest default denominator for a savings figure.
Baseline bool `json:"baseline,omitempty"`
// PartialReplayUnsafe marks an arm whose Strategy implementation commits ONCE for a whole
// conversation and never revisits the choice (see StickySession1h.committed), rather than
// deciding fresh from Observation on every call. Such an arm has no way to tell "the first
// row of this Simulate call" apart from "the conversation's true first turn" — Simulate
// itself makes no such promise (see its own doc comment: a caller may hand it any slice,
// in chronological order, and it is scored honestly as exactly that slice).
//
// A caller that replays ONE real conversation's requests across several DISJOINT Simulate
// calls — a per-account, per-hour-of-day sweep, for one — will see such an arm silently
// re-decide in every call it appears in, each time believing it is at turn one. That
// contradicts the arm's own documented guarantee (decide once, hold for the whole session)
// without erroring or even being visible in the result: the numbers are simply answering a
// different, less meaningful question than the one the arm's name and description promise.
// True only when the whole trajectory that arm cares about is guaranteed to be in the one
// Simulate call it is given — false (the default) for every arm that decides fresh from
// Observation and Stats alone, which cannot be broken by slicing.
PartialReplayUnsafe bool `json:"partial_replay_unsafe,omitempty"`
}
StrategySpec is one arm, as the API and the page should present it.
func Registry ¶
func Registry() []StrategySpec
Registry lists every arm, in presentation order. A copy, so a caller cannot reorder it.
type TTL ¶
type TTL string
TTL is a prompt-cache lifetime tier, spelled the way the provider's usage block spells it — the same vocabulary as the `cache_ttl` column, so a row's configured tier and a strategy's chosen tier are the same type and cannot be compared by accident.
The three tiers, and ” is a THIRD answer rather than a synonym for 5 minutes: a request carrying no cache_control at all is not a 5-minute request, and folding the two together is how a page comes to report that everything is cached.
func (TTL) Lifetime ¶
Lifetime is how long an entry at this tier survives without being touched. It is a function of the TIER only: the simulator replays Anthropic-style tiers, and an OpenAI thread has no tier (see modelinfo.CacheLifetime for the provider-aware rule).