Documentation
¶
Overview ¶
Package campaign holds the keep-alive campaign math that every host shares: the closed-form replay of a ping plan, the calibrated constants, the fidelity model behind the adapt report, the ship gate, the auto builder's spec, and the mapping of a suggest arm to a live strategy.
A host (the proxy, Cortex) reads history and traffic, calls these functions, and keeps the transport, the files and the HTTP views. Nothing here imports a host package.
Index ¶
- Constants
- Variables
- func Apply(pol keepalive.Policy, k int, active bool) keepalive.Policy
- func ArmEnforceable(arm string) bool
- func BuildSpec(rows []predictive.AutoRow, facts []RowFacts, tenant string, since, until int64, ...) (spec map[string]any, rec string)
- func CellOutcome(cell Cell, honorsHeadTTL1h func(tenantID string) bool) (activatable bool, skipReason string)
- func Choose(spec *predictive.Spec, model predictive.Model, row *predictive.Row, ...) (k int, idleS float64)
- func DefaultWeekdays() []time.Weekday
- func FidMiss(model string) float64
- func ForcePolicy(spec map[string]any) bool
- func HeadTTL1hHonored(model string) bool
- func HonorsHeadTTL1h(models []string) bool
- func MarkOverlaps(resolved []*Resolved, owners []tenant.CampaignCellOwner)
- func NewFacts(model, stop, agent string, prefix int64, pingCost float64, hourUTC, dowUTC int) predictive.Facts
- func PlanName(k int) string
- func PlanOutcome(k int, x, u, gap float64, returned bool, stop float64) (fired int, rescued bool)
- func Priced(pRead, pWrite float64) bool
- func RowFloor(pol keepalive.Policy, f *RowFacts) int
- func SegmentOf(segBy string) func(f *RowFacts) (key string, when []any)
- func SessionCI(v []float64, sess []string, seed int64) [2]float64
- func ShipGate(subject []float64, legs []GateLeg, sess []string) (pass bool, failed []string)
- func Stake(prefix int64, pRead, pWrite float64) float64
- func StrategyForGroup(campaignName string, g *Group, days []time.Weekday) tenant.Strategy
- func SumOf(v []float64) float64
- func TileHours(hours []int, days []time.Weekday) []tenant.Window
- func WeekdaysFromNames(names []string) []time.Weekday
- type Active
- type Arm
- type Cell
- type EvalResult
- type FidParams
- type GateLeg
- type Group
- type Option
- type Pick
- type Picker
- type Plan
- type Resolved
- type RowFacts
- func (f *RowFacts) DefaultK() int
- func (f *RowFacts) Expected(k int, x float64, sessionEnd bool, p *FidParams) (rescue, ping, pings, rescues float64)
- func (f *RowFacts) Facts() predictive.Facts
- func (f *RowFacts) Gain(k int, x float64, sessionEnd bool, bScale, pScale float64) float64
- func (f *RowFacts) Outcome(k int, x float64, sessionEnd bool) (fired int, rescued bool)
- type Score
- type Tally
Constants ¶
const ( Cliff = 296.5 Late = 1.0 PingDur = 2.0 )
The closed-form replay constants of scripts/campaign/cgpredict.py (plan_eval): the provider cliff, the scheduling lateness and a ping's duration, in seconds.
const ( BenefitScale = 0.948 PingScale = 1.346 )
BenefitScale and PingScale are scripts/campaign/engine_calibration.json (benefit_scale, ping_scale); a test keeps them equal. They calibrate the closed form to the pinned replay engine.
const ( // AutoK is the highest ping count of the auto builder's menu. AutoK = 6 // AutoX is the menu spacing. 240 s, not 280: live, pings 275-280 s after a response end miss the provider's cache 19% of the time, // and 240 s also leaves room for a ping's 60 s timeout inside the 5-minute cache (#707, #716). It is the shipped default idle. AutoX = config.DefaultKeepAliveIdle )
const (
FidPFirst = 0.0089 // P(a first ping rewrites instead of refreshing)
)
Variables ¶
var AutoMinTst, AutoMinSes = 500, 20
The evidence floors of a build: held-out rows and sessions (the same floors as scripts/campaign/build_campaign.py). Variables only so tests can run the whole build on a small fixture.
Functions ¶
func Apply ¶
Apply writes an ACTIVE campaign's decision (k pings) into the entry's policy. Account-level bounds (the per-ping dollar ceiling) are left alone. A campaign that is not active (shadow, off, or the tenant opted out) leaves the policy as it is.
func ArmEnforceable ¶
ArmEnforceable reports whether a campaign can enforce arm on live traffic at all. A cell can still be skipped for its own reasons (too few requests, unpriced rows, a 1h-tier arm on a model that does not honor it): CellOutcome answers that.
func BuildSpec ¶
func BuildSpec(rows []predictive.AutoRow, facts []RowFacts, tenant string, since, until int64, sessionEnd bool, segBy string) (spec map[string]any, rec string)
BuildSpec builds the campaign document for one tenant from the fleet's rows. It is the whole build; the host only does the I/O around it. facts (same order as rows) add the shipped default to the gate and are needed for segBy: facts may be nil only when segBy is empty.
func CellOutcome ¶
func CellOutcome(cell Cell, honorsHeadTTL1h func(tenantID string) bool) (activatable bool, skipReason string)
CellOutcome is what creating a campaign would do with one uploaded suggest cell: activate it (or keep it on a baseline arm), or record it with skipReason. honorsHeadTTL1h reports whether a tenant's traffic honors the 1h cache tier. It is the SAME decision a host's campaign create makes, so an offline tool that builds an upload file reports it without a second copy of the rules.
func Choose ¶
func Choose(spec *predictive.Spec, model predictive.Model, row *predictive.Row, facts *predictive.Facts, econ predictive.Econ) (k int, idleS float64)
Choose is the ping count and the spacing a campaign gives one finished response. The segment rule of spec for the response's facts decides: a model rule asks the model (its own spacing), a plan rule reads the menu, and any other rule means no pings at the spacing the decision is scored at (kvcache.DefaultPingIdle). row is the model's feature row, nil for a plan-only campaign.
func DefaultWeekdays ¶
DefaultWeekdays returns a copy of that work week, so a caller cannot change the next caller's days.
func FidMiss ¶
FidMiss is the default miss rate of a request that only a ping kept alive, by model family.
func ForcePolicy ¶
ForcePolicy makes an "apply anyway" run the plan the user chose: a non-ship build's spec holds the fleet plan as its policy and the tenant's own tuned plan under own_policy; this swaps them in the spec document. false when the spec holds no own plan.
func HeadTTL1hHonored ¶
HeadTTL1hHonored reports whether model is measured to honor the 1h cache tier on this deployment: the set a campaign checks before it activates a 1h-tier arm.
func HonorsHeadTTL1h ¶
HonorsHeadTTL1h reports whether every model a tenant used honors the 1h cache tier. It fails CLOSED: no models (unknown traffic, or the history unreachable) means "not confirmed", never "assume yes".
func MarkOverlaps ¶
func MarkOverlaps(resolved []*Resolved, owners []tenant.CampaignCellOwner)
MarkOverlaps turns any cell whose (tenant, hour) an ACTIVE campaign already enforces into a non-activatable one, naming the campaign that holds it.
A per-cell skip, not a refusal of the whole request. The two alternatives are both worse: rejecting the campaign outright makes one already-covered hour block a batch of two hundred good cells, and a manager's only recovery is to hand-edit the payload to remove it — while creating the strategy anyway leaves two live strategies competing for one hour, where the resolution chain silently picks one and both campaigns claim it. Skipping reuses the machinery every other unenforceable cell already flows through: recorded with a reason, grouped by that reason in the create result, never hidden.
Deliberately blind to the ARM: a second campaign recommending a DIFFERENT arm for an hour is still a conflict, not a refinement. Only one of the two strategies can win the resolution chain, so letting the different-arm case through would recreate exactly the ambiguity this gate exists to remove. Re-issuing an hour under a new arm is a real need, and the honest path for it is to archive the campaign that holds it first.
func NewFacts ¶
func NewFacts(model, stop, agent string, prefix int64, pingCost float64, hourUTC, dowUTC int) predictive.Facts
NewFacts is the one place that turns a request's attributes into the facts a campaign segment tests, for the live decision and for a replay.
func PlanOutcome ¶
PlanOutcome is the closed-form replay of one decision: ping j starts at j*x - u + late after the response end and fires if the conversation has not returned (and the client has not ended the session) by then; the entry survives to the return if the last touch is within the cache lifetime of it.
func Priced ¶
Priced reports whether a row's rates let a campaign decide: a cache read must cost something and a write must cost more than a read.
func RowFloor ¶
RowFloor is the prefix floor the keeper would apply to a replayed row (Policy.WaitMinPrefix). A row has the stop reason, not the wait cause or the tool names: a tool stop is read as a tool wait, any other stop as a wait for a person (80k). A row that waited for background work or a teammate gets 80k here, where the keeper gives it 20k, so the replay under-counts those rows. A row carries no stored cause here, so every tool stop reads as a tool wait (20k). Dash's storedWait differs: it keeps a tool stop with a stored human cause as human. So a main-thread tool stop that asks a person reads as a tool wait here, and the replay can admit a few rows the keeper would refuse. An OpenAI row gets the general floor only: the keeper plans no wait for OpenAI.
KNOWN GAP, kept on purpose: this gap is a behaviour change held for a human decision in #1298. Do not fix it here.
func SegmentOf ¶
SegmentOf is the segment function of a segmentation name (cacheBuildIn.SegmentBy), nil when the name is unknown: a row's segment key and the runtime predicates that select the same requests live.
func ShipGate ¶
ShipGate is the auto builder's ship rule, shared by the build and the adapt report: the subject's held-out net is positive and its paired session-bootstrap interval against every leg lies above zero. failed names each leg (and the sign) that did not hold.
func Stake ¶
Stake is one avoided rewrite: the prefix times what a write costs over a read. Gateway dollars.
func StrategyForGroup ¶
StrategyForGroup builds the tenant.Strategy one Group resolves to: the coalesced Target and the tiled Windows, at the arm's own live parameters.
func TileHours ¶
TileHours turns a set of UTC hours into the fewest tenant.Window values that cover exactly those hours and no others, merging consecutive hours into one window.
Hour 23 never merges past midnight into hour 0: tenant.Window has no overnight span (Window.Validate rejects end <= start), so a run ending at 23 closes its own window at "24:00" — the end-of-day sentinel tenant.parseHHMM accepts for exactly this reason. It used to close at "23:59", which as an exclusive end left 23:59:00-23:59:59 covered by nothing.
func WeekdaysFromNames ¶
WeekdaysFromNames converts a suggest payload's Weekdays (["Sunday", "Monday", ...]) into tenant.Window's []time.Weekday. An unrecognized name is silently dropped rather than erroring — the caller has no better recovery than "run with fewer restricted days", and the alternative (refusing the whole campaign for one bad string in a list this deployment itself generated) is a worse failure mode.
If NOTHING is recognized — Weekdays omitted entirely by a hand-edited upload, or every name in it misspelled — this returns a copy of DefaultWeekdays(), never an empty slice: tenant.Window.contains treats an empty Days as "every day matches", not "no day restricted", so a silent drop-to-empty here would create a live strategy that fires on Friday and Saturday too — traffic the frozen PredictedUSD figures were never backtested against (both this suggester and its own callers only ever read Sunday-Thursday history). "Fewer restricted days" must have a floor.
Types ¶
type Active ¶
type Active struct {
ID string
Spec *predictive.Spec
}
Active is a live campaign whose plan a replay follows.
type Arm ¶
type Arm struct {
// activatable is false for an arm with no live enforcement path at all — a
// simulation-only arm. reason explains why, for CampaignCell.SkipReason.
Activatable bool
Reason string
// baseline is true for an arm that means "change nothing" (no-cache/fixed-5m/
// fixed-1h) — a SUCCESSFUL outcome that creates no strategy, distinct from
// activatable=false, which is a limitation, not a recommendation to do nothing.
Baseline bool
// needsModelHonoring is true for a 1h-tier Arm: ResolveCell additionally
// checks headTTL1hHonoredModels for this specific tenant before activating it.
NeedsModelHonoring bool
IdleSeconds int
MaxPings int
// predictorID and predictorThreshold always travel together: a predictorID with a
// zero threshold would make predictorFor's gate a no-op (see validPredictorRef) —
// pingable() ends up pinging on the arm's idle/max-ping schedule unconditionally,
// identically to keepalive-5m, while still being labeled and billed as the
// predictor-gated arm.
PredictorID string
PredictorThreshold float64
HeadTTL1h bool
HeadTTLMinTokens int
MinPrefixTokens int
}
Arm is how one suggest arm maps onto a live keepalive_strategies row, decided once per ARM NAME, never per cell: every cell recommending the same arm gets the same live parameters, which is what makes it safe to coalesce cells sharing an arm across tenants and hours into one strategy.
func ArmFor ¶
ArmFor is the single source of truth the create flow consults. idleSeconds/ maxPings for the 5-minute arms sit well inside validStrategyBounds' 5m band (minOverrideIdle..maxOverrideIdle, minOverridePings..maxOverridePings); for the 1h-tier arms they sit inside the 1h band (maxOverrideIdle1h, maxOverridePings1h) — see proxy/keepalivestrategy.go for both bands and why they differ.
type Cell ¶
type Cell struct {
User string
HourUTC int
Requests int64
BestStrategy string
SavingUSD float64
BaselineUSD float64
OptimalSavingUSD float64
InsufficientData bool
UnpricedRequests int64
}
Cell is one suggest cell as a campaign reads it. A host fills it from its own suggest type.
type EvalResult ¶
type EvalResult struct {
Insufficient string // why there was nothing to evaluate; "" when evaluated
Cut int64
TenantRows []int // indices of the tenant's rows
Test []int // indices of the tenant's held-out rows (ending at or after cut)
NSessTest int
Scope []string // the tuner scope of every row: tenant[\x1fsegment] for the tenant's rows when segmented
Fit, Final *predictive.AutoFit
}
EvalResult is one build's held-out evaluation, shared by the builder (BuildSpec) and the host's adapt report.
func Eval ¶
func Eval(rows []predictive.AutoRow, facts []RowFacts, tenant string, until int64, segBy string) *EvalResult
Eval tunes the tenant's plan(s) on the fleet's rows resolved before the tenant's 70% point and refits on all of them. segBy "" is one plan for the tenant; otherwise one tuner scope per (tenant, segment), each shrunk toward the fleet. facts (same order as rows) may be nil only when segBy is empty: a segmentation reads each row's facts, and a nil slice panics.
func (*EvalResult) HeldPlan ¶
func (e *EvalResult) HeldPlan(i int) int
HeldPlan is the subject's plan on row i, tuned before the cut; InPlan is the plan refitted on the whole window (in-sample).
func (*EvalResult) InPlan ¶
func (e *EvalResult) InPlan(i int) int
type FidParams ¶
FidParams are the two quantities fitted on the caller's own history: h, the share of requests that still hit after a gap no ping covers (another session kept the shared prefix warm), and the head a request that misses reads anyway, per model.
type GateLeg ¶
GateLeg is one baseline of the ship gate: its per-row net on the held-out rows.
func GateLegs ¶
GateLegs are the ship gate's baselines, in one place for the build and the adapt report: what the tenant would get anyway, blanket K3, the fleet plan and (when known) the shipped default. A hindsight-best blanket plan is no gate: when the tuner picks a fixed plan it can at best tie it.
type Group ¶
Group is one set of activatable, non-baseline cells that will share exactly one keepalive_strategies row: the same arm, AND the same set of hours. Grouping any looser than "same hour set" would be wrong, not just coarser — a strategy's Target and Windows both apply to the WHOLE strategy, not per-tenant, so folding a tenant recommended for hours {9} together with one recommended for {9,14} into one strategy would activate hour 14 for the first tenant too, an hour it was never recommended for.
type Option ¶
type Option struct {
ID string
Adapted bool // an adapted plan: the builder's gate applies to it
Net float64 // its held-out net, gateway dollars
Diff float64 // its held-out net minus the default's
CI [2]float64 // the paired session interval of Diff
// GatePass and GateWhy are the builder's ship gate (ShipGate) on the same rows, for an adapted option.
GatePass bool
GateWhy []string
}
Option is one strategy of the adapt report, scored on the held-out rows against the default.
type Pick ¶
type Pick struct {
BestID string
BestCI [2]float64
BestDiff float64
GateID string // the adapted option with the best net that passes the builder's gate; "" when none does
GateDiff float64 // zero when GateID is ""
GateCI [2]float64 // zero when GateID is ""
Disagree []string
// contains filtered or unexported fields
}
Pick is the outcome of a Picker.
func (Pick) BeatsDefault ¶
BeatsDefault reports whether the best option leads the default with a 95% interval above zero.
func (Pick) Recommends ¶
Recommends reports whether the report recommends a change: an adapted option passed the builder's gate.
type Picker ¶
type Picker struct {
// contains filtered or unexported fields
}
Picker picks the recommendation of an adapt report from its options, in the order they are added.
type Plan ¶
Plan is a strategy's decision on row i: k pings, x seconds apart, cancelled by SessionEnd or not.
func CurrentPlan ¶
func CurrentPlan(pol keepalive.Policy, se bool, camp *Active, facts []RowFacts) (plan Plan, label string, ok bool)
CurrentPlan replays the caller's own policy as configured now: its live campaign's plan where one is active (rules campaigns only), else the account's keep-alive with its floor, ceiling, first-request skip and predictor gate. SessionEnd counts only if this deployment honours the signal (se). A manager strategy (time windows) and per-session overrides are not replayed; a model campaign is reported as not replayable (ok=false). camp is the account's ACTIVE campaign, nil when it has none or its mode is not active.
type Resolved ¶
type Resolved struct {
TenantID string
HourUTC int
Requests int64
Arm string
PredictedUSD, BaselineUSD float64
OptimalSavingUSD float64
InsufficientData bool
Activatable bool
SkipReason string
// StrategyID is filled in by Coalesce's caller once the group this
// cell belongs to has an actual keepalive_strategies row.
StrategyID string
// Config is only meaningful when Activatable && !Config.Baseline.
Config Arm
}
Resolved is one suggest cell's outcome after resolving its arm and, for a 1h-tier arm, checking whether this specific tenant's traffic honors it.
func DuplicateCell ¶
DuplicateCell reports the first cell whose (tenantID, hourUTC) pair also appears earlier in resolved, or nil if every pair is unique — the same key shape tenant.CreateCampaign's own guard checks, run here up front so a duplicate is refused before any strategy is created for it, not just before the campaign record that would have referenced it.
func ResolveCell ¶
ResolveCell turns one suggest cell into its outcome. honorsHeadTTL1h reports whether tenantID's own traffic honors the 1h tier — a function rather than a precomputed map so the caller can memoize per tenant however it likes and tests can fake it cheaply.
HourUTC is bounds-checked FIRST, before the arm is even resolved: the live-fetch source can never produce one outside [0,23] (it's always time.Time.UTC().Hour()), but the upload source accepts a hand-edited suggest payload verbatim, and an out-of-range hour reaching TileHours would build a Window string like "24:00" that tenant.Window.Validate rejects — silently, if nothing catches it first, producing a strategy that is created successfully but can never match anything.
func (*Resolved) TenantCell ¶
func (c *Resolved) TenantCell() tenant.CampaignCell
TenantCell is the cell as a campaign records it.
type RowFacts ¶
type RowFacts struct {
U, Gap float64 // request duration and the gap from its response end to the next request, seconds
Returned bool
ToEnd float64 // seconds from this response's end to the end of the session's last response (any model): SessionEnd cancels pings after it
Stake, Ping float64 // one avoided rewrite (prefix x (write - read)) and one ping, gateway $
Turn int // requests of the conversation before this one
Prefix int64
Hour, Dow int // request start, UTC
StartMs int64
Model, Agent, Stop string
Subagent bool // the request is on a subagent thread (keepalive.IsSubagentThread)
OpenAI bool // an OpenAI request: the keeper gives it the general floor only
PRead, PWrite float64 // gateway rates of the row's model
NextPrefix int64 // the next request's cached prefix (0 = none or unknown)
Span float64 // seconds from the response end to the next request of the same session thread (any model): the keeper's entry is per thread, so its pings stop then
}
RowFacts is what a decision point carries besides its tuner row: its timing (to replay any plan, not only the menu), its dollars at the gateway's rates, and the facts a campaign segment tests.
func Rows ¶
func Rows(reqs []*kvcache.Request, price func(model string) (pIn, pOut, pRead, pWrite float64, ok bool), sessionEnd bool, untilMs int64) ([]predictive.AutoRow, []RowFacts)
Rows turns the dashboard dataset into tuner rows plus each row's facts (same order). A row whose outcome is not known by untilMs (its response ended less than the last ping plus the cache lifetime before it) is dropped, and so is one with no price or incomplete accounting. Gains are in the builder's units (calibrated to the pinned replay engine).
func (*RowFacts) DefaultK ¶
The shipped default keep-alive (config.Default*): K2 at 240 s on a prefix of at least 80K tokens, at most $0.50 a ping, never after a thread's first request, with SessionEnd.
func (*RowFacts) Expected ¶
func (f *RowFacts) Expected(k int, x float64, sessionEnd bool, p *FidParams) (rescue, ping, pings, rescues float64)
Expected is plan (k pings x s apart) on the row in expectation over ping failures and the cliff: the consumer's saving, the pings' cost (a failed ping is billed as a rewrite), the expected number of pings and of rescues. Gateway dollars.
func (*RowFacts) Facts ¶
func (f *RowFacts) Facts() predictive.Facts
Facts is the row as a campaign segment tests it (predictive.Facts).
type Score ¶
type Score struct {
Fired int
Rescued bool
PingUSD float64 // PingScale x pings fired x one ping
RescUSD float64 // BenefitScale x stake when rescued, else 0
NetUSD float64 // RescUSD - PingUSD
}
Score is the closed-form result of one decision, in the builder's units (gateway dollars times the calibrated scales).
func ScoreDecision ¶
ScoreDecision scores plan (k pings x x seconds apart) on a request of duration u seconds whose conversation returned after gap seconds (returned), when the client ends the session stop seconds after the response (+Inf for never). ping and stake are one ping and one avoided rewrite.