campaign

package
v0.7.16 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 17 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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.

View Source
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.

View Source
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
)
View Source
const (
	FidPFirst = 0.0089 // P(a first ping rewrites instead of refreshing)

)

Variables

View Source
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

func Apply(pol keepalive.Policy, k int, active bool) keepalive.Policy

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

func ArmEnforceable(arm string) bool

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

func DefaultWeekdays() []time.Weekday

DefaultWeekdays returns a copy of that work week, so a caller cannot change the next caller's days.

func FidMiss

func FidMiss(model string) float64

FidMiss is the default miss rate of a request that only a ping kept alive, by model family.

func ForcePolicy

func ForcePolicy(spec map[string]any) bool

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

func HeadTTL1hHonored(model string) bool

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

func HonorsHeadTTL1h(models []string) bool

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 PlanName

func PlanName(k int) string

PlanName is a menu plan's name: "none" or "K<k>".

func PlanOutcome

func PlanOutcome(k int, x, u, gap float64, returned bool, stop float64) (fired int, rescued bool)

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

func Priced(pRead, pWrite float64) bool

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

func RowFloor(pol keepalive.Policy, f *RowFacts) int

RowFloor is the prefix floor the keeper would apply to a replayed row. It asks Policy.FloorFor, the one rule, with the row's stored wait cause and stop reason. A main-thread row with neither (an old row) gets the general floor. A tool stop stored as a human cause stays human, so a tool stop that asks a person reads as a person wait (80k), as the dashboard replay reads it; the keeper can read such a stop as a tool wait. An OpenAI row gets the general floor only: the keeper plans no wait for OpenAI.

func SegmentOf

func SegmentOf(segBy string) func(f *RowFacts) (key string, when []any)

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 SessionCI

func SessionCI(v []float64, sess []string, seed int64) [2]float64

SessionCI is the 95% interval of sum(v) by bootstrap over sessions.

func ShipGate

func ShipGate(subject []float64, legs []GateLeg, sess []string) (pass bool, failed []string)

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

func Stake(prefix int64, pRead, pWrite float64) float64

Stake is one avoided rewrite: the prefix times what a write costs over a read. Gateway dollars. The accountant owns the formula (accountant.MissCost): a rewrite never costs less than 0.

func StakeHead added in v0.7.11

func StakeHead(prefix, head int64, pRead, pWrite float64) float64

StakeHead is Stake on a mixed entry. head above 0 is a 1-hour head that lives: only the tail is rewritten.

func StrategyForGroup

func StrategyForGroup(campaignName string, g *Group, days []time.Weekday) tenant.Strategy

StrategyForGroup builds the tenant.Strategy one Group resolves to: the coalesced Target and the tiled Windows, at the arm's own live parameters.

func SumOf

func SumOf(v []float64) float64

SumOf is the sum of v.

func TileHours

func TileHours(hours []int, days []time.Weekday) []tenant.Window

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

func WeekdaysFromNames(names []string) []time.Weekday

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

func ArmFor(arm string) Arm

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 DecisionPrices added in v0.7.11

type DecisionPrices struct {
	// PIn, POut, PRead and PWrite are the rates at the request's own prompt size.
	PIn, POut, PRead, PWrite float64
	// Stake is one avoided rewrite: the prefix at the 5-minute write rate minus the read rate, at the
	// request's own rates. It is in the calibrated units of the replay (BenefitScale), so it stays at
	// the 5-minute rate on a 1-hour thread too.
	Stake float64
	// Ping is one ping, at the rates of the ping's prompt size.
	Ping float64
	// Miss is the miss that the value rule weighs (keepalive.MissUSD): the same figure at the ping's
	// prompt size, at the write rate of the entry (5 minutes, or 1 hour when oneHour). 0 means unknown,
	// and the rule then fails open.
	Miss float64
}

DecisionPrices is what one decision point is worth, in gateway dollars. The replay (Rows) and the live campaign (the proxy) build it with PriceDecision, so both decide on the same economics.

func PriceDecision added in v0.7.11

func PriceDecision(price PriceFunc, model string, prefix, promptTokens int64, oneHour bool) (DecisionPrices, bool)

PriceDecision prices one decision point: a request of promptTokens prompt tokens that left a cached prefix of prefix tokens. oneHour says that the entry was billed at the 1-hour tier. ok is false when the model has no price. The caller applies its own gate on the rates (the replay drops a row whose write rate is not above its read rate; the live campaign tests Priced).

The ping reads the prefix plus its own input (keepalive.PingPrompt), so it is priced at that size: a prefix just below a price line sends a ping above it. When the ping's size has no price, the request's own rates stand in. The accountant owns each formula (PingCost, MissCost).

func PriceDecisionHead added in v0.7.11

