Documentation
¶
Overview ¶
Package meter is the run meter (§4, C3, C5): every poll.meter, on every run, it writes the usage annotation the composition projects into status.usage.tokens, and revokes a live run at its cap: budget-run for the run's own (in USD when its tier sets runUSD, OD-6 (b), else in tokens), budget-fleet for a gateway 429 of the fleet bucket, budget-principal for the principal's day when budgets.enforcePrincipal (R13, C5). The day's spend is the R50 ledger's, appended here tick by tick (R07); Crossplane owns AgentRun status, so this writes annotations only. Every run is metered, human-launched ones included.
Index ¶
Constants ¶
const ( // ReasonBudgetRun is the revocation at a run's own cap (enforced from phase 1: R3). ReasonBudgetRun = "budget-run" // ReasonBudgetFleet is a gateway 429 below the run ceiling: the fleet bucket, the only // other one on agent-router (R13). ReasonBudgetFleet = "budget-fleet" // ReasonBudgetPrincipal is the principal's day spent (OD-10), read from the ledger (R07). ReasonBudgetPrincipal = "budget-principal" )
Revocation reasons (C5). The composition turns each into its own BudgetExhausted variant, and the broker's end reason reads it back (runwatch.EndReason).
const ( LimitRunUSD = "run-usd" LimitRunTokens = "run-tokens" LimitGatewayCeiling = "gateway-ceiling" // B1 LimitFleet = "fleet" // B2 LimitPrincipalDay = "principal-day" )
The limit behind a revocation. The reason stays C5's closed set, since the composition maps each value to a phase, so the limit goes to the log and the revocations metric instead.
const ( FallbackUnpriced = "unpriced" // its claim's model has no meter.prices entry FallbackUntyped = "untyped" // meter.query does not group by gen_ai_token_type )
Why a run whose tier caps in USD is capped in tokens instead.
const BlindTicks = 10
BlindTicks is how many periods without a metered tick admission tolerates before an enforced daily cap refuses (#54): a leader handover or a scrape gap is not an outage, five minutes at a 30 s period is.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Cost ¶
type Cost struct {
MicroUSD int64
Why string
// Served is the models that served the run's typed reading, by gen_ai_request_model, sorted
// (R10); nil when the query does not group by model.
Served []string
}
Cost is what the meter knows of a run's USD cost: MicroUSD once a typed reading priced it, or Why it cannot be priced (FallbackUnpriced, FallbackUntyped).
type CostKey ¶ added in v0.41.0
type CostKey struct{ Tier, Role, Cohort, Profile string }
CostKey is what a run's cost is reported by: its tier and costRole, and the task's cohort and profile when the run started (R34), "" without.
type Costs ¶
type Costs struct {
// contains filtered or unexported fields
}
Costs hands each tick's run costs to the reconciler, which sums a task's for its USD cap (OD-6 (b)) and re-prices a terminal task's runs from them (CD23). Safe for concurrent use: the meter writes it, the reconciler reads it.
func (*Costs) Get ¶
Get is a run's cost as of the meter's last tick that held it; false when the meter has no word on it, or when that tick is costsRetain ago (CD23) and the next Put has dropped it.
func (*Costs) Put ¶ added in v0.36.0
Put records one tick's run costs, with the tick's clock (CD23); it is the only writer. A run in m is stamped as the tick that held it; a run absent from m is kept, unrefreshed, while the tick that last held it is less than costsRetain ago, and dropped from then on: a task's final re-price reads the cost its last run settled at, which the tick that dropped that run no longer names.
type Meter ¶
type Meter struct {
Runs Store
Source Source
// PerReplica is true when the Source's query keeps each gateway replica a series of its own
// (config.Meter.ByReplica): only then is a series a replica's counter, and fold keeps one
// baseline per series (D10). Unset, the per-run reading is taken as it comes.
PerReplica bool
// Throttle maps gateway 429s to runs; nil: no 429 mapping (VL implements it).
Throttle Throttled
// Cfg is the live config, read once per tick (factory resources D12): budgets (the daily
// ceilings, enforced only when EnforcePrincipal, R3's shadow first), meter.prices, each
// tier's USD run cap (RunUSD), and harnessProfiles, which bound a run's cost profile label
// (R40). nil reads an empty config: no price, no cap, no budget, no profile.
Cfg config.Source
// B1Ceiling is the gateway's per-run ceiling (config.RunTokenCeiling), in the unit B1 charges
// (b1Spend): a 429 at or above it is the run spending its own bucket, below it the fleet's
// (R13). Zero: never name B1.
B1Ceiling int64
// Costs receives each tick's run costs, for the task cap; nil: nobody reads them.
Costs *Costs
Every time.Duration
// Now is the clock; nil means time.Now.
Now func() time.Time
// OnRevoke is told of each revocation written, with its reason and the limit that fired, under
// a context that binds the run's payer (fmetrics.WithPrincipal): fmetrics.Set.RunRevoked.
OnRevoke func(ctx context.Context, reason, limit string)
// OnCharge is told of each run's charge once the write that settles it succeeded, or once
// resolve finds a write in doubt landed: its payer (runs.Run.Payer), its kind and the
// micro-USD (spend per identity SI2). Its sum over payers is what the day's spent columns
// gained: R10's lift reaches a run's settled entry, never spent, and is never counted.
OnCharge func(ctx context.Context, principal, kind string, microUSD int64)
// OnCharges receives, each tick that listed the runs, those the charge info names (SI3):
// every run not ended, and each ended one until endSettle after its status.finishedAt. Each
// hand-over is a slice of its own, kept by the receiver; Start hands over nil as it returns,
// so a meter that stops leading names no run.
OnCharges func(live []runs.Run)
// OnCost is told, once, of a priced run's USD cost, in total and by the model that served it,
// with its tier and costRole: endSettle after the meter, having seen it live, sees it end, or
// when it is deleted first. OnFallback of a run of a USD-capped tier capped in tokens instead,
// once per run.
OnCost func(ctx context.Context, key CostKey, usd float64, byModel map[string]float64)
OnFallback func(ctx context.Context, why string)
// OnLateCost is told of what a run spent after its cost was reported, by served model: a
// reading slower than endSettle corrects the total spend, never the reported cost.
OnLateCost func(ctx context.Context, byModel map[string]float64)
// OnSpend receives, each tick that read usage, the USD spend of every priced run whose cost
// is not reported yet, by run then served model: the per-run gauge.
OnSpend func(spend map[string]map[string]float64)
// OnSettled receives, each tick that listed the runs, what the day ledgers settled for each
// run that has an entry, in USD: the sum of its settled.<runId> over the days, as the ledger
// objects read or written show it (XC5), never the meter's own account of it. A run stays in it
// settledKept after it ends, then leaves.
OnSettled func(settled map[string]float64)
// OnUnpriced is told, once per run, of a model that served it with no price (J-AC4).
OnUnpriced func(ctx context.Context, model string)
// OnInputExcludesCache is told, once per run, of a model whose input read below its cache
// tokens: the gateway reported it without them, and it was priced as fresh input whole.
OnInputExcludesCache func(ctx context.Context, model string)
// Day reports each principal's day after a tick that settled, in micro-USD: what it spent,
// unclamped, and its cap. The fmetrics gauges.
Day func(principal string, spent, limit int64)
// OnUsageError is told of each failed usage read; OnSucceeded of each tick that metered,
// with its time; OnOvershoot of what a run spent past its cap when revoked (#54).
OnUsageError func(ctx context.Context)
OnSucceeded func(ctx context.Context, at time.Time)
OnOvershoot func(ctx context.Context, tokens int64)
// Ledger is the store of R50's day ledgers (the manager's client): the meter charges each
// tick's increase, in micro-USD, to the spent column and to each run's settled entry in one
// write, releases the reservations of runs that ended, stamps the heartbeat admission reads
// (#54), and prunes old days. nil: the day's spend lives in this meter's memory alone, and a
// failover loses it — fine while EnforcePrincipal is off, which is every wiring that leaves
// it unset today.
Ledger client.Client
// Tasks lists the factory's Tasks (the manager's cached client: no apiserver call per tick),
// so a live task's reserved next run is never released as unclaimed. nil: none is protected.
Tasks client.Reader
Namespace string
// Ticker starts the period; nil means a time.Ticker.
Ticker func(d time.Duration) (c <-chan time.Time, stop func())
Log *slog.Logger
// contains filtered or unexported fields
}
Meter is a leader-only manager.Runnable. Tick is not safe for concurrent use: Start is its one caller in the binary.
func (*Meter) NeedLeaderElection ¶
NeedLeaderElection is true: two meters would each add the same increase.
func (*Meter) Start ¶
Start ticks at once, then every Every, until ctx ends. A failed tick is logged and the next one retries.
func (*Meter) Tick ¶
Tick meters every run once: it charges the cost this tick saw to the day's ledger, writes usage as it grew, revokes a live run at any of its caps, stamps the heartbeat admission reads, and keeps the ledgers themselves clean. A failed read of runs or usage writes no usage and no stamp. A ledger that cannot be read or written writes no usage annotation (a run's usage shows only what a day ledger charged), no stamp and no upkeep, but still revokes at the per-run caps. A failed annotation is reported and is no revocation. Occupancy is not usage: a tick that could not read usage still releases the runs that ended (#55), provided the ledger can be written.
type ModelUsage ¶
type ModelUsage struct {
Input, CacheRead, CacheWrite, Output int64
}
ModelUsage is one served model's typed counters within a run's Usage.
type Off ¶ added in v0.35.0
type Off struct{}
Off is the Source of a factory with no metrics backend (demo mode): every run reads as no usage.
type Series ¶ added in v0.33.0
type Series struct {
Run, Key string
Typed bool // the series carries gen_ai_token_type
Type, Model string // gen_ai_token_type, gen_ai_request_model ("" when unlabelled)
Value int64
}
Series is one series of the meter's query that is a run's: its run, its labels as one key, its token type and served model when labelled, and its raw value.
type SeriesSource ¶ added in v0.33.0
SeriesSource is a Source that also reads the query series by series. With Meter.PerReplica, the meter keeps one baseline per series (D10) rather than one per run's sum; without it, the series are summed per run and read as RunUsage would. VM implements it.
type Store ¶
type Store interface {
List(ctx context.Context) ([]runs.Run, error)
Annotate(ctx context.Context, id string, kv map[string]string) error
}
Store is the part of the AgentRun client the meter uses; runs.Client implements it.
type Throttled ¶
Throttled names the runs a gateway answered with a rate-limit 429 lately; VL implements it against VictoriaLogs. A lookup failure costs only the fleet mapping for that tick: budget-run and budget-principal stand without it.
type Usage ¶
type Usage struct {
Tokens, Input, CacheRead, CacheWrite, Output int64
// Typed: the reading carried gen_ai_token_type, so it can be priced.
Typed bool
// Models splits the typed counters by the model that served them (gen_ai_request_model), so
// each is priced at its own rate; "" holds a series without that label, priced by the claim's
// model. nil on a typed reading: all of it is "".
Models map[string]ModelUsage
}
Usage is a run's raw counters. Tokens is what the token caps count: input plus output, or an untyped series' value. `Input` is the gateway's `input` series, which counts `cached_input` and `cache_creation_input` inside it on every path the platform runs: agentgateway 1.6's Chat Completions to Messages translation, streamed or not (measured 2026-10-22), and Z.ai's prompt_tokens. `cost` subtracts them to price fresh input, unless the input is below them (inputExcludesCache): only a gateway that leaves them out reports that.
type VL ¶
type VL struct {
// Kind is the runs kind, required: a row is a run's only when its verified identity is one
// of Kind's run subjects.
Kind runwatch.Kind
URL, Query string
// HC is the meter's egress: one from httpx.New. nil is an error at use, never a
// hand-rolled client: the audited bounds (timeout, redirect cap) are the point.
HC *http.Client
}
VL asks VictoriaLogs which runs agent-router answered with a rate-limit 429 lately (R13). The query groups by the verified identity header (x_ar_agent), never a client-supplied one.
type VM ¶
type VM struct {
// contains filtered or unexported fields
}
VM runs the meter's one instant query against VictoriaMetrics (R12): the expression of SP4 PR 2's agent_router:run_tokens:total over the raw series, until that rule exists.
func NewVM ¶
NewVM is the source at rawURL (meter.url): http or https with a host, since vmsingle serves plain http in the cluster. kind is the runs kind whose run subjects it reads; hc comes from httpx.New.
func (*VM) RunSeries ¶ added in v0.33.0
RunSeries is the query's reply series by series (D10), each keyed by its labels. A series that is not a run's, whose value is not a finite, non-negative count, or whose gen_ai_token_type the meter does not price (reasoning, a subset of output, and unknown types), is no reading.
func (*VM) RunUsage ¶
RunUsage is each run's raw counters, by run id: RunSeries summed by run, stateless. A series labelled gen_ai_token_type counts as its type, and also under its gen_ai_request_model, the model that served it; an unlabelled one is the token count itself, so an untyped query meters as before.