Documentation
¶
Overview ¶
Package accounting is Cortex's own host for github.com/rossoctl/accountant: it computes context-savings figures with the same rules the context-guru proxy uses, following the host obligations in accountant/docs/cortex-wiring.md W6.
This file's package holds the leaf host code with no caller yet (design §5.2, task 1 of the accountant integration plan):
- wire: splits an inference request body into the sections and breakpoints accountant.NewBody wants (W6.3).
- facts: classifies the destination provider and gives the cache facts (accountant.EntryFacts) for a provider and model (W6, cached-prefix.md).
- skip.go: SkipReason says when not to call Compute, and why (W6.1).
- thread.go: ThreadOf gives the accountant.Thread for a request (W5.2).
core/accounting imports only the standard library, github.com/rossoctl/accountant, OTel, and github.com/rossoctl/cortex/core/... packages — never github.com/rossoctl/context-guru/... (global-constraints.md; boundary_test.go enforces it).
Index ¶
- Constants
- Variables
- func BasisOf(m accountant.BillingMode) string
- func CallUSD(r pricing.Resolver, c *accountant.ModelCall, host string) (float64, bool)
- func CallUSDCurrency(r pricing.Resolver, c *accountant.ModelCall, host string) (usd float64, estimated bool, currency string)
- func SetRequestWindow(pctx *pipeline.Context, w RequestWindow)
- func SkipReason(in SkipInput) string
- func ThreadOf(pctx *pipeline.Context) accountant.Thread
- func TierUSD(r pricing.Resolver, endpoint, model string, promptTotal int, ...) (float64, bool)
- func USD(r pricing.Resolver, endpoint, model string, promptTotal int, t pricing.Tier, ...) (usd float64, estimated bool)
- func USD1h(r pricing.Resolver, endpoint, model string, promptTotal int, tokens int64) (usd float64, estimated bool)
- func Units(w config.SubscriptionWeights, tt accountant.TierTokens, output int) float64
- type DetachedSpend
- type DetachedSpendListener
- type Extras
- type Host
- func (h *Host) AddCostRecorder(r session.Recorder)
- func (h *Host) AddDetachedSpendListener(fn DetachedSpendListener) (remove func())
- func (h *Host) AddKeyedPingListener(key string, fn PingListener) (remove func())
- func (h *Host) AddPingListener(fn PingListener) (remove func())
- func (h *Host) ClearReadSetsTTL(token uint64)
- func (h *Host) Close() error
- func (h *Host) Compute(pctx *pipeline.Context) (accountant.Result, bool)
- func (h *Host) LateOps(pctx *pipeline.Context) func([]accountant.Operation) int
- func (h *Host) Ping(sessionID string, client *model.EventClient, host string, p accountant.Ping, ...) (res accountant.Result, ok bool)
- func (h *Host) RequestBasis(pctx *pipeline.Context) string
- func (h *Host) RequestEnd(pctx *pipeline.Context)
- func (h *Host) RequestStart(pctx *pipeline.Context)
- func (h *Host) Savings(pctx *pipeline.Context) ([]event.Saving, Extras, bool)
- func (h *Host) SetReadSetsTTL(fn ReadSetsTTLFunc) (token uint64)
- func (h *Host) ThreadBilling(session, thread string) accountant.Billing
- type Options
- type PingInfo
- type PingListener
- type PingSpend
- type ReadSetsTTLFunc
- type RequestRatio
- type RequestWindow
- type Sink
- func (s *Sink) CountPing(model, endpoint, outcome string, projectedUSD float64, ...)
- func (s *Sink) CountTTLDowngrade(model string)
- func (s *Sink) Observe(meta accountant.RequestMeta, u accountant.Usage, output int, ...)
- func (s *Sink) ObserveBill(meta accountant.RequestMeta, u accountant.Usage, output int, endpoint string, ...)
- func (s *Sink) ObserveDetached(meta accountant.RequestMeta, res accountant.Result, endpoint string)
- func (s *Sink) ObserveSized(meta accountant.RequestMeta, u accountant.Usage, output int, ...)deprecated
- type SkipInput
- type SpendPrice
Constants ¶
const ( PingOK = "ok" // the provider answered 2xx PingFailed = "failed" // a status outside 200-299, or no response at all (a transport error) PingTimeout = "timeout" // the ping ran to the keeper's timeout with no answer (#754) )
The outcome label of llm.keepalive.pings, with context-guru's values (its observePing), so the central dashboard stacks the two proxies on one axis.
const ( MissColdStart = "cold_start" MissTTLExpiry = "ttl_expiry" MissModelChanged = "model_changed" MissOther = "other" )
The cause label of llm.cache.misses and llm.cache.miss_cost_usd, with context-guru's values (its missCause). Cortex cannot see the body diffs behind context-guru's prefix_change, compaction_after_rewrite and bypass_flip, so such a miss is "other" here, not a guess.
const ( BasisUSD = event.BasisUSD BasisSubscriptionEquivalent = event.BasisSubscriptionEquivalent BasisUnknown = event.BasisUnknown )
The values of event.Saving.Basis (accountant design §7.1, Cortex design §5.7a).
const ( WithheldCheckSum = accountant.WithheldCheckSum WithheldCheckUniqueChange = accountant.WithheldCheckUniqueChange WithheldCheckSpans = accountant.WithheldCheckSpans WithheldCheckOther = accountant.WithheldCheckOther WithheldUnpriced = accountant.WithheldUnpriced WithheldImplausibleSize = accountant.WithheldImplausibleSize )
The reasons Host.Savings books no saving for a request (Extras.Withheld, event.Event.SavingsWithheld, the reason label of llm.savings.withheld). They are the library's names: accountant.Withhold decides the gates (accountant design §6.7, docs/cortex-wiring.md W6.5), so the ledger and the library's metrics sink withhold the same requests.
const KeeperOperator = "keeper"
KeeperOperator is the operator a keep-alive rescue is credited to: the name accountant.PingOps gives the keeper's spend op. A rescue's ChangeID is the ping's window ("ka:<thread>:<window>"), which no op of the request it lands on carries, so it is credited by kind, not by ChangeID.
const MeterName = "github.com/rossoctl/cortex/core/accounting"
MeterName is the instrumentation scope the savings counters are created under.
const PingPurpose = event.PurposeKeepAlive
PingPurpose is the cost record's Purpose for a keep-alive ping (event.PurposeKeepAlive), so a later consumer can show ping spend apart from agent spend (design §5.8). The record's Source stays what settle set: how the cost was arrived at.
Variables ¶
var Components = []string{ "tool-prune", KeeperOperator, "model", "inference-router", "context-guru", "agentdiet", "cache_aware_summarizer", "cacheinject", "cachesplit", "cmdfilter", "collapse", "coref", "dedup", "dropex", "dropfirst", "extract", "extract_llm", "extract_llm_sweep", "failed_run", "format", "keeptail2", "linecap", "mask", "midsum", "readlifecycle", "searchcap", "searchfold", "skeleton", "smartcrush", "summarize", "testreorder", "testrevert", "testrewrite", "testrewrite2", "textclean", "toolfilter", "toolschema", "toon", "usershrink", "adjudicate", "headttl", "tailbreakpoint", "toolcut", "tooldefer", "expand", "expand_restore", }
Components are the operator names, without their prefix, that may appear as the `component` label of the llm.savings.* counters (acmetrics.WithComponents). Any other name is pushed as "other", so the label stays bounded.
- Cortex's own operators: tool-prune (its plugin name), keeper (the keep-alive ping's spend, KeeperOperator), model (cortex.model, the setting op of a model change no plugin claimed), inference-router (the plugin that rewrites the model), and context-guru (the plugin name its own model calls are stamped with).
- context-guru's components as of v0.7.4-beta.1: the names its registry lists (components.Names(), which context-guru's own push passes to WithComponents), plus the operators Cortex's envelope ops and context-guru's traces report under names of their own.
core/accounting may not import context-guru (global constraint), so the list is copied here, and core/plugins/contextguru's TestComponentsCoverTheRegistry fails when a context-guru bump adds a component this list does not hold.
Functions ¶
func BasisOf ¶
func BasisOf(m accountant.BillingMode) string
BasisOf is event.Saving.Basis for a billing mode: "usd" for api, "subscriptionEquivalent" for subscription, "unknown" for anything else.
func CallUSD ¶
CallUSD prices one operator's model call as the ledger's spends[] does: its prompt tiers and its output at the call's own model, at host, and at the call's own prompt total (callPromptTotal), so a small call never takes the request's long-context premium. The metrics sink binds a spend's model to the same host and total (Sink.Observe), so the pushed llm.savings.added.usd{kind="spend"} equals this figure. A CostUSD the call stated is the ledger's business (spendRecord); this function never reads it.
func CallUSDCurrency ¶
func CallUSDCurrency(r pricing.Resolver, c *accountant.ModelCall, host string) (usd float64, estimated bool, currency string)
CallUSDCurrency is CallUSD plus the currency its figure is denominated in — host's, which can differ from the primary request's (a credits-billed gateway beside a USD-endpoint operator call, review finding) — empty for the default (USD), pricing.UnitOf's own convention.
func SetRequestWindow ¶
func SetRequestWindow(pctx *pipeline.Context, w RequestWindow)
SetRequestWindow stashes a host's window facts on pctx for RequestEnd to read. A host that resolves its model's context window calls it in its request hook; RequestEnd sets accountant.RequestMeta.Window and CompactionPoint from it. Not called leaves both at 0.
func SkipReason ¶
SkipReason says why Compute must not be called for this request, or "" to say it should be called. The strings are the context-guru proxy's own fallback-reason strings (proxy/dashcapture.go: noResultWhy, accDeferralUnplaced), not the shorter names accountant/docs/cortex-wiring.md's W6.1 table uses in prose, so that a reader who greps a Cortex log line for one of these reasons finds the same string in the proxy's.
Order matters: a request with no session never opened an accounting record at all (the proxy's "no_record" case, c.accReq == nil) regardless of its status, and a server-held-history request is skipped for its shape before its response is even known, before either upstream-rejection reason.
func ThreadOf ¶
func ThreadOf(pctx *pipeline.Context) accountant.Thread
ThreadOf gives the accountant.Thread for pctx's request (accountant/docs/cortex-wiring.md W5.2): "main" for the primary agent, and the Claude Code subagent id for a subagent, with Parent set to the agent that started it. A subagent with no recorded parent forked from the primary agent, so its parent is "main".
That is the default rule, with no context-guru plugin in the pipeline. A plugin that named a thread with pctx.SetAccountingThread overrides it: context-guru's own thread split, built from prefix continuity inside the engine rather than from the subagent header, takes precedence where it ran (design §5.4).
func TierUSD ¶
func TierUSD(r pricing.Resolver, endpoint, model string, promptTotal int, tt accountant.TierTokens) (float64, bool)
TierUSD prices the library's tokens by tier with USD: Input at TierInput, CacheWrite5m at TierCacheWrite, CacheWrite1h via USD1h, CacheRead at TierCacheRead. It is estimated when any tier that holds tokens is. The tiers are summed in dollars only; tokens of different tiers are never added together (R52).
A negative count (a CacheEffect's Net can have one) prices negative.
func USD ¶
func USD(r pricing.Resolver, endpoint, model string, promptTotal int, t pricing.Tier, tokens int64) (usd float64, estimated bool)
USD prices tokens of one tier with the process rate table, at the rates the request landed on: its endpoint, its model and its prompt total, so a long-context premium applies (design §5.6). It is the one pricing function of the accountant's figures: the ledger's savings and the metrics pricer both call it, so the two cannot price one token differently.
estimated is true when the rate is a starting point rather than a fact about the account (pricing.ProvBundled), or when there is no rate at all (pricing.ProvNone, or the tier is unset — the figure is then 0). Zero tokens price at 0 and are not an estimate of anything.
TierOutput is priced like any other tier; the library's TierTokens have no output, so only a host's own model calls reach it.
Cache write 1h tokens are a SUBSET of CacheWrite and have no Tier of their own (see pricing.Tier's doc), so they are priced by USD1h, not this function.
func USD1h ¶
func USD1h(r pricing.Resolver, endpoint, model string, promptTotal int, tokens int64) (usd float64, estimated bool)
USD1h is USD for 1-hour-TTL cache-write tokens, which price at pricing.Rates.CacheWrite1hRate rather than at a Tier's flat rate — see pricing.Tier's doc for why that rate has no Tier of its own. estimated is additionally true when CacheWrite1hRate itself falls back to the 5m rate.
func Units ¶
func Units(w config.SubscriptionWeights, tt accountant.TierTokens, output int) float64
Units values tokens in usage-limit units: each tier times its weight, plus output times the output weight. A negative count (a CacheEffect's Net) gives negative units.
Types ¶
type DetachedSpend ¶
type DetachedSpend struct {
Session, Thread, Operator, Model, Host string
At time.Time
Figures event.Figures
}
DetachedSpend is one booked detached model call, as a detached-spend listener receives it. Figures holds only the PluginSpend* fields: the call's cost by basis.
type DetachedSpendListener ¶
type DetachedSpendListener func(DetachedSpend)
DetachedSpendListener receives every detached model call Host books. It is called on the booking goroutine, with no Host lock held; it must not block. A panic in it is recovered.
type Extras ¶
type Extras struct {
// UnattributedBreakUSD is the net cost of every cache effect no applied op owns — not only
// breaks, despite the name, which is kept to match W7.1's Event.UnattributedBreakUSD: a break
// with no ChangeID (a change that had already ended), an effect whose ChangeID only a dry run
// reported, and a split, TTL or mark effect with no owning op. Positive is a cost; an unowned
// effect that saved makes it smaller. InBaseline effects are not in it: the client body would
// have had them too. Host.Savings also puts here the long-context re-rate that no op owns
// (accountant.USDFigure.UnownedReRateUSD). That is rare: the ops that moved the prompt size own
// the re-rate, so an op that pushes a prompt over a price line pays it.
UnattributedBreakUSD float64
// InteractionUSD is the net value of the tokens no operation owns on a rescued request:
// Result.Interaction minus Result.InteractionCaused, priced (design §6.2). A keep-alive ping kept
// the cache warm and an operator changed the body, so the client body would have written these
// tokens cold and the forwarded body read them. Positive saves. Signed. It belongs to no
// operator's saving, so it is in no Saving: it is counted in the session total only (W7.1's
// Event.InteractionUSD). The accountant metrics sink books the same figure as
// llm.savings.interaction.usd (rossoctl/cortex#2139). Set on basis "usd" only, the one basis the
// metrics price: a subscription request has no figure here, as it has none there.
InteractionUSD float64
// Thread is the accountant thread of the request. Savings leaves it empty: a Result does not
// name its thread. Host.Savings fills it, here and on each Spends entry.
Thread string
// OpsVersion is Result.Version, the version of the accountant rules.
OpsVersion int
// Spends are the request's spend ops — an operator's own model calls — one record each,
// priced with the call's own model, host and prompt size. A spend is shown beside the savings,
// never inside a Saving (W7.1).
Spends []event.SpendRecord
// Compaction is Result.Compaction: set on the first request after a client compaction, with
// the changes it ended (R55). nil on any other request.
Compaction *event.CompactionRecord
// Withheld is the W6.5 gate the request's Result failed (accountant.Withhold), or "". With one,
// Host.Savings books no saving, no UnattributedBreakUSD and no InteractionUSD (the sink books no
// interaction either): the figures come from a list of operations the library says is wrong,
// from an op it did not price, or from ops that saved more than the request had (the size
// bound). docs/pricing.md#withheld-savings lists all seven reasons. Spends stay: each is
// priced from its own model call, not from the Result's attribution.
Withheld string
}
Extras are the request-level figures of a Result that belong to no operator's saving (W7.1).
func Savings ¶
func Savings(res accountant.Result, price func(model, host string, tt accountant.TierTokens) (float64, bool), reqModel, reqHost string) ([]event.Saving, Extras)
Savings converts a Result into one event.Saving per operator, priced with price, as for a request billed per token (basis "usd"). It is SavingsBilled with accountant.BillingAPI, the default weights, and spend calls priced by price over their prompt tiers alone: price has no output tier, so a call with output tokens and no stated cost is priced low and marked estimated. Host.Savings prices the output.
func SavingsBilled ¶
func SavingsBilled(res accountant.Result, price func(model, host string, tt accountant.TierTokens) (float64, bool), spend SpendPrice, reqModel, reqHost string, mode accountant.BillingMode, w config.SubscriptionWeights) ([]event.Saving, Extras)
SavingsBilled converts a Result into one event.Saving per operator (accountant wiring W7.1), for a request billed in mode, with w valuing a subscription saving in usage-limit units.
For each operator:
- USD is the priced Saved of its ops, plus the priced Net of each cache effect with a positive Net under one of its ChangeIDs. A keep-alive rescue goes to KeeperOperator.
- PenaltyUSD is the priced Caused of its ops, plus the cost of each cache effect with a negative Net under one of its ChangeIDs — a break is ONE net cost, Caused priced minus Saved priced, never a saving of its Saved.
- Neither is floored or netted against the other: a negative net is kept as two figures.
- Tier is the tier with the largest Saved; TokensAvoided the sum of its Saved tiers, a size for display and never priced. Its ops' Saved only, plus a rescue's Saved for the keeper, which has no op: a split or mark effect moves tokens between tiers (a cache read in place of a write) and removes none, so its dollars are in USD and its tokens are not here. operatorTokens, which matches the proxy's dashboard, counts both sides of every owned effect; the two token figures differ by design.
- Estimated is true when any of its ops, its effects or the rates is estimated, and for every basis but "usd".
- Units and PenaltyUnits are set only on a subscriptionEquivalent saving.
An operator's dry-run ops are kept apart from its applied ones: they make a second saving for the operator with Projected set, so a "would have saved" amount never enters an applied figure. An operator with only dry runs has only the projected saving.
A spend op (an operator's own model call) is not a saving: it becomes one Extras.Spends record, priced with spend, and the operator gets no Saving for it. The record is flagged Projected for a dry run and Refused when res.Unpriced lists it; neither enters a spend total (event.SpendRecord.Counted).
A cache effect with InBaseline set is skipped: the client body has it too, so it is not part of the bill difference. One no applied op owns goes to Extras.UnattributedBreakUSD. Only an applied (non-DryRun) op owns a ChangeID: a dry run changed nothing upstream, so it caused nothing.
Result.Interaction minus Result.InteractionCaused, priced, goes to Extras.InteractionUSD, on basis "usd" only. It is in no Saving: no operator owns it (design §6.2).
The saving list is in the order each (operator, projected) pair first appears in res.Ops; KeeperOperator, which has no op on the request, comes last.
type Host ¶
type Host struct {
// contains filtered or unexported fields
}
Host is Cortex's accountant host: one per process, shared by every pipeline a reload builds, so the Tracker state survives a reload (Review Focus 5). It implements pipeline.RequestAccountant.
It holds nothing per request beyond the handle it leaves on the request's own pctx, and nothing per thread beyond what accountant.Trackers keeps (the library bounds that to 10,000 threads) plus one BillingMode per (session, thread) in threadBilling, for keep-alive pings (design §5.7), and one last forwarded body per (session, thread) in siblings, for EntryFacts.SharedWarm. Both are bounded the same way (threadBillingCap/threadBillingTrimTo).
func New ¶
New builds a Host. With a SnapshotPath it restores the saved Tracker state, when there is a usable one, and starts saving it every 60s.
New cannot fail: a snapshot that cannot be read only WARNs and starts fresh, because accounting fails open. So it returns no error, and a caller has no "accounting could not start" branch to get wrong.
func (*Host) AddCostRecorder ¶
AddCostRecorder adds a Recorder after New. cmd/cortex needs it: the Host must exist before the first pipeline build, and the ledger and the usage aggregator are opened after it.
func (*Host) AddDetachedSpendListener ¶
func (h *Host) AddDetachedSpendListener(fn DetachedSpendListener) (remove func())
AddDetachedSpendListener registers fn for every detached model call booked from now on, and returns the function that removes it. cmd/cortex's session store uses it: a detached call is not an event, so it reaches the store no other way.
func (*Host) AddKeyedPingListener ¶
func (h *Host) AddKeyedPingListener(key string, fn PingListener) (remove func())
AddKeyedPingListener is AddPingListener for a consumer that a config reload builds again: of the live registrations under one key, ONLY THE NEWEST IS CALLED. The reloader starts the new pipeline (its plugins' Init) before it stops the old one, and the old one can drain for minutes; with two plain listeners, a consumer that writes shared state (session-budget's Redis counters) would count every ping twice for that time. Removing the newest registration gives the turn back to the one before it, so a reload that fails after the new instance's Init leaves the old instance counting. Removing an older one only drops it. key names what the consumer counts into, so two consumers that share it are one counter; an empty key is a plain listener.
func (*Host) AddPingListener ¶
func (h *Host) AddPingListener(fn PingListener) (remove func())
AddPingListener registers fn for every ping Host.Ping accounts from now on, and returns the function that removes it. A ping is not agent activity, so it never passes through the session store or the pipeline; this is how the consumers that must still count its cost see it. For a process-wide consumer (cmd/cortex's session store). A plugin uses AddKeyedPingListener.
func (*Host) ClearReadSetsTTL ¶
ClearReadSetsTTL removes the registration token names, unless a newer one has already replaced it.
func (*Host) Close ¶
Close stops the snapshot saver and writes a final snapshot. Safe to call more than once.
func (*Host) Compute ¶
Compute prices pctx's request with the usage the response billed, once: a second call returns the first call's answer, so a repeated settle cannot price twice. ok is false when there is no record (non-inference traffic, a refused request), when a W6.1 rule skips it, when the record is not ended within computeWait, and when the library panics. All of those record the request with no saving: accounting fails open.
The Tier 1 counters (llm.inference.tokens, cost_usd, estimated_cost_usd, llm.cache.misses) book every request whose response reports usage, also when ok is false (rossoctl/cortex#2013): the skips keep the saving correct, and the provider bills the request whatever the accountant does. A priced request books them with its Result (observe); every other request books them in bill.
func (*Host) LateOps ¶
LateOps implements pipeline.LateOpsAccountant. It returns the handler for pctx's context operations that are reported after the request was accounted: a model call that an engine detached from the request, such as a background summarizer (cortex#2140, wiring W4.8 B).
The handler keeps each spend that has a Call, and books it on its own goroutine as a standalone spend (bookDetached). It keeps no other kind: a late rewrite cannot change bytes that were already sent. A request with no session gets no handler, as RequestEnd starts no record for it.
func (*Host) Ping ¶
func (h *Host) Ping(sessionID string, client *model.EventClient, host string, p accountant.Ping, info PingInfo) (res accountant.Result, ok bool)
Ping accounts for one keep-alive ping: a spend on the thread it kept warm, and the facts the thread's next request needs to credit the rescue under the same ChangeID (design §5.8, wiring W4.6). Ported from the context-guru proxy's PingSavings, minus the dashboard.
It refuses (ok false, nothing recorded, nothing kept) a ping with no Window — its ChangeID would be shared by every such ping —, a status outside 200-299, a timeout, or no usage: it billed nothing that can be priced. A refused ping is still counted once in llm.keepalive.pings, by outcome, and a timeout books its projected cost there (countPing); a priced ping is counted by the observation instead. The billing mode is that of the thread's last request (design §5.7), because a ping uses the same credential.
A manual ping is priced and recorded, but its facts are not kept: the write it avoided is already booked on its own row from the user's estimate, and a library rescue on the next request would credit the same write again (context-guru#768 B3).
The ping's spend is written to the cost recorders (the ledger writer and the usage aggregator) as a response event whose cost record has Purpose PingPurpose. It never goes through the session store: a ping is not agent activity, and counting it as activity would distort the idle tracking keep-alive depends on.
host is the upstream the ping was sent to; it prices the ping and labels its event. A panic in the library is recovered and reported as not ok: the keeper calls this on its own goroutine.
func (*Host) RequestBasis ¶
RequestBasis is the event.Event.Basis of a request's own cost: the billing mode Savings and the metrics sink use, so the ledger books its cost as money only where the sink counts dollars.
func (*Host) RequestEnd ¶
RequestEnd implements pipeline.RequestAccountant. It takes what the record needs from pctx and starts the record on a goroutine of its own: the parse, BeginRequest, each op and EndRequest never run on the request goroutine (global constraint).
Traffic that is not an inference request, or that has no session to key a thread on, starts nothing and logs nothing (Review Focus 2). The one exception is a request on a path FormatOf does not know that an operator still reported ops on: it gets one DEBUG line, because its saving is lost.
A request a plugin asked to translate (pctx.TranslateTarget) also starts nothing: the listener converts the body to the target protocol in startTranslation, which runs after Run returns, so at this point pctx.Body is still the client-protocol body. wire.FormatOf(pctx.Path) and facts.Classify both key on the client's own path, so a record built here would classify and price a request under the wrong protocol's caching rules — the provider bills the converted body under its own. The same TranslateTarget check also covers a translation the listener later refuses: RequestEnd has no later chance to undo the record it would otherwise start, and a refused request must start no accounting work (pipeline/accounting.go).
func (*Host) RequestStart ¶
RequestStart implements pipeline.RequestAccountant. It reads pctx.BillingSnapshot() — captured by the FIRST Pipeline.Run call on this pctx, before any plugin of either direction can rewrite the credential header BillingFrom reads — and stores the billing mode it implies for RequestEnd. It does NOT call accountant.BillingFrom itself: this hook runs on the outbound Pipeline, which on every listener runs its Run AFTER the inbound chain's own Run on the same pctx, so reading the header fresh here would see jwt-validation's placeholder_mode or token-exchange's rewrite of Authorization instead of the client's own credential — silently misclassifying the billing mode as "unknown" and zeroing every saving's dollar total for the request. BillingSnapshot's own doc comment has the detail.
accountant.BillingFrom reads only the credential's type and returns no part of the credential itself (accountant R2); only the resulting mode is stored, never the header value.
func (*Host) Savings ¶
Savings is Compute, then SavingsBilled: pctx's request priced with the process rate table, at the request's model and the endpoint it was sent to (after any redirect: the server that bills). accountant.Figure gives the dollars of the applied ops and the cache effects, so each side is priced at its own prompt size and a saving is the whole bill difference (rossoctl/cortex#2135). A dry run is priced at the billed prompt total. It is priced in the billing mode the client's credential implied, with the configured subscription weights. Extras.Thread is the request's accountant thread. ok is Compute's: false when there is no Result, so there is no figure — EXCEPT that a request with a reported spend (an operator's own model call, pctx.ReportedOps) still answers ok with just that spend, savings excluded, when Compute refused for a reason that is about PRICING THE REQUEST rather than about the request at all (review finding: an error status with no prompt usage, or a context-guru call billed before an inference-router resend took the request past one round, used to lose the spend along with the never-priced savings). A spend prices from its own operator call (spendRecord) — it does not need the library's Compute, which is what makes this safe to do without it: Compute's thread-state transition is skipped entirely, so a multi-round request's mismatched usage/body pair cannot corrupt the thread's cache-effect tracking for later requests, which is the actual reason Compute refuses one. Latched like Compute, so a repeated settle gets the same answer either way.
A Result that fails a W6.5 gate (accountant.Withhold, run once in Compute: a fatal check, an op or cache effect unpriced for a reason other than penalty_unknown, or the size bound) books no saving: ok is true, the savings are empty, and Extras.Withheld names the gate. Its spends stay. A penalty_unknown op marks every saving Estimated instead. SavingsBilled runs no gate: it converts whatever Result it is given.
func (*Host) SetReadSetsTTL ¶
func (h *Host) SetReadSetsTTL(fn ReadSetsTTLFunc) (token uint64)
SetReadSetsTTL registers fn as the current ReadSetsTTL source and returns a token. A config reload's new plugin instance calls this again before the old instance's Shutdown runs (plugins.Deps ordering); pass the returned token to ClearReadSetsTTL so a late Shutdown from the OLD instance cannot clear a registration a newer one already replaced it with.
func (*Host) ThreadBilling ¶
func (h *Host) ThreadBilling(session, thread string) accountant.Billing
ThreadBilling returns the billing mode of the given thread's last request, for a keep-alive ping on that thread: a ping uses the same credential as the request it pings for (design §5.7). accountant.BillingUnknown if the thread has made no request yet.
type Options ¶
type Options struct {
// Resolver is the process rate table. Savings prices every Result with it (USD, TierUSD).
Resolver pricing.Resolver
// SnapshotPath is where the Tracker state is saved every 60s and on Close, and restored
// from at New. Empty means no snapshot: in a cluster a pod restart starts fresh (design §5.4).
SnapshotPath string
// CostRecorders receive the cost record of spend the host makes outside a request (the
// keep-alive ping, a later task). The ledger writer and the usage aggregator, the same
// Recorders the session store feeds.
CostRecorders []session.Recorder
// Now is the clock. Nil means time.Now.
Now func() time.Time
// SubscriptionWeights value a saving on a subscription login in usage-limit units
// (accounting.subscription_weights). Nil means config.DefaultSubscriptionWeights.
SubscriptionWeights *config.SubscriptionWeights
// Sink receives each computed request's Result, once, and each keep-alive ping's, for the
// llm.savings.* counters (design §5.10). Nil means no metrics.
Sink *Sink
}
Options configure a Host.
func OptionsFrom ¶
OptionsFrom is the Options every binary builds its Host from: the process rate table, the config's accounting.subscription_weights, and the metrics sink. cmd/cortex and cmd/cortex-envoy both start here, so a setting the accounting block carries cannot reach one binary's host and not the other's (review finding: cortex-envoy priced every subscription saving with the default weights). A binary adds what only it has on top, such as the laptop's SnapshotPath.
type PingInfo ¶
type PingInfo struct {
// Status is the ping's HTTP status. A ping outside 200-299 is refused.
Status int
// Manual marks a ping the user asked for. It is priced, but its facts are not kept (see Ping).
Manual bool
// Duration is how long the ping took, for the cost event.
Duration time.Duration
// TimedOut marks a ping that ran to the keeper's timeout with no answer (#754). It has no
// usage, so it is refused like any other unpriced ping, but it is counted as a timeout.
TimedOut bool
// ProjectedUSD is the keeper's projected cost of a timed-out ping. The provider probably
// billed it, so llm.keepalive.cost_usd books it, all of it as estimated. It is the one
// figure Cortex takes from the keeper rather than pricing itself: there is no usage to price.
ProjectedUSD float64
}
PingInfo is what the host knows about a ping beyond accountant.Ping: the library type carries neither the response status nor whether the user asked for the ping.
type PingListener ¶
type PingListener func(PingSpend)
PingListener receives every ping Host.Ping accounts. It is called on the keeper's goroutine, after the ping is recorded, with no Host lock held; it must not block. A panic in it is recovered and logged, and the other listeners still run.
type PingSpend ¶
type PingSpend struct {
Session, Thread, Model, Host string
At time.Time
Usage accountant.CallUsage
Figures event.Figures
}
PingSpend is one accounted keep-alive ping, as a ping listener receives it: the tokens it billed and its spend split by basis (only the KeepAlive* fields of Figures are set; all zero when the ping was not priced).
type ReadSetsTTLFunc ¶
ReadSetsTTLFunc reports whether a read sets the entry's TTL on this route (the keeper's own readSetsTTL rule), so RequestEnd can set EntryFacts.Provider.ReadSetsTTL (accountant R# — see internal/engine/compute.go's Provider.ReadSetsTTL doc) before it prices the request. provider is Cortex's own wire-dialect classification (facts.Provider), the same one facts.For uses; a plugin that needs a richer provider enum (bschemas.ModelProvider) converts it itself — core/accounting does not import context-guru. pinged is whether this request's thread carried ping facts into this record (end's p.pinged).
type RequestRatio ¶
type RequestRatio struct{ Tokens, Bytes int }
RequestRatio is the request ratio Compute priced pctx's request with: the provider's billed tokens of the forwarded text and its bytes (accountant.Ratio.Text). A host reads it after Compute and keeps it for the thread's next turn (lifecycle.Fin.RatioTokens/RatioBytes).
func RequestRatioOf ¶
func RequestRatioOf(pctx *pipeline.Context) (RequestRatio, bool)
RequestRatioOf returns the request ratio Compute priced pctx's request with. ok is false when Compute booked no figure for it (no record, no usage, or a ratio that was skipped, out of range or capped): the host then keeps its last ratio rather than overwriting it with 0. It reads the latched answer off the request's pending handle, under the same lock Compute sets it with, so a call that races Compute reads either 0 or the final figure, never a half-written one. Call it after Compute (lifecycle order: Compute runs in the response phase, this in OnFinish).
type RequestWindow ¶
type RequestWindow struct {
// Window is the model's context window in tokens, 0 when the host does not know it.
Window int
// Exact says Window is a figure published for THIS model, not a family guess. A guess is not
// handed to the library, which declines every fraction trigger on an inexact window anyway.
Exact bool
// CompactionPoint is where the client's own compaction acts, in provider-billed tokens; 0 when
// the host does not know it.
CompactionPoint int
}
RequestWindow is a host's per-request window facts, which it stashes on pctx for RequestEnd to read (cortex#2280 item 3). It carries the model's resolved context window and the client's own compaction point to accountant.RequestMeta.Window and CompactionPoint. A request no host set it on leaves both at 0: the library then uses its own default window for the model.
type Sink ¶
type Sink struct {
// contains filtered or unexported fields
}
Sink hands each computed Result to accountant/metrics, which adds it to the llm.savings.* counters (design §5.10). It makes no network call: the counters are read by the MeterProvider's own reader (core/accounting/push), on its own goroutine.
The library's Pricer has no endpoint and no prompt total (accountant/docs/metrics.md), and Cortex's rates depend on both. So the pricer is bound to one observation at a time: Observe holds mu, sets that observation's bindings on the pricer, calls the library's Observe, and releases mu (design §5.6). The library's Observe only adds to in-memory counters, so the lock is held for microseconds.
The pricer is given only a model, so the bindings are keyed by model (bindingsFor): the request's model prices at the request's endpoint and prompt total, as the ledger's savings do, and a spend call's model at the call's own host and prompt total, as the ledger's spends[] do (CallUSD).
func NewSink ¶
func NewSink(mp metric.MeterProvider, r pricing.Resolver) *Sink
NewSink builds the sink on mp, priced with r through USD, the function the ledger prices with. It returns nil, a no-op sink, when mp is nil (no push configured) or the meter refuses an instrument. Every instrument must be created or none is: a Sink with some Tier 1 counters missing would make Observe branch on which fields are non-nil instead of failing closed like the rest of this constructor.
func (*Sink) CountPing ¶
func (s *Sink) CountPing(model, endpoint, outcome string, projectedUSD float64, mode accountant.BillingMode)
CountPing counts a ping the Host refused to price (Host.Ping): one llm.keepalive.pings with outcome, counted whatever the billing mode — this is a count, not money. projectedUSD is the keeper's projected cost of a ping with no answer; it is booked as cost and, all of it, as estimated cost, because the provider probably billed the ping but nobody measured it, and only for mode == accountant.BillingAPI, the same gate Observe applies (design §5.7a: a ping's basis is the thread's). 0, or a non-API mode, books no money. A priced ping is counted by Observe instead, never here too. Safe on a nil Sink.
func (*Sink) CountTTLDowngrade ¶
CountTTLDowngrade counts one priced request whose 1h cache ask was billed at 5m (#2136). Safe on a nil Sink.
func (*Sink) Observe ¶
func (s *Sink) Observe(meta accountant.RequestMeta, u accountant.Usage, output int, res accountant.Result, endpoint string, promptTotal int, firstOnThread bool)
Observe adds one computed request, or one ping (an empty RequestID), to the counters. output is the response's generated tokens: accountant.Usage holds only the prompt tiers, so the output tier reaches the Tier 1 token and cost counters through this argument. endpoint and promptTotal are the ones the ledger priced the request at: the server that billed (after any redirect) and the request's whole prompt. A panic in the library or the pricer is recovered and logged: it costs this observation and nothing else. Safe on a nil Sink.
firstOnThread says the request is its thread's first that the Host has seen (missCause). It is ignored for a ping.
Money moves only for meta.Billing.Mode == api; this sink decides that for the Tier 1 (llm.inference.*/llm.keepalive.*/llm.cache.*) dollar counters, in observeInferenceMetrics. The library decides it for llm.savings.*, through acmetrics.
func (*Sink) ObserveBill ¶
func (s *Sink) ObserveBill(meta accountant.RequestMeta, u accountant.Usage, output int, endpoint string, promptTotal int, cause string)
ObserveBill adds a request the accountant did not price to the Tier 1 counters alone (llm.inference.*, llm.cache.*), priced at endpoint and promptTotal as Observe prices them. It books nothing in llm.savings.*: there is no Result (rossoctl/cortex#2013). cause is the llm.cache.misses cause. Safe on a nil Sink.
func (*Sink) ObserveDetached ¶
func (s *Sink) ObserveDetached(meta accountant.RequestMeta, res accountant.Result, endpoint string)
ObserveDetached adds a detached model call's Result (Host.LateOps) to the llm.savings.* counters, with its spends bound to their own model, host and prompt size, as Observe binds an in-request spend. It books no llm.inference.* or llm.keepalive.* figure: the call is not the agent's request and not a ping. The library sink counts each Result it observes in llm.savings.requests (and llm.savings.estimated when it is estimated), so a detached call adds 1 there, as a priced keep-alive ping does. Safe on a nil Sink.
func (*Sink) ObserveSized
deprecated
func (s *Sink) ObserveSized(meta accountant.RequestMeta, u accountant.Usage, output int, res accountant.Result, endpoint string, promptTotal int, firstOnThread bool, tokensBefore int)
ObserveSized is Observe, with a tokensBefore this version ignores. accountant v0.11.0+ gates every call on the library's own measure (Result.MessageTokens); a host size is no longer read.
Deprecated: call Observe instead. Kept only so that an external caller of the pre-cortex#2159 signature still builds; a nonzero tokensBefore no longer applies a size gate of its own.
type SkipInput ¶
type SkipInput struct {
// Status is the upstream response status. 0 means no provider answered (for example, a
// request the proxy answered itself, such as /compact): that is not a rejection.
Status int
// Rounds is the number of upstream round trips this one client request caused. More than one
// means a single usage object does not describe a single forwarded body.
Rounds int
// SessionID is empty when the request has no session: the thread key (design §5.4) needs one.
SessionID string
// ServerHeldHistory is true for an OpenAI Responses request whose prompt history the
// provider holds (previous_response_id, conversation, or an item_reference input item): the
// body this host sees holds only the new turn, and the library would read the missing
// history as a client edit (W6.1, #899).
ServerHeldHistory bool
// UnplacedDeferral is true when a tool deferral (or similar body rewrite) could not be
// described to the library: computing on the bodies as they are would fail the library's sum
// check (W6.1).
UnplacedDeferral bool
}
SkipInput is what the host knows about a finished request, before it decides whether to call accountant.Request.Compute (accountant/docs/cortex-wiring.md W6.1).
type SpendPrice ¶
type SpendPrice func(c *accountant.ModelCall, host string) (usd float64, estimated bool, currency string)
SpendPrice prices one model call an operator made: its whole bill, output included, at the call's own model and host (host is the request's when the call names none) and its own prompt size. estimated follows USD's rule. currency is the unit usd is denominated in, empty for the default (USD) — event.SpendRecord.Currency's own convention — because the call's own host can resolve to a different rate table than the primary request's (a credits-billed gateway beside a USD-endpoint operator call, review finding): usd is never assumed to be the request's currency just because the field is still named USD.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package facts classifies which LLM provider a request went to, and gives the cache facts (accountant.EntryFacts) that provider's prompt cache has for a model.
|
Package facts classifies which LLM provider a request went to, and gives the cache facts (accountant.EntryFacts) that provider's prompt cache has for a model. |
|
Package push sends Cortex's accountant counters (llm.savings.*) to the central collector over OTLP/HTTP (design §5.10).
|
Package push sends Cortex's accountant counters (llm.savings.*) to the central collector over OTLP/HTTP (design §5.10). |
|
Package reqstats pushes the llm.inference.* transport metrics (requests by status class, duration, time-to-first-byte, time the proxy added, request/response bytes) that core/accounting/metrics.go's per-request accountant data cannot provide, because that call site never sees an HTTP status, a wall-clock duration, or a byte count.
|
Package reqstats pushes the llm.inference.* transport metrics (requests by status class, duration, time-to-first-byte, time the proxy added, request/response bytes) that core/accounting/metrics.go's per-request accountant data cannot provide, because that call site never sees an HTTP status, a wall-clock duration, or a byte count. |
|
Package wire reads an inference request body into the shape github.com/rossoctl/accountant hashes: tools, then system, then messages, one []byte per position, in the provider's cache order (accountant/docs/cortex-wiring.md W6.3).
|
Package wire reads an inference request body into the shape github.com/rossoctl/accountant hashes: tools, then system, then messages, one []byte per position, in the provider's cache order (accountant/docs/cortex-wiring.md W6.3). |