func PriceDecisionHead(price PriceFunc, model string, prefix, promptTokens int64, oneHour bool, head int64) (DecisionPrices, bool)

PriceDecisionHead is PriceDecision on a mixed entry. head above 0 is the 1-hour head of the write (keepalive.MixedHead) and it lives, so the stake and the miss are the tail rewrite only; oneHour then does not count. The replay and the live campaign both give the head of the request's own write.

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

type FidParams struct {
	H    float64
	Head map[string]float64
	N    int // requests the fit used
}

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.

func FitFidelity

func FitFidelity(reqs []*kvcache.Request, tenant string) FidParams

FitFidelity fits h and the heads on the tenant's own requests.

type GateLeg

type GateLeg struct {
	Name string
	V    []float64
}

GateLeg is one baseline of the ship gate: its per-row net on the held-out rows.

func GateLegs

func GateLegs(k3, fleet, def []float64, fleetPlan int) []GateLeg

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

type Group struct {
	Arm       string
	Config    Arm
	HourSet   []int
	TenantIDs []string
	Cells     []*Resolved
}

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.

func Coalesce

func Coalesce(cells []*Resolved) []*Group

Coalesce groups activatable, non-baseline cells by (arm, exact hour set) — see Group's doc comment for why that is the loosest safe grouping. Baseline cells (Arm.Baseline) and non-activatable cells are excluded: neither needs, nor can have, a strategy.

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

func (r Pick) BeatsDefault() bool

BeatsDefault reports whether the best option leads the default with a 95% interval above zero.

func (Pick) Recommends

func (r Pick) Recommends() bool

Recommends reports whether the report recommends a change: an adapted option passed the builder's gate.

func (Pick) Summary

func (r Pick) Summary() string

Summary is the one-paragraph answer of the report.

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.

func NewPicker

func NewPicker() *Picker

NewPicker is a Picker with no option yet.

func (*Picker) Add

func (p *Picker) Add(o Option)

Add scores one option. "never" is a baseline, never the best. An adapted option that leads in gateway dollars while the builder's gate disagrees, or the reverse, is named in `Pick.Disagree` (from `Result()`).

func (*Picker) Result

func (p *Picker) Result() Pick

Result is the pick, with the summary sentence of the report.

type Plan

type Plan func(i int) (k int, x float64, se bool)

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 PriceFunc added in v0.7.11

type PriceFunc func(model string, promptTokens int64) (pIn, pOut, pRead, pWrite float64, ok bool)

PriceFunc is a host's rate lookup: a model's rates at a prompt size, in $ per token. A request above a price line reads the rates of its tier (modelinfo.Price.At). ok is false for a model with no price.

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

func DuplicateCell(resolved []*Resolved) *Resolved

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

func ResolveCell(cell Cell, honorsHeadTTL1h func(tenantID string) bool,
) Resolved

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 $
	Miss               float64 // the miss the value rule weighs (keepalive.MissUSD): the same figure at the ping's prompt tier, at the 5-minute write rate, or at the 1-hour rate for a row with CacheWrite1h > 0 (the entry was billed at the 1-hour tier). 0 = unknown, and the rule fails open
	Turn               int     // requests of the conversation before this one
	Prefix             int64
	Hour, Dow          int // request start, UTC
	StartMs            int64
	Model, Agent, Stop string
	Cause              string  // the row's stored wait cause (waiting_for), "" on an old row
	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 PriceFunc, 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

func (f *RowFacts) DefaultK() int

The shipped default keep-alive (config.Default*): K2 at 240 s on a prefix of at least 80K tokens, every chain costing less than the miss it protects, 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).

func (*RowFacts) Gain

func (f *RowFacts) Gain(k int, x float64, sessionEnd bool, bScale, pScale float64) float64

Gain is the net of plan (k, x) on the row: bScale x the avoided rewrite, minus pScale x the pings. Scales 1 = gateway dollars.

func (*RowFacts) Outcome

func (f *RowFacts) Outcome(k int, x float64, sessionEnd bool) (fired int, rescued bool)

Outcome replays plan (k pings x s apart) on the row; sessionEnd stops the pings after the session's last response.

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

func ScoreDecision(k int, x, u, gap float64, returned bool, stop, ping, stake float64) Score

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.

type Tally

type Tally struct {
	Net, Engine, Rescue, Ping float64
	Pings, Rescues            float64 // expected counts
}

Tally is one strategy's replay over a set of rows.

func ScoreRows

func ScoreRows(facts []RowFacts, idx []int, plan Plan, fp *FidParams) (t Tally, per, eng []float64)

ScoreRows replays plan on the rows idx: the totals, and each row's net in gateway dollars (per) and in the builder's units (eng).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL