Documentation
¶
Overview ¶
Package predictive is the learned keep-alive policy: from the facts known when a response ends it estimates P(this conversation returns inside each ping window) and picks how many keep-alive pings are worth buying. It is a small MLP (~6K parameters, a few seeds averaged) that outputs a censored mixture-of-Weibulls survival curve of the time-to-return, plus the economic rule on top of it:
k* = argmax_k lam*stake*(S(Tc) - S(k*x + Tc)) - pingCost * sum_{j<=k} S(j*x)
stake = prefix * (write5m - read) is what a rescued cache entry is worth. Training and the held-out comparison live in scripts/campaign; this package is inference only and costs microseconds.
Index ¶
- Constants
- Variables
- func FamilyOf(model string) string
- type Arrival
- type AutoFit
- type AutoGrid
- type AutoRow
- type Decision
- type Econ
- type Facts
- type LGB
- type MLP
- type Model
- type ModelRef
- type Plan
- type Policy
- type Request
- type Response
- type Row
- type Rule
- type SegRule
- type Segment
- type Spec
- type Tracker
Constants ¶
const ( NGBS = 72 GBSBase = NIn NAll = NIn + NGBS )
NGBS is len(GBSNames); GBSBase is where they start in Row.F.
const ( RuleModel = "model" // the predictor picks the number of pings per request RulePlan = "plan" // a fixed plan from the menu (uniform: Plan.GapsS[0] seconds apart, len(GapsS) pings) RuleNone = "none" // never ping )
Rule kinds a segment may name.
const NCat = 12
NCat is len(CatNames).
const (
NIn, H1, H2, NOut = 37, 48, 64, 10
)
Layer sizes of the exported network.
const SpecSchema = "cg.cache.campaign/2"
SpecSchema is the campaign document this package reads. v2 extends the v1 decision-tree campaign with a model reference: a campaign is an ordered list of segments, each naming the rule that decides for the requests it matches.
Variables ¶
var CatNames = [NCat]string{"family", "agent_type", "provider", "stop_reason", "thinking", "m_stop_reason", "m_prev_stop_reason", "m_model", "m_agent", "m_cache_ttl", "m_thinking", "m_effort"}
CatNames are the categorical GBS inputs; Row.Cat is indexed by position in this list.
var FeatureNames = [NIn]string{
"l_prefix", "l_out", "l_fresh", "cw_frac", "l_msgs", "l_tools", "l_turn", "l_sturn", "l_dur", "l_sage", "pg_first", "pg_pos", "pg_neg", "pg2",
"hs", "hc", "ds", "dc", "kv_p5", "kv_p1", "kv_ln", "gq_nan", "l_gq", "think", "stream", "l_ping",
"sr_tool_use", "sr_stop_sequence", "sr_end_turn", "sr_stop", "sr_tool_calls", "fam_opus", "fam_sonnet", "fam_haiku",
"ag_claude-cli", "ag_openai", "ag_asyncopenai",
}
FeatureNames is the model's input vector, in order. Every one is a function of what the proxy has seen by the time a response ends: that response's own sizes and stop reason, the idle gaps this thread and tenant have ALREADY closed, and counters of its own traffic.
var GBSNames = [NGBS]string{
"messages", "tools", "system_blocks", "stream", "session_turn", "turn_in_thread", "hour_utc", "dow", "prefix_tok", "output_tok", "read_cost", "rebuild_cost", "ping_cost", "cost_usd", "fresh_input",
"stake", "ping_over_stake", "family", "agent_type", "provider", "stop_reason", "thinking",
"m_n_req_thread", "m_n_req_session", "m_session_age_s", "m_thread_age_s", "m_ctx_tokens", "m_ctx_window", "m_ctx_fill", "m_cache_read_ratio", "m_cache_write_ratio", "m_fresh_ratio",
"m_rewrite", "m_rewrites_last5", "m_reqs_since_rewrite", "m_ctx_growth", "m_ctx_growth_ratio", "m_gap1", "m_gap2", "m_gap3", "m_gap_mean5", "m_gap_median5", "m_gap_std5", "m_gap_max10",
"m_gap_trend5", "m_gap_ewma", "m_is_user_turn", "m_since_user_turn_s", "m_tool_streak", "m_reqs_since_user_turn", "m_messages", "m_messages_delta", "m_reqs_since_compaction", "m_compactions",
"m_stop_reason", "m_prev_stop_reason", "m_model", "m_agent", "m_cache_ttl", "m_tools", "m_system_blocks", "m_out_tokens", "m_out_ratio", "m_resp_s", "m_ttfb_s", "m_resp_mean5", "m_thinking",
"m_effort", "m_max_tokens", "m_status_ok", "m_cost_req", "m_cost_session_cum",
}
GBSNames are the 72 inputs of the LightGBM discrete-time hazard, in training order (scripts/campaign/gbsfeat.py NAMES): 22 request columns and 50 thread / session features. Categorical ones are strings in Row.Cat and are coded by the model with its own table.
Functions ¶
Types ¶
type Arrival ¶
type Arrival struct {
// contains filtered or unexported fields
}
Arrival is the state a request carries from its start to its end: everything that depends on what came BEFORE it.
type AutoFit ¶
type AutoFit struct {
HalfLifeDays float64 // +Inf = no decay
Kappa float64 // +Inf = the fleet plan for everyone
FleetPlan int
Plan map[string]int // per scope; a scope with no rows is not listed and gets FleetPlan
Weight map[string]float64 // recency-weighted rows behind each scope's choice
}
AutoFit is the tuner's answer.
type AutoGrid ¶
type AutoGrid struct {
Kappas []float64 // pseudo-rows of the fleet prior; +Inf = the fleet plan for everyone
HalfLivesDays []float64 // recency half-life of a row's weight; +Inf = no decay
InnerFrac float64 // the inner split point of the training rows
}
AutoGrid is what the tuner may choose from. Zero values take the defaults below.
type AutoRow ¶
AutoRow is one decision point: whose it is, when its response ended, and the net $ of each menu plan on it (Gain[0] = never ping = 0).
type Decision ¶
type Decision struct {
K int // pings to buy, 0 = let it lapse
PWindow float64 // P(return inside the window the K pings cover), 0 when K == 0
S295 float64 // P(still no return when the cache lifetime ends)
}
Decision is the model's answer for one decision point.
func Decide ¶
Decide applies the economic rule to one decision point: the number of pings k in 0..kmax that maximises
sum_{j<=k} stake*(S(x(j-1)+Tc) - S(xj+Tc)) - lam*pingCost*S(xj)
(the j-th ping is paid only if the conversation has not returned by xj and rescues a return in the window it opens). Ties keep fewer pings.
type Econ ¶
type Econ struct {
PrefixTok float64
PWrite5m, PRead float64 // $ per token
PingCost float64 // $ per ping
}
Econ is the money side of one decision: what the entry is worth and what a ping costs.
type Facts ¶
type Facts struct {
Family, StopReason, Model, Agent string
PrefixTok, PingCost float64
SessionTurn float64
// HourUTC (0-23) and DowUTC (0 = Sunday) are the request's start, UTC: per-time segments test them.
HourUTC, DowUTC float64
}
Facts are the per-request values a segment predicate may test.
type LGB ¶
type LGB struct {
// contains filtered or unexported fields
}
LGB is a LightGBM discrete-time hazard model: the time to return is cut into bins at Edges; for every bin a gradient-boosted classifier gives the hazard h_b = P(return in bin b | not returned before it) from the 72 request inputs plus the bin and its right edge. S(edge_b) = prod_{i<=b} (1 - h_i). Trees are exported from LightGBM as flat node arrays; evaluation is the same arithmetic LightGBM's predict does (split on <=, NaN / zero routed by the stored default direction).
type MLP ¶
type MLP struct {
Features []string
// contains filtered or unexported fields
}
MLP is the Weibull-mixture network. Safe for concurrent use.
func (*MLP) Standardize ¶
Standardize writes (raw - mu) / sd into x.
type Model ¶
type Model interface {
Kind() string
Rule() Rule
// Survival writes S(t) for every t in ts into out (len(out) >= len(ts)).
Survival(row *Row, ts []float64, out []float64)
}
Model is a pluggable time-to-return predictor: it turns one Row of live features into the survival curve S(t) = P(no return by t seconds). The economic rule (Decide) is model independent. To add a model: implement this, register its "kind" in ParseModel, and have it read the inputs it needs from Row (the research feature blocks are documented in features.go and gbsfeatures.go).
func ParseModel ¶
ParseModel loads a model document, dispatching on its "kind".
type ModelRef ¶
type ModelRef struct {
Ref string `json:"ref"`
SHA256 string `json:"sha256"`
Schema string `json:"schema"`
Kind string `json:"kind"`
Features int `json:"n_features"`
Rule Rule `json:"rule"`
}
ModelRef points at the predictor file next to the spec.
type Plan ¶
type Plan struct {
GapsS []float64 `json:"gaps_s"`
MaxPings int `json:"max_pings"`
Tier string `json:"tier"`
}
Plan is a menu entry.
type Policy ¶
type Policy struct {
Kind string `json:"kind"` // "rules" (no model) or "model+segments"
Model *ModelRef `json:"model,omitempty"`
Segments []Segment `json:"segments"`
Fallback SegRule `json:"fallback"`
}
Policy is the executable part of a campaign.
type Response ¶
type Response struct {
Request
EndMs, DecMs int64 // provider-side response end, and when the proxy finished returning it (>= EndMs)
Provider, CacheTTL, Effort string // request facts: serving provider, cache tier asked for ("ephemeral_5m", ...), reasoning effort
MaxTokens, SystemBlocks int
TTFBMs, UpstreamMs, CostUSD float64 // time to first byte, upstream duration, billed cost of this request
Prefix, CacheWrite, Fresh, Output int64
Messages, Tools int
StopReason, Agent, Thinking string // Agent: the dash agent family ("claude-cli", "openai", ...)
Stream bool
PIn, POut, PRead, PWrite5m float64
}
Response is what it knows when that request's response has ENDED. Prices are $ per token. The request's own start time is the one the Arrival carries (Request.TsMs here is ignored).
type Row ¶
type Row struct {
F []float64
Cat [NCat]string
Ctx float64
ModelName string
// Skipped is true when, within the last 10 requests of the thread, an earlier request had not finished when this one's features were taken (parallel
// requests on one thread): the response-dependent history inputs then come from the last finished request and can differ from the offline definition.
Skipped bool
}
Row is every live input for one decision point. F[:NIn] is the MLP block; F[GBSBase:] the GBS block (categorical slots NaN, see Cat). Ctx and ModelName let a model derive the two inputs that depend on its own training table (served context window).
type Rule ¶
type Rule struct {
Lam float64 `json:"lam"`
XS float64 `json:"x_s"` // seconds between pings
KMax int `json:"kmax"` // most pings ever bought
TCS float64 `json:"tc_s"` // the provider's cache lifetime, seconds
}
Rule is the economic decision rule's constants, exported with the model.
type SegRule ¶
type SegRule struct {
Kind string `json:"kind"`
Plan string `json:"plan,omitempty"`
// Lam optionally rescales the model's value of a rescue for this segment (default 1).
Lam float64 `json:"lam,omitempty"`
}
SegRule is the rule one segment applies.
type Segment ¶
type Segment struct {
ID string `json:"id"`
When [][3]any `json:"when"`
Rule SegRule `json:"rule"`
Raw map[string]any `json:"-"`
}
Segment applies Rule to the requests where every predicate in When holds. When is a list of [fact, op, value] triples.
type Spec ¶
type Spec struct {
Schema string `json:"schema"`
Version string `json:"version"`
Policy Policy `json:"policy"`
Menu map[string]Plan `json:"menu"`
}
Spec is the campaign document. Only the fields a runtime needs are typed; the rest (evidence, caveats, ...) is kept verbatim in Extra for the API to return.
type Tracker ¶
type Tracker struct {
// contains filtered or unexported fields
}
Tracker accumulates, per campaign scope, the causal history the features need. All state is bounded: idle threads and sessions are dropped after six hours.
func (*Tracker) Arrive ¶
Arrive registers a request that is starting. Call it once per request, in start order; keep the result for Features.
func (*Tracker) Ended ¶
Ended records that a response has finished, at its provider-side end: from now on a request that starts on the same thread closes this request's gap. A successor that already started (we were told late) closes it at once.