usage

package
v0.0.0-...-53bd38a 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: 15 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 usage aggregates session events into fixed-width time buckets so a client can chart volume, errors, latency and cost over wall-clock time.

It lives server-side on purpose. An aggregate built inside a client would start empty when that client connected, so two operators watching the same pod would see different histories of the same traffic — and neither would see anything from before they attached. The store is the only place with the whole picture, so the arithmetic belongs next to it.

Memory is O(buckets x distinct labels), independent of event volume: mean and standard deviation come from running sums (count, sum, sum-of-squares) rather than from retained samples, and every bucket is preallocated in a fixed ring. Nothing here grows with traffic.

Index

Constants

View Source
const (
	// BucketWidth is the storage resolution. Every window the API offers is a
	// whole multiple of it, and clients fold buckets together for wider views
	// rather than asking the server to pre-aggregate — one storage shape, and a
	// client is free to pick its own on-screen resolution.
	BucketWidth = time.Minute

	// NumBuckets covers the longest window offered (6h). The ring is
	// preallocated at this size for both the all-sessions aggregate and each
	// tracked session.
	NumBuckets = 360

	// MaxWindow is the longest span Snapshot will return.
	MaxWindow = NumBuckets * BucketWidth
)
View Source
const (
	KindInput uint8 = 1 << iota
	KindCacheRead
	KindCacheWrite
	KindOutput
	KindReasoning
)

The PresentKinds bits, one per token kind a provider can report.

EXPORTED, AND HERE, because PresentKinds is where the layout is documented and this is the package every consumer of it already imports. The authority is core/internal/parsercommon.Kind, which cannot be imported from outside core — so before these existed, every reader spelled the bits itself: agentop's `cost` command, agentop's spend strip, and this package's own tests as a bare `1 | 8`. Three uncoordinated copies of a wire format, with nothing comparing them.

TestKindBits_MatchTheParserThatProducesThem, which lives with parsercommon, is what pins these to it.

WIRE FORMAT: they are serialised in PresentKinds and stored in the cost ledger, so they cannot be renumbered whatever any Go identifier is called.

View Source
const (
	WindowToday = "today"
	Window7d    = "7d"
	WindowMonth = "month"
)

WindowToday, Window7d and WindowMonth are the symbolic windows the API accepts.

Symbolic because none is a LENGTH: "today" and "month" are boundaries, and while "7d" has a fixed span it is longer than the ring retains, so all three can only be answered from the durable cost ledger. time.ParseDuration reads none of these strings, which is why ParseWindow already rejects them and why they need their own parse.

"month" RATHER THAN "mtd", because "today" is already a boundary word rather than a length and this joins that family. "mtd" is less ambiguous read cold, at the cost of a second naming convention on the same small enum; the label is echoed back on the wire either way, so a client always learns which window it got. It means month-TO-DATE — since the first of the local month, not a rolling thirty days — which is what a budget that resets on the first is measured against.

View Source
const MaxSeriesInResponse = 16

MaxSeriesInResponse bounds how many label series ONE RESPONSE carries, per bucket.

A SEPARATE BOUND FROM maxLabelsPerBucket, and the reason both exist is that they bound different things. That one is a MEMORY bound at record time: 64 per axis, so a caller varying a label per request cannot grow this process. This one is a RESPONSE bound, and nothing was enforcing it — the two multiply. Measured on the endpoint as shipped: window=6h&resolution=1m&group=session is 360 buckets times up to 64 series, which produced a 4.7 MB response from a single unauthenticated GET.

SIXTEEN, because the response is something a person reads. A by-model or by-agent breakdown past a dozen rows is not a breakdown anyone consumes; the rest belongs in the (other) band, which every client already renders because the record-time cap has always produced it. That is the property that makes this cheap: no new wire vocabulary, and a client written against the old shape shows a correct total with one extra row.

RANKED ACROSS THE WHOLE WINDOW, not per bucket, which is the part that has to be got right. Capping each bucket independently would let the SAME label be a series in one minute and part of (other) in the next, so a chart would show a line appearing and vanishing while the traffic behind it was steady. The ranking is by cost, because this is a cost API and the question "where did the money go" is the one the top of the list has to answer.

View Source
const UnknownProjectLabel = "unknown"

UnknownProjectLabel is the GroupProject series of an event with no project. A whole project label starts with "/" or "~", and a cut one is at least 93 bytes, so neither is this one.

View Source
const Window7dLocalDays = int(Window7dSpan/(24*time.Hour)) + 2

Window7dLocalDays is the MOST distinct LOCAL DATES a 7d window can touch: NINE.

A CEILING, NOT A COUNT. Eight is what the window touches in an ordinary week, and it is wrong once a year in every zone that observes DST.

Two increments, for two different reasons:

  • +1 because the span is ROLLING rather than calendar-aligned. Unless it begins exactly at midnight it starts part-way through one date and ends part-way through another — seven days' worth of hours spread across eight dates. Asked at 15:30 it runs from 15:30 seven days ago to 15:30 today and needs a piece of every date between, both ends included. Asked exactly at midnight it needs the eighth date for one instant, which is still a file to open.
  • +1 again because A SPRING-FORWARD WEEK IS 167 HOURS. Eight assumed every day in the week is 24 hours long, and one week a year is not: a 168-hour span reaches an hour further back than a calendar week does. MEASURED at 00:00 local on 2026-03-15, From lands at 23:00 on 2026-03-07 and the window touches NINE dates — in America/Havana, in America/Santiago and in America/New_York alike, because this has nothing to do with WHERE in the day the transition falls. Autumn is the harmless direction: a 169-hour week means the span reaches less far and the ceiling is slack by a day.

It is therefore the number of DAY FILES a durable ledger must still hold to answer this window, which is why config's retention floor is derived from this rather than written as its own independent number. As two constants that had to agree, they did not: a floor of 7 let retention_days: 7 pass validation and then answer window:"7d" over a partial week — the exact case the floor exists to refuse.

COSTS ONE DAY FILE OF RETENTION ALL YEAR to cover two mornings of it, and that is the trade taken deliberately. The alternative considered was making 7d CALENDAR-ALIGNED, which is the more correct fix — it would make the count exactly 8 and true every week — but it changes what the window MEANS on the wire: "the last 7 days" and "since midnight 7 days ago" differ by up to a day of spend, every client comparing figures across the change would see a step, and ParseWindowSpec's own doc promises the rolling reading. That is a product decision, so it is disclosed rather than made here. A day file is roughly 300 KB at the volumes this ledger is sized for; the partial week it prevents is a wrong dollar total that nothing downstream can detect.

Distinct from the local-midnight defect StartOfLocalDay fixes: 7d's From is a plain duration subtraction from now and contains no calendar arithmetic at all. TestParseWindowSpec_SevenDaysTouchesAtMostWindow7dLocalDays pins the ordinary week and TestParseWindowSpec_ASpringForwardWeekReachesTheNinthLocalDate pins the week that forced the second +1. The agreement with config's retention floor is pinned on the CONFIG side, by TestCostLedgerConfig_TheFloorCoversEveryDayTheWindowTouches, which this change adds along with the cost_ledger settings it guards.

View Source
const Window7dSpan = 7 * 24 * time.Hour

Window7dSpan is what "7d" MEANS: a rolling seven times twenty-four hours back from now. Stated once, and read by ParseWindowSpec, so nothing that has to reason about the span can spell it differently.

View Source
const WindowMonthLocalDays = 31

WindowMonthLocalDays is the MOST distinct LOCAL DATES a month-to-date window can touch: THIRTY-ONE, the length of the longest calendar month.

NO +1, unlike Window7dLocalDays, and the asymmetry is the whole difference between a boundary window and a rolling one. 7d needs two increments because it starts part-way through a date and because a spring-forward week is 167 hours, so it reaches an hour further back than a calendar week does. This window's From IS a date boundary — StartOfLocalMonth returns the first instant of the first — so it begins exactly where a day file begins and cannot spill onto an earlier date. A DST transition inside the month moves which instants the window covers but not the set of DATES, and a date is what a day file is named by.

It is therefore the number of day files a durable ledger must hold to answer this window on the 31st of a 31-day month, which is why cost/ledger's default retention is derived from this rather than written as its own number — the lesson Window7dLocalDays records about two constants that had to agree and did not.

Variables

This section is empty.

Functions

func CapSeries

func CapSeries(series map[string]Counts, n int) map[string]Counts

CapSeries folds everything past the n costliest entries into the (other) band.

EXPORTED FOR cost/ledger, which serves the symbolic windows from disk and had no bound of its own at all: its rows come from day files, so the number of distinct (endpoint, model, agent) keys in a response is however many a month of traffic produced. One map rather than a whole snapshot, because that source answers with a single bucket.

Ranked by cost, ties broken by requests and then by label, so the answer is deterministic — a breakdown whose membership changed between two identical requests would be worse than an unbounded one, because a client could not tell a traffic change from a tie-break.

The (other) entry is Counts.Add-ed, so every field it carries is summed by the one summation point and a field added to Counts is carried here with no edit.

func CountsAsError

func CountsAsError(e *model.SessionEvent) bool

countsAsError reports whether e is a failed exchange for Counts.Errors: a status of 400 or more, a denial, or an explicit error on the row. The last matters for the one row that keeps a success status on purpose: a streamed response the upstream broke mid-body has no 502 to synthesize — the status is already on the wire — so its row keeps the sent 200 with the failure in Error (#1543). Keying on status alone counted those as healthy, which is what #1543's rows exist to stop.

Except a proxy-declined WebSocket upgrade (model.ErrorKindUpgradeDeclined). Its 426 is Cortex telling Codex to use HTTPS, which it then does, once per session: by design and on the default path, so counting it would give every healthy Codex fleet a nonzero error rate. The Finisher sees it as an allow for the same reason.

And except the egress guard's refusal (model.ErrorKindDestinationPrivate). Same shape, same reasoning: its 403 is the guard doing exactly what the operator configured it to, on traffic that was never going to be allowed through — a nonzero "error rate" made of refusals is the policy working, not the proxy failing. The Finisher sees it as an allow for the same reason.

func FoldSeriesAcrossWindow

func FoldSeriesAcrossWindow(buckets []Bucket) map[string]Counts

FoldSeriesAcrossWindow sums each series label's Counts over every bucket, giving one total per label for the whole window.

EXTRACTED FROM capSeriesAcrossWindow, which carried this loop inline to build the ranking it caps by, and exported because two consumers outside this package need the same answer: agentop's AGENTS pane, which renders one row per agent for the window, and `agentop cost --agent`, which needs one label's total plus the set of labels to name in a "no such agent" error. Either writing the loop again would be a second definition of what a window total means.

THROUGH Counts.Add, which is the reason it is worth sharing rather than retyping: Add saturates and records it in Saturated, where a hand-written `+=` wraps negative. The consumers that RANK OR COMPARE the result are the ones that argument is for: a wrapped cost total sorts BELOW a ten-micro one, so in the pane that orders agents by spend it silently moves the biggest spender to the bottom. rankSeriesByCost's godoc in agentop records the same trap being hit for real. `agentop cost --agent` looks up a single label and does neither, and wants the same saturating answer anyway — one definition of a window total, not two.

Returns an empty map rather than nil for no buckets, so "no traffic" is an empty answer and not something a caller has to nil-check.

func ParseResolution

func ParseResolution(s string, window time.Duration) (time.Duration, error)

ParseResolution validates a resolution parameter — the width of the buckets the caller wants back, as opposed to the window's total span.

Folding happens server-side so every client gets the same arithmetic. A 1h window at 1m resolution is 60 bars, which no terminal renders legibly; at 5m it is 12. Doing that here rather than in each client means the mean-of-means problem below is solved once, correctly, instead of per consumer.

Zero or empty means "storage resolution" (BucketWidth). A resolution finer than BucketWidth is an error rather than a silent upgrade: returning coarser data than asked for would make a client's axis labels wrong.

func ParseResolutionUnbounded

func ParseResolutionUnbounded(s string) (time.Duration, error)

ParseResolutionUnbounded validates a resolution that will not be used to slice anything, so only the checks that do not depend on a window apply.

FOR THE WINDOW THAT IS ANSWERED AS ONE BUCKET. A symbolic window served from the cost ledger returns a single bucket spanning the whole window and never reads the resolution — so validating it against the RING's maximum refused requests that were fine: window=7d&resolution=7m came back 400 because 6h does not divide by 7m, while 7m divides seven days exactly (1440 buckets). The bound was a property of a window the caller had not named and of a code path that was not going to run.

The two remaining checks are still meaningful, because they are about the STORAGE bucket rather than the window: a resolution finer than BucketWidth or not a multiple of it cannot be honoured by any window. And a malformed value is still refused rather than ignored, so a typo in a parameter this path does not read is not silently accepted.

NOT ParseResolution(s, MaxWindow), which is the shape I first wrote and which reproduces the very defect: MaxWindow is 360 minutes, so a 7m resolution fails the divisibility check against it just as it did against the 6h window. "Unbounded" has to mean the checks are skipped, not that a wide window is passed.

func ParseWindow

func ParseWindow(s string) (time.Duration, error)

ParseWindow validates a window parameter against the storage resolution.

Durations ONLY. It rejects the symbolic windows "today", "7d" and "month", because a time.Duration genuinely cannot express a boundary and silently substituting a length would report a number for a span nobody asked for. Callers that accept those use ParseWindowSpec, which delegates here for every fixed length so the duration rules are defined once.

func PriceableRequest

func PriceableRequest(e *model.SessionEvent) bool

PriceableRequest is the ledger's definition of "this request could have been priced" (#1566), matching costOf's arms: the parser recognised the traffic well enough to name a model, and the request either carried usage or was not a failure — a truncated OpenAI-dialect stream succeeds at the HTTP layer but yields no counters, and hiding it from the denominator made coverage read "9/9 priced" while real spend was missing. A FAILED response WITH usage is priceable: the counters exist and the rates apply. Usage is read through pricing.UsageFromInference, as costOf reads it.

func ProjectLabel

func ProjectLabel(p string) string

ProjectLabel is the GroupProject series label of the project path p. It keeps the END of a long path, like ledger.projectRowLabel, so the ring and the ledger spell one project the same way.

func ReplayCopy

func ReplayCopy(e *model.SessionEvent) model.SessionEvent

ReplayCopy is e reduced to what Record reads, for a caller that holds many events before replaying them: an archived inference event carries its whole conversation, and six hours of those would otherwise sit in memory at once to be sorted. A copy costs about 1KB, however long the conversation was.

A COPY WITH THE HEAVY FIELDS CLEARED, NOT A COPY OF THE FIELDS RECORD READS, so a field Record starts reading later is kept without anyone remembering to add it here. What is cleared is what Record has no use for: the protocol payloads, the conversation, the tool manifest, the completion and its tool calls, the tool calls and results the request re-sends, and every plugin entry but the cost record. TestReplayCopy_RecordsWhatTheEventDoes holds that.

func SortSeriesLabels

func SortSeriesLabels(labels []string, series map[string]Counts)

SortSeriesLabels orders labels IN PLACE by what they cost, descending, breaking ties on the label.

ONE DEFINITION FOR EVERY SURFACE THAT RANKS A BREAKDOWN. agentop's AGENTS pane and `agentop cost --by` show the same series in the same order, and the rule lives here so the two cannot drift — the spend drawer's rankSeriesByCost records what it cost the last time a consumer wrote its own.

THE TIE-BREAK IS LOAD-BEARING, not tidiness. Every UNPRICED series has CostMicros 0, so until billing units land the label is the entire order for all of them; and these rows are rebuilt on every poll, so without it equal-cost entries swap places between reads under a reader trying to compare them.

A SLICE, NOT A MAP, and the signature is the point. Ranking straight out of a map takes the tie order from Go's randomised walk, and sort.Slice is unstable, so the tied block is permuted by the sort itself — a test for the tie-break could then only catch its deletion when the random order happened to be wrong. Given a slice the result is a pure function of the input and the assertion holds every run.

A label absent from series sorts as zero cost: the map lookup yields the zero Counts, which keeps the ordering total rather than panicking, and the label tie-break still places it stably.

func StartOfLocalDay

func StartOfLocalDay(t time.Time) time.Time

StartOfLocalDay is the earliest instant that EXISTS on t's local calendar date, in t's own zone. It is the lower bound of "today".

IT IS NOT time.Date(y, m, d, 0, 0, 0, 0, loc), and the difference is money. In a zone whose DST transition falls AT 00:00 the spring-forward day has no midnight at all, and time.Date resolves a wall time inside the gap onto the far side of it. MEASURED, with that expression as the bound:

now  = 2026-03-08 15:00 -0400 America/Havana
From = 2026-03-07 23:00 -0500   ← an hour before the previous day even ended
now  = 2026-09-06 15:00 -0300 America/Santiago
From = 2026-09-05 23:00 -0400   ← same shape

So window=today reached an hour and fifty-nine minutes back into YESTERDAY and folded its last hour of spend into today's total. America/New_York, whose transition is at 02:00, was unaffected — which is why a suite whose only non-UTC zone was a time.FixedZone passed. A fixed offset has no transitions and structurally cannot express this. See TestStartOfLocalDay_IsTheFirstInstantOnTheDateInEveryZone.

IT HAS TO AGREE WITH THE LAYER UNDERNEATH. The cost ledger names its day files from a date carried at noon (ledger.dayOf, dayFromName and dayHour) and this function is what SELECTS those files, so a midnight bound and that naming would disagree about where a Havana day starts — silently: no error, no caveat, just a total including an hour that belongs to another date.

THE RULE, stated plainly: sweep the instant axis forward from a point certainly before the date began and take the FIRST instant whose local date is the one wanted. That is the definition of "earliest existing instant" evaluated directly, rather than a wall time handed to time.Date and hoped to exist. It needs no assumption about which direction time.Date normalises, or that local time is monotone across a transition.

AUTUMN-BACK IS THE OTHER HALF, and it is a real choice rather than a corollary. Where the clock goes back THROUGH midnight the wall time 00:00 occurs TWICE — in America/Havana on 2026-11-01 at 00:00 -0400 and again at 00:00 -0500, an hour apart. Both are on the date, so "midnight" alone does not name a bound. THE EARLIER ONE IS CHOSEN: a lower bound of the later instant would exclude the first hour of the day, and any spend in it would be missing from today's total with nothing saying so — the same silent shortfall in the other direction. The sweep picks it for free, because the earlier instant is the first one it reaches. Go's own time.Date happens to resolve an ambiguous wall time to the earlier occurrence here, but its documentation explicitly declines to guarantee that, so the choice is made here instead of inherited.

EXPORTED because sessionapi's tests have to anchor a "today" fixture to the SAME boundary this serves. That helper was a second copy of the midnight expression and carried the identical flaw; a boundary derived twice is a boundary that drifts. The dependency direction is sessionapi to usage, never the reverse.

func StartOfLocalMonth

func StartOfLocalMonth(t time.Time) time.Time

StartOfLocalMonth is the earliest instant that EXISTS in t's local calendar month, in t's own zone. It is the lower bound of "month to date".

IT IS StartOfLocalDay ASKED ABOUT THE FIRST, not a second sweep, and that is deliberate: the earliest instant in a month is the earliest instant on its first date, so there is one definition of "where a local period begins" in this package rather than two that agree until a zone makes them disagree. StartOfLocalDay's own doc records what a duplicated boundary cost the layer above it.

THE FIRST IS ANCHORED AT NOON before being handed over, for the reason dayAnchorHour exists: no DST transition can move midday onto a different date, so the anchor identifies the month's first date without depending on midnight existing on it.

AND IT HAS TO, because a month bound can be wrong in a way a day bound cannot. Paraguay moved its clocks forward AT 00:00 ON 1 OCTOBER in 2017 and 2023, so midnight on that date does not exist and time.Date(y, 10, 1, 0, 0, 0, 0, loc) resolves BACKWARDS to 23:00 on 30 September — an hour before the previous month ended. A month-to-date total on that bound folds September's last hour into October and reports a budget closer to its limit than it is. See TestStartOfLocalMonth_TheNaiveFirstOfMonthExpressionIsStillWrong, which is the negative control, and note that the day-level cases StartOfLocalDay documents are all mid-month: this shape needed its own fixture to be found at all.

A ZONE THAT SKIPS THE FIRST resolves correctly by construction. Pacific/Apia dropped 2011-12-30 entirely when it crossed the date line; were a zone ever to drop a first of the month, the noon anchor normalises onto the next date and the sweep returns the start of THAT date — which is then genuinely the earliest instant in the month.

Types

type Aggregator

type Aggregator struct {
	// contains filtered or unexported fields
}

Aggregator is a fixed ring of per-minute buckets. Safe for concurrent use.

Expiry is implicit: a slot is indexed by minutes-since-epoch modulo NumBuckets, so a write whose timestamp does not match the slot's recorded start has landed on a stale bucket from a previous lap and resets it. No sweeper goroutine, no cleanup path. The tradeoff is that a large backwards clock jump can reset buckets that were still current; for observability counters that is acceptable, and it is preferable to a timer that has to be stopped on shutdown.

func New

func New(opts ...Option) *Aggregator

New returns an empty Aggregator.

func (*Aggregator) AbandonReplay

func (a *Aggregator) AbandonReplay()

AbandonReplay ends a replay without merging anything.

func (*Aggregator) AgentSnapshot

func (a *Aggregator) AgentSnapshot(window, resolution time.Duration, sessionID, agent string, group Group) Snapshot

AgentSnapshot is Snapshot narrowed to one agent's traffic, for /v1/usage?agent=.

A RECOGNISED AGENT IS READ FROM ITS OWN RING, so group is honoured — see Aggregator.agents. Any other label, and any agent within a session, is narrowed from the agent axis instead, read uncapped so an agent past MaxSeriesInResponse is still found, and served as group none.

func (*Aggregator) BeginReplay

func (a *Aggregator) BeginReplay() *Aggregator

BeginReplay starts a replay that runs alongside live traffic, and returns the private aggregator to feed it with Replay — configured as a is, written by nothing else. FinishReplay merges it into a, or AbandonReplay drops it.

A PRIVATE RING, NOT a ITSELF, because live traffic writes a meanwhile. Replay's guard and the time-ordered feed that keeps eviction and request pairing right both assume they are the only writer, and the private ring keeps them so.

Until the replay ends, a logs every erasure and rename it takes — Cleared, Deleted, Rekeyed — for FinishReplay to apply to the private ring first. Without that, a session the user erased while the replay was reading would come back with the merge.

func (*Aggregator) Cleared

func (a *Aggregator) Cleared()

Cleared implements session.Clearer: every figure answerable by session id goes — each session's own ring, and the session breakdown of the all-sessions ring and of every agent's and project's. Everything else stays, including the all-sessions, per-agent and per-project totals, which name no session. They are the figures the cost ledger keeps on disk too, and a clear does not touch that.

pending stays as well. It is keyed by request id and holds plugin names, not content: dropping it would only misattribute the plugins of a request in flight across the clear.

func (*Aggregator) Deleted

func (a *Aggregator) Deleted(sessionID string)

Deleted implements session.Deleter: every figure answerable by sessionID goes — its own ring, and its row in the session breakdown of the all-sessions ring and of every agent's and project's. The totals stay, as in Cleared: they name no session, and the cost ledger keeps the same figures on disk.

func (*Aggregator) FinishReplay

func (a *Aggregator) FinishReplay(r *Aggregator)

FinishReplay merges r, the aggregator BeginReplay returned, into a and ends the replay.

It first does to r what a did while the replay ran, in the order a did it. Then each ring merges slot by slot as mergeRing does for a rename: the same minute sums, the newer minute wins a slot, so a replayed minute that aged out meanwhile cannot overwrite a live one. Session rings beyond the cap go coldest first, which is a replayed one before any session live traffic has touched. Project rings beyond maxProjectRings go the same way. r's unpaired requests are dropped: their process is gone, and no response will come.

func (*Aggregator) ProjectSnapshot

func (a *Aggregator) ProjectSnapshot(window, resolution time.Duration, sessionID, agent, project string, group Group) Snapshot

ProjectSnapshot is Snapshot narrowed to one project's traffic, for /v1/usage?project=. project is a GroupProject series label, as a client got it from group=project.

A PROJECT RING THAT HOLDS THE WHOLE WINDOW IS READ DIRECTLY, so group is honoured. That needs no session and an agent that is "" or recognised: only those have a ring per project. A ring that was evicted and came back holds fewer minutes than its reference ring says it should, and is not read. Then the reply is narrowed from the project axis of the agent's ring (or the session's) and served as group none.

AN UNRECOGNISED AGENT has no ring per project, but the all-agents ring of the project has an agent axis. With no session and that ring complete, the reply is narrowed from it to the agent, as group none. Otherwise there is no agent-by-project data, so it gets AgentSnapshot's reply with no Project echo: the filter was not applied.

func (*Aggregator) Record

func (a *Aggregator) Record(sessionID string, e *model.SessionEvent)

Record folds one event into the aggregate.

Counts and timings come from the response event only: a request event carries no status, no duration and no usage, so counting it as traffic would double every request and pull the latency mean toward zero. Denials (phase "denied") are counted as errors — they are requests that happened and failed, and omitting them would make an authentication outage look like a traffic drop.

A request event is not ignored, though. The listener splits plugin invocations by phase — the request event carries InvocationPhaseRequest, the response event InvocationPhaseResponse — so a plugin that only acts on the request appears in neither the response event nor, previously, the by-plugin breakdown. context-guru and tool-prune are exactly that shape (WritesRequestBody with a stub OnResponse), so `by plugin` silently meant "plugins that ran on the response".

Request-phase plugin names are therefore held by RequestID — the field that exists for this pairing — and merged when the paired response arrives, so each gets the response's own tokens and latency and one turn counts once. Pairing on the id rather than positionally matters because a client can have several requests in flight at a time.

func (*Aggregator) Rekeyed

func (a *Aggregator) Rekeyed(oldID, newID string)

Rekeyed moves oldID's figures to newID: the per-session ring, and oldID's row in every bucket's session breakdown. It implements session.Rekeyer.

Without it the store would list the session under its new id while /v1/usage kept answering for the old one — the "listed but zeroed" shape sessionRing exists to prevent.

func (*Aggregator) Replay

func (a *Aggregator) Replay(sessionID string, e *model.SessionEvent) bool

Replay records an event from before this process started — the session archive's, at startup — and reports whether it was in range. It is Record with one guard: an event whose minute is in the future, or not among the newest NumBuckets-1 minutes, is dropped.

THE GUARD IS WHAT MAKES OLD EVENTS SAFE TO FEED. A slot is a minute modulo NumBuckets, and a write to a slot holding a different minute resets it (see Aggregator): an event exactly NumBuckets minutes old shares its slot with the current minute and would erase it. Record never meets one, because live events are current; a replay is made of nothing else.

ONE MINUTE OF MARGIN, so a minute boundary passing between this check and Record's lock cannot carry an event over the edge. A check outside the lock is enough because nothing else writes the ring a replay feeds: it is the private one BeginReplay returns.

Feed events in ascending At order. Record pairs a request with the response after it, and reclaims the least recently written session ring at the cap, so that order is what makes the replayed ring the one the old process had.

func (*Aggregator) Snapshot

func (a *Aggregator) Snapshot(window, resolution time.Duration, sessionID string, group Group) Snapshot

Snapshot returns the last window of buckets, oldest first.

The newest bucket is the one containing now, still filling — a client rendering it should expect its final value to rise. Reporting it partially is better than withholding it: an operator watching a live chart wants the current minute visible.

An unknown session yields a snapshot of all-zero buckets rather than an error: a session that has produced no priceable traffic yet is a normal state, and the caller already knows whether the session exists from /v1/sessions.

type Bucket

type Bucket struct {
	At          time.Time `json:"at"`
	Counts                // totals across every label
	LatMeanMs   float64   `json:"latMeanMs,omitempty"`
	LatStdDevMs float64   `json:"latStdDevMs,omitempty"`
	// LatSamples is how many requests in this bucket carried a duration, which
	// is not always Requests: an unmeasured response counts as traffic but not
	// as a latency sample. Folding needs it to weight each bucket by its real
	// sample count, and a client showing a window-wide mean needs it for the
	// same reason.
	LatSamples int64 `json:"latSamples,omitempty"`
	// Series is the requested grouping, keyed by model / status / plugin name.
	// Nil when group=none.
	Series map[string]Counts `json:"series,omitempty"`
}

Bucket is one BucketWidth slice of time, as served to clients.

A bucket with no traffic is still emitted, with zeroed counts. That is deliberate: a client rendering a bar chart must be able to distinguish an idle minute from a minute that fell off the end of the ring, and inferring absent buckets from timestamps is exactly the kind of thing every client would get slightly differently.

type BucketScope

type BucketScope int

BucketScope says whether ScopeToAgent narrows the per-bucket series as well as the window-level figures.

AN EXPLICIT PARAMETER RATHER THAN A DEFAULT, because the two callers want different things and the cheaper one is not the safe one. agentop's usage pane renders a CHART from Buckets, so leaving them whole-window would draw every agent's traffic under a title naming one — silent, and wrong in the direction a reader cannot detect. `agentop cost` reads only window totals on its scoped path, so it asks for no narrowing and pays for none.

NEITHER VALUE IS A SAFE DEFAULT, which is why there is no zero-argument form. Defaulting to KeepBuckets hands a chart the whole window; defaulting to NarrowBuckets silently drops the latency a caller may be about to render, and drops Series from a response a caller may be about to break down. The caller knows which it reads; this package does not.

const (
	// KeepBuckets narrows only the window-level figures. Buckets and their Series come
	// through untouched.
	KeepBuckets BucketScope = iota
	// NarrowBuckets additionally rewrites every bucket's counts to the scoped agent's share
	// of it and drops Series. See ScopeToAgent for what this cannot carry across.
	NarrowBuckets
)

type Counts

type Counts struct {
	Requests int64 `json:"requests"`
	Errors   int64 `json:"errors,omitempty"`
	Tokens   int64 `json:"tokens,omitempty"`
	// The four billed token kinds, plus reasoning. Names match
	// model.InferenceExtension exactly: one vocabulary from parser to aggregate
	// to ledger to collector, because aggregate-side synonyms are how two halves
	// of a system come to disagree about what a field means.
	//
	// Tokens above stays as the legacy aggregate for clients written against it.
	// These are additive to the wire, not a replacement.
	//
	// Tokens is NOT always the sum of the fields below. parsercommon.Fill prefers
	// the provider's own total_tokens when one was reported and falls back to
	// summing the split otherwise, so a gateway reporting only a total — prompt and
	// completion absent — yields a non-zero Tokens with every split field at 0. A
	// client normalising a stacked bar against Tokens would be wrong in that case;
	// PresentKinds below is what keeps it legible, since no bits set means nothing
	// reported a breakdown at all, which is a different answer from a breakdown that
	// was genuinely zero.
	//
	// They matter because the kinds price very differently — a cache read is
	// roughly 0.1x uncached input and a cache write roughly 1.25x — so for a
	// long-running agent, whose traffic is overwhelmingly cache reads, the split
	// IS the shape of the bill. One scalar cannot express that.
	InputTokens      int64 `json:"inputTokens,omitempty"`
	CacheReadTokens  int64 `json:"cacheReadTokens,omitempty"`
	CacheWriteTokens int64 `json:"cacheWriteTokens,omitempty"`
	OutputTokens     int64 `json:"outputTokens,omitempty"`
	// ReasoningTokens is a SUBSET of OutputTokens, not a sibling of it: the
	// provider reports how much of what it generated was reasoning. Adding the two
	// double-counts every reasoning token at the output rate, which is the most
	// expensive tier there is.
	//
	// THE SUBSET RELATION IS NOT ENFORCED HERE, which is a decision rather than an
	// omission. plausibleTokenReport screens for negatives and an implausible ceiling
	// but not for ReasoningTokens > OutputTokens, so a provider reporting a
	// contradictory pair is stored as it reported it — and `agentop cost`'s token line
	// and the detail pane both print it, which is the only way a reader notices the
	// provider bug. Clamping at ingest would make every surface agree on a number
	// nobody measured.
	//
	// ApportionReasoning DOES clamp what it derives, because a bar drawn longer than
	// its parent's is a containment claim the layout makes rather than one it relays.
	// Numbers stay faithful; geometry is not allowed to lie.
	ReasoningTokens int64 `json:"reasoningTokens,omitempty"`
	// RefusedTokenRequests counts the requests whose token report was REJECTED as
	// implausible and contributed nothing to any figure above. See plausibleTokenReport for
	// the rule and for why the whole report goes rather than the offending field.
	//
	// It exists because capping cost while leaving tokens unbounded is not a position that
	// survives being stated. Cost is bounded per request twice over
	// (pricing.MaxPlausibleRequestCostMicros for a gateway's own figure, pricing.MaxCostMicros
	// for the unit) while the token fields are read straight from a provider-controlled `int`
	// on the wire — so unbounded, the same forged response that cannot move the dollar total
	// by more than $10,000 moves the token total by 9.2e18, or moves it DOWN with a negative,
	// and both feed the same aggregate a client renders side by side.
	//
	// REFUSED, NOT CLAMPED, matching how an out-of-range cost is handled: a clamp invents a
	// number nobody reported, and 10,000,000 tokens presented as fact is a worse answer than
	// no figure plus a count of what was dropped. The request itself still counts in
	// Requests, and its cost — settled by a different producer, bounded separately — is
	// untouched, because this says nothing about whether the response was billed.
	//
	// A COUNTER, on the same reasoning as PricedRequests: buckets are summed when a client
	// asks for a coarser resolution, and a count survives that where a flag degrades to
	// "somewhere in here". Non-zero here means Tokens and the split are SHORT by whatever
	// those requests really used, which is unknowable by construction.
	RefusedTokenRequests int64 `json:"refusedTokenRequests,omitempty"`
	// PresentKinds is the OR of every folded event's InferenceExtension.PresentKinds:
	// a set bit means at least one response in this bucket actually REPORTED that
	// kind. Bit layout matches parsercommon.Kind (Input=1, CacheRead=2,
	// CacheWrite=4, Output=8, Reasoning=16).
	//
	// Summing would be meaningless, hence the union. It exists because a zero in
	// one of the fields above has two readings — "this traffic wrote no cache" and
	// "nothing here reports cache writes" — and a by-model table showing a blank
	// column cannot be interpreted without knowing which. The per-event flag
	// already carries that distinction; dropping it at the aggregate would throw
	// away the only thing that makes an empty cell readable.
	PresentKinds uint8 `json:"presentKinds,omitempty"`
	// Saturated says that at least one addition into this Counts hit the int64 ceiling and
	// was CLAMPED rather than allowed to wrap. Every number here is then a FLOOR: the real
	// figure is larger, and by an amount nothing in this struct can state.
	//
	// It exists because the alternative was a wrapped total, and a wrapped total is a lie
	// that reads as a fact. No per-request bound can prevent the wrap — for any bound C the
	// sum overflows after ceil(math.MaxInt64/C) requests and nothing bounds the request
	// count (see pricing.MaxCostMicros, which spells out the arithmetic) — so the only place
	// to close it is where the sum is kept, which is Add below. A clamp on its own would
	// merely trade a large negative lie for a large positive one; this field is what makes
	// the clamp honest, and it is the whole reason the clamp is acceptable.
	//
	// A BOOL, NOT A COUNTER, unlike every other disclosure in this struct. A count of
	// saturating additions would depend on how many folds happened, which depends on the
	// bucket resolution the client asked for — the one property this package insists a total
	// must not have (see Totals and UngroupedCostMicros, both summed from the raw buckets for
	// exactly that reason). "This number is a ceiling" survives any regrouping; "it was
	// clamped four times" does not.
	//
	// OR-ED THROUGH Add, like PresentKinds: folding a saturated bucket into a clean one
	// yields a saturated total, because the total inherits the floor.
	//
	// NOT LOGGED, deliberately: this package has no logger, and the disclosure travels on the
	// same response as the number it qualifies.
	Saturated bool `json:"saturated,omitempty"`
	// CostMicros is millionths of a US dollar. An integer unit keeps bucket
	// addition exact and JSON round-tripping lossless, which float dollars do
	// not; a client divides by 1e6 to display. Zero when nothing here could be
	// priced, which is not the same as "this traffic was free" — the API omits
	// the field entirely in that case rather than asserting $0.
	CostMicros int64 `json:"costMicros,omitempty"`
	// The modelled cost of each token tier, summed over the requests in this bucket.
	//
	// ADJACENT TO CostMicros, not filed with the token counters they parallel, because the
	// distinction that matters here is not "tokens versus money" but AUTHORITATIVE VERSUS
	// MODELLED. CostMicros may be a gateway's own post-discount figure; these four are
	// always the rate table's, so they need NOT sum to it and a reader who assumes they do
	// is wrong. Put beside the field they qualify, that is visible in one glance instead of
	// inferred from a field name.
	//
	// USED AS A RATIO, never as a total — see ApportionTiers, which is the only thing that
	// should read them. All four zero means no modelled split reached this bucket, which is
	// NOT a claim that the traffic was free.
	//
	// Reasoning is deliberately absent: it is a subset of output, not a fifth tier, so a
	// field here would double-count. It stays in the token counters below.
	InputCostMicros      int64 `json:"inputCostMicros,omitempty"`
	CacheWriteCostMicros int64 `json:"cacheWriteCostMicros,omitempty"`
	CacheReadCostMicros  int64 `json:"cacheReadCostMicros,omitempty"`
	OutputCostMicros     int64 `json:"outputCostMicros,omitempty"`
	// AvoidedMicros is cost that was NOT INCURRED — what the context operators (tool-prune,
	// context-guru, the keeper) saved, as the accountant priced it, tier by tier — in the same
	// unit as CostMicros. ONLY BASIS "usd": a subscriptionEquivalent saving is in AvoidedUnits
	// and an unknown one in AvoidedUnknownMicros (design §5.7a). See event.Event.Figures.
	//
	// A COUNTERFACTUAL SITTING BESIDE A MEASUREMENT, and the adjacency is deliberate: the
	// invariant on event.Event.Avoided forbids adding any of this to spend, to a budget
	// or to a usage total, and a reader who finds CostMicros finds that rule in the same
	// glance. Placing it further down the struct would hide the one thing a new consumer
	// must know. TestAggregator_TotalsAreInvariantToAvoidedCost holds the line.
	//
	// APPLIED savings only. event.Event.TotalAvoidedUSD skips the projected ones and
	// this counter inherits that: observe-mode figures are money that WAS spent, and a
	// total mixing them would claim a saving for every byte still on the wire.
	//
	// INDEPENDENT OF PRICEDNESS, which is why it does not travel with the cost figure. A
	// request whose response could not be priced still had tokens removed from its prompt,
	// and event.Record's own doc names that as the interesting case; deriving this from
	// the priced record would silently drop it.
	//
	// ESTIMATED, sometimes. Saving.Estimated marks a figure from an estimated op or rate, and
	// the per-request flag does not survive summation — so a client must present this as
	// approximate unconditionally rather than inferring exactness from its absence here.
	//
	// GROSS, NOT NET, which is the caveat most likely to be dropped on the way to a screen. What
	// the same operators CAUSED — a rewrite inside the cached prefix, a cache break — is
	// PenaltyMicros, beside it and never subtracted from it here. Net is AvoidedMicros minus
	// PenaltyMicros, and may be negative.
	//
	// SUMMABLE BECAUSE IT IS DOLLARS. The same doc refuses to publish one "tokens saved"
	// figure, because prompt tiers differ by up to 12.5x and a single token count invites
	// multiplying by one rate. That objection does not apply here and its absence is the
	// reason this field is money rather than tokens: each saving was priced at the tier it
	// actually came out of BEFORE reaching this counter, so the sum is tier-correct by
	// construction. A tokens-avoided aggregate would not be, and is deliberately not offered.
	AvoidedMicros int64 `json:"avoidedMicros,omitempty"`
	// PenaltyMicros is what the operators behind AvoidedMicros caused on the same requests,
	// priced: event.Event.TotalPenaltyMicros, basis "usd" only. Never netted into AvoidedMicros
	// and never floored: a net below zero is the two figures, read together.
	PenaltyMicros int64 `json:"penaltyMicros,omitempty"`
	// AvoidedUnits and PenaltyUnits are AvoidedMicros and PenaltyMicros for requests on a
	// subscription login (basis "subscriptionEquivalent"), in usage-limit units — tokens times
	// accounting.subscription_weights — as integer MILLI-units. Not money, and estimated.
	AvoidedUnits int64 `json:"avoidedUnits,omitempty"`
	PenaltyUnits int64 `json:"penaltyUnits,omitempty"`
	// AvoidedAPIEquivalentMicros is what the savings in AvoidedUnits would have been worth at API
	// rates, net of their penalty like the units: the "API equivalent" a reader shows beside them. NOT MONEY — the request
	// was on a subscription — so it is in no dollar total.
	AvoidedAPIEquivalentMicros int64 `json:"avoidedApiEquivalentMicros,omitempty"`
	// AvoidedUnknownMicros is the net saved dollars (saved minus penalty, may be negative) of
	// savings whose billing mode was unknown (basis "unknown"). Shown beside the money totals, never added to them.
	AvoidedUnknownMicros int64 `json:"avoidedUnknownMicros,omitempty"`
	// PluginSpendMicros is what the context operators' own model calls cost (event.Event.Spends,
	// basis "usd"): a context-guru summary call, for instance. Those calls do not pass through
	// the proxy, so this is the only figure that holds them. KEPT OUT OF CostMicros so the
	// existing spend totals keep their meaning; spend in all is CostMicros + PluginSpendMicros +
	// KeepAliveMicros. PluginSpendUnits is the subscriptionEquivalent calls in milli-units, and
	// PluginSpendUnknownMicros the calls whose billing mode was unknown (never added).
	PluginSpendMicros        int64 `json:"pluginSpendMicros,omitempty"`
	PluginSpendUnits         int64 `json:"pluginSpendUnits,omitempty"`
	PluginSpendUnknownMicros int64 `json:"pluginSpendUnknownMicros,omitempty"`
	// KeepAliveMicros is what the keep-alive pings on an API key cost (a record with
	// event.PurposeKeepAlive and basis "usd"), and KeepAlivePings how many pings there were, of
	// every billing mode. Split like PluginSpend*: KeepAliveUnits is the subscriptionEquivalent
	// pings' tokens in usage-limit milli-units (the configured subscription weights, output
	// included), KeepAliveAPIEquivalentMicros those pings' dollars at API rates (NOT MONEY, shown
	// beside the units), and KeepAliveUnknownMicros the pings whose billing mode was unknown
	// (never added). Only KeepAliveMicros is money, which is where the metrics sink moves its
	// USD counters too. A ping is not the agent's request: it is in neither Requests, Tokens,
	// CostMicros, the coverage counters nor the latency mean, only here. Its rescue — the cache
	// read it kept warm — is credited to the "keeper" operator on the next request.
	KeepAliveMicros              int64 `json:"keepAliveMicros,omitempty"`
	KeepAliveUnits               int64 `json:"keepAliveUnits,omitempty"`
	KeepAliveAPIEquivalentMicros int64 `json:"keepAliveApiEquivalentMicros,omitempty"`
	KeepAliveUnknownMicros       int64 `json:"keepAliveUnknownMicros,omitempty"`
	KeepAlivePings               int64 `json:"keepAlivePings,omitempty"`
	// CostAPIEquivalentMicros is what the requests on a subscription login cost at API rates, and
	// CostUnknownMicros what the requests of unknown billing cost. Neither is money, nor in
	// CostMicros or the tier mix, as the metrics sink counts no dollars for them. A record with no
	// basis is money, so rows written before the split read as before.
	CostAPIEquivalentMicros int64 `json:"costApiEquivalentMicros,omitempty"`
	CostUnknownMicros       int64 `json:"costUnknownMicros,omitempty"`
	// InteractionMicros is the value of the tokens no context operator owns on a rescued request
	// (event.Event.InteractionUSD, design §6.2), basis "usd" only. Money in the same unit as
	// AvoidedMicros, but never in it: no operator saved it. SIGNED, so a window can hold a net
	// cost. A net saving adds it (agentop money.NetMicros), as the accountant metrics add
	// llm.savings.interaction.usd (rossoctl/cortex#2139).
	InteractionMicros int64 `json:"interactionMicros,omitempty"`
	// PricedRequests counts the requests that actually produced a cost. Coverage
	// is a counter rather than a flag because buckets are summed when a client
	// asks for a coarser resolution, and because a deployment can price some of
	// its traffic and not the rest: several endpoints, rates known for some.
	//
	// PriceableRequests-minus-PricedRequests is the gap, correct at every
	// resolution, and it is what stops a partial total being presented as a
	// complete one.
	//
	// NOT Requests-minus-PricedRequests. Requests counts every proxied response — MCP
	// tool calls, health checks — none of which can ever carry a price, so
	// that difference never reaches zero and a client obeying it marks every total
	// partial forever. Requests is not the denominator for coverage;
	// PriceableRequests is.
	//
	// It counts an INEXACT figure too — see IncompleteRequests. This counter answers
	// "did anything price this", which a request priced from partial counters
	// truthfully did; withholding it here would answer a question this counter is not
	// asking and would state the same caveat twice in two vocabularies.
	PricedRequests int64 `json:"pricedRequests,omitempty"`
	// IncompleteRequests counts the priced requests whose figure is not EXACT: known-low
	// because a stream died before its output count arrived, or approximate because the
	// gateway reported only a total. event.Event.IncompleteReason carries which, per
	// request; this counter is the aggregate's answer to "is this dollar total exact".
	//
	// HOW MANY, not in which way. The two readings are different claims about money — a
	// floor means the real figure is higher, an approximation means it is off in no known
	// direction — and this counter cannot tell them apart because it is one number.
	// Snapshot.IncompleteBy carries the split, keyed on the reason, and its counts sum to
	// this one.
	//
	// A SUBSET of PricedRequests, never a sibling of it. Their dollars are in CostMicros and
	// the requests are in PricedRequests, because both of those are true; the disclosure
	// rides alongside instead of subtracting from either — honest by saying more, not by
	// counting less. Subtracting would be an adjustment, and an adjustment invites a client
	// to render the remainder as an exact total, which is the error this counter exists to
	// prevent.
	//
	// A counter rather than a flag, for the reason PricedRequests is one: buckets are summed
	// when a client asks for a coarser resolution, and a count survives that where a flag
	// degrades to "somewhere in here".
	//
	// NOT a pricing gap, and deliberately absent from byUnpriced: nothing an operator
	// adds to a rate table would make one of these disappear, so naming it there would
	// point at an entry that already exists.
	IncompleteRequests int64 `json:"incompleteRequests,omitempty"`
	// PriceableRequests counts the requests that COULD be priced; see PriceableRequest.
	//
	// It exists because Requests is the wrong denominator for coverage. Requests
	// counts every proxied response, including MCP tool calls and health checks, while
	// PricedRequests can only ever cover inference. Dividing one by the other made a
	// CORRECTLY configured deployment read "1/10 priced" forever with an empty gap
	// list — a permanent warning with nothing to act on, which trains an operator to
	// ignore the one signal that matters.
	//
	// Priced-versus-priceable is the ratio that answers "is my cost total complete",
	// and it reaches parity when it should.
	//
	// WHAT COUNTS AS PRICEABLE WIDENED, and a client comparing figures across versions should
	// know. Requiring extractable token counts made a 2xx inference response whose usage the
	// parser could not read invisible: not priced, not priceable, and absent from UnpricedBy —
	// nine good requests plus one of those read "9/9 priced", parity, while real spend was
	// missing. It is now counted as priceable-but-unpriced and named as a gap, which is a
	// HIGHER priceable figure for identical traffic: a dashboard tracking the ratio across an
	// upgrade sees coverage appear to drop, and nothing got worse.
	//
	// There is deliberately NO version marker on the wire for it. A field whose meaning is
	// versioned needs every consumer to branch on the version, and the honest reading is the
	// same in both: this is the count of requests that could have carried a price.
	PriceableRequests int64 `json:"priceableRequests,omitempty"`
}

Counts is the per-label tuple accumulated in each bucket.

func (*Counts) Add

func (c *Counts) Add(o Counts)

Add accumulates o into c, field by field — except PresentKinds, which is OR-ed. It is a set of which token kinds a response reported, so adding two buckets' flags would produce a number that is not a bit set at all. Do not pattern-match on the `+=` below when adding a field of that shape.

Exported because consumers fold these too — agentop collapses low-volume series into an "(other)" band — and an unexported version left them hand-summing the fields in another module. That copy silently missed PricedRequests when it was added, under a comment explaining that every field had to be carried. One summation, in the same file as the struct, is the only way that stays true.

Pointer receiver and mutating, matching how the aggregator accumulates on the hot path. For a map value, read-modify-write: `v := m[k]; v.Add(o); m[k] = v`.

EVERY FIELD IS A CHECKED ACCUMULATE. A bare `+=` wraps, and a wrapped total is the worst failure this package has: 1,024 requests at pricing.MaxCostMicros sum to -9214364837600034816, which then sits in the durable ledger for its full retention with no repair path. pricing.MaxCostMicros' own doc proves no per-request bound can close that and names this function as the place that must. Add is the single summation point, so the guard lands once and cannot be forgotten at a call site.

WHICH FIELDS ARE ACTUALLY AT RISK, in order:

  • The TOKEN fields. They are read from a provider-reported `int` on the wire, and foldInto refuses an implausible one — but the refusal is a ceiling per request, not on the sum, and Add is exported so a consumer can hand it anything.
  • CostMicros. Bounded per request at pricing.MaxPlausibleRequestCostMicros for the modelled path and pricing.MaxCostMicros for a gateway's own cost header, which puts the wrap at ~9.2e8 and 1,024 requests respectively. The second is reachable.
  • Requests, Errors and the three coverage counters are one per event at the source, so traffic cannot reach 2^63 of them. They are checked anyway: Add is exported, agentop folds arbitrary Counts through it to build its "(other)" band, and a uniform call site is the only kind that cannot be forgotten when a field is added.

func (*Counts) AddFigures

func (c *Counts) AddFigures(f event.Figures)

AddFigures accumulates one record's savings and plugin spends (event.Event.Figures) into c, each into its field of the same name. The ledger and the ring both call it, so the two put the same figure in the same field.

func (Counts) ApportionReasoning

func (c Counts) ApportionReasoning(outputMicros int64) (micros int64, ok bool)

ApportionReasoning is the reasoning share of an already-apportioned output figure, in micros.

HERE RATHER THAN IN A RENDERER, for the reason ApportionTiers gives for itself: one place, so the surfaces cannot disagree about a figure derived more than once. Kept in this package is also what lets `agentop cost --json` publish it, instead of leaving a consumer to reimplement the rule — which is what costJSON.Tiers refuses for the tier split.

outputMicros is the DISPLAYED output figure, not c.OutputCostMicros: the displayed one is already scaled to the gateway's authoritative total, so deriving from the raw mix would produce a child that does not divide into the parent beside it.

A TOKEN RATIO APPLIED TO A COST FIGURE, which is a second approximation on top of ApportionTiers' own. Reasoning's share of output COST equals its share of output TOKENS only where every model in the window bills output at one rate. Across a mixed window it can be off by the spread between those rates — an expensive model that did no reasoning beside a cheap one that was nearly all reasoning is the worst case, and the error there is an order of magnitude, not a rounding.

Accepted because there is no better source: nothing reports a ReasoningCostMicros, and the alternative is showing no figure at all for the component this feature exists to expose. Callers must present it as modelled — `agentop cost` and the drawer already mark the tier split that way, and the README says so for the child specifically.

ok is false when there is no defensible figure, and the caller renders "not known here" — never $0.00, which would assert the reasoning was free: a count that is zero or negative, a missing denominator, or a share that truncates below one micro.

THE PRESENT BIT IS NOT CONSULTED HERE, because neither "nothing reported" nor "reported zero" has a figure to apportion. The bit separates them, and a caller that needs to — the spend drawer does, to choose between the not-known cell and an exact "$0.00" — reads PresentKinds itself. A positive count with the bit CLEAR does apportion: that is a producer predating PresentKinds, where the value is the only evidence there is.

The result is clamped to outputMicros: a provider reporting reasoning above output must not yield a child figure above its parent, though the counts themselves are left as reported — see Counts.ReasoningTokens.

func (Counts) ApportionTiers

func (c Counts) ApportionTiers() (tiers [pricing.NumTiers]int64, ok bool)

ApportionTiers splits CostMicros across the rate tiers by the modelled mix.

THE MIX IS THE RATE TABLE'S, THE MAGNITUDE IS THE GATEWAY'S. A request priced from a response header has an authoritative total and no breakdown, because no gateway publishes one — so the modelled figures cannot be shown as dollars beside it without putting two disagreeing totals on screen. Used as a ratio they answer the question anyway, and the column adds up to the headline a reader checks first.

ok is false when there is no mix (nothing to apportion by) or no usable total (nothing to apportion). Callers render the "not known here" cell — NOT four zeros, which would report the traffic as free, and not a guess.

NO COVERAGE THRESHOLD, deliberately. A mix drawn from one request of forty is a weak key, but every particular floor is a number nobody can defend — 50% and 10% are equally arbitrary — and a constant whose value is unjustifiable is worse than the behaviour it guards. The display marks every figure inexact instead, and a reader who wants coverage has `agentop cost`, which reports priced against priceable already.

THE ONE PLACE THIS ARITHMETIC LIVES. The drawer, the text command and the JSON all call it, so three surfaces cannot disagree about a figure derived three times.

type Degraded

type Degraded struct {
	// SkippedLines is how many LINES could not be decoded and were passed over. Each is
	// spend that happened and is not in the total.
	//
	// A FLOOR ON ROWS LOST, NOT AN EXACT COUNT OF THEM. It counts lines because that is
	// what the reader can see. One undecodable line is usually one row — but the ledger's
	// newline fence only runs while the writing process is alive, so a crash mid-append
	// leaves an unterminated fragment and the next append is concatenated onto it: ONE
	// line holding TWO lost rows, measured that way.
	//
	// So a non-zero value means "AT LEAST this many rows are missing", which is the reading
	// a client has to present. Same number and same qualification as
	// ledger.Caveats.SkippedLines, which is where this field is copied from; see
	// cost/ledger's appendBytes for why the bytes on disk cannot support an exact figure.
	SkippedLines int64 `json:"skippedLines,omitempty"`
	// TruncatedDays is how many day files were abandoned part-way. Worse than a skipped
	// line by an unbounded amount: the rest of that file is missing, and a file holds a
	// whole day.
	TruncatedDays int64 `json:"truncatedDays,omitempty"`
	// DroppedRowsTotal is rows the WRITER lost: a failed append, or an enqueue dropped because the
	// queue was full while the filesystem stalled. Cumulative for the life of the process, which the
	// name says because it cannot be anything else — a drop is a fact about the writer, it happened
	// once, and no later read can rediscover it, so attributing it to whichever read happened to
	// notice would be a fiction.
	//
	// THE WRITE SIDE OF THIS OBJECT, which had only the read side. A day that lost a minute to ENOSPC
	// served a short total under priced:true with no caveat at all — exactly the silence this struct
	// was added to end, on the half nobody wired up. Compare across polls for a rate; a non-zero
	// value at all means some total below is short.
	DroppedRowsTotal int64 `json:"droppedRowsTotal,omitempty"`
	// UnreadableDays is how many day files could not be opened or scanned at all — a
	// permission change, a vanished mount, an IO error on the first read.
	//
	// THE WORST OF THE THREE, and the one this struct was missing. A producer reports a
	// caveat when any of them is non-zero, so a read whose only fault was an unopenable
	// day serialised as `"degraded":{}` — every field omitempty, nothing quantified — which
	// says "something was wrong" and withholds what. A whole day of spend is missing on
	// this path, which is more than a truncated file loses.
	UnreadableDays int64 `json:"unreadableDays,omitempty"`
}

Degraded is what a ledger read could not deliver.

It exists because the alternative was silence. The ledger already skipped a corrupt line rather than discarding the rest of the day, and already abandoned a file it could not scan — both strictly better than the behaviour they replaced. But the response looked IDENTICAL to a clean one: a short dollar total labelled priced:true with no caveat anywhere in it, which is the exact failure this branch keeps refusing in every other place it appears.

The counters are GAUGES for the most recent read, not cumulative totals. One corrupt line re-read on every /v1/usage poll would make a running count climb forever over a single piece of damage, and a client watching it would infer an outage that is not happening.

type Group

type Group string

Group selects which label breakdown a Snapshot carries.

const (
	GroupNone Group = "none"
	// GroupModel breaks totals down by the model named on the request.
	//
	// This is the series that shipped as GroupMethod. The aggregator only ever
	// populated it from Inference.Model (see foldInto) — A2A and MCP method names
	// never entered it — so "method" was a misnomer from the start. agentop's
	// events-table METHOD cell DOES show A2A/MCP methods, which is what made the
	// name look right; that is a different code path.
	GroupModel Group = "model"
	// GroupMethod is the name GroupModel shipped under. Accepted forever, resolves
	// to the same series.
	//
	// Kept because it is on the wire and tui/usage_pane.go's cycleGroup passes it:
	// dropping it would break a live client to fix a spelling. NOT a second map —
	// series() maps both to byMethod.
	GroupMethod Group = "method"
	// GroupEndpoint breaks totals down by target host.
	//
	// Half of the rate key. The same model bills differently on a discounted
	// gateway than on the vendor endpoint, and only the host distinguishes them, so
	// a cost table without this axis cannot explain why two identical-looking
	// requests cost different amounts.
	GroupEndpoint Group = "endpoint"
	// GroupSession breaks totals down by session.
	//
	// Requested on the ALL-sessions ring (session=""), which is the point: one
	// response then answers for every session a client is listing. Asked for
	// alongside session=<id> it is legal but degenerate — a single-entry series
	// duplicating Totals.
	//
	// What one key means depends on how the listener assigns session ids. While
	// several concurrent agents share one id (#949), their spend lands in one entry
	// and this axis reports per-id rather than per-agent cost. That is a property of
	// the current session bucketing, not of this grouping.
	GroupSession Group = "session"
	// GroupAgent breaks totals down by the coding agent that made the request, by
	// name with its version dropped (pipeline.AgentName) — the axis #952 asks for, since "what did today cost" is only
	// actionable once it says which agent spent it. It is also what GroupSession
	// cannot answer while several concurrent agents share one session id (#949).
	//
	// The key is parsed from the request's User-Agent, so it is CLIENT-ASSERTED AND
	// TRIVIALLY SPOOFABLE: a display and cost-attribution axis, never an authorization
	// input. A caller that lies here mis-attributes its own spend and nothing else.
	//
	// Its accumulator has NO INFERENCE GUARD, so this series counts MCP and tool
	// traffic too and its request denominator differs from GroupModel's — the same
	// property GroupEndpoint has. See the byAgent field for the full reasoning.
	//
	// An event that carried no User-Agent lands under the reserved key "unknown",
	// which is NOT an agent name; an agent that was reported but is not recognised
	// lands under its raw User-Agent, so a new coding agent is visible the day someone
	// runs it rather than after a parser update ships.
	GroupAgent Group = "agent"
	// GroupProject breaks totals down by project: the git repo root of the agent process's
	// working directory, from SessionEvent.Project. An event with no project lands under
	// UnknownProjectLabel. Folded for every event, like GroupAgent, so the series sum to the total.
	GroupProject Group = "project"
	// GroupCurrency breaks totals down by the BILLING UNIT the figures are denominated in.
	//
	// It exists so a deployment whose gateways bill in different units has somewhere to get a
	// figure per unit, once a combined total has been refused as meaningless. Unlike every other
	// axis here it is not a property of the traffic but of the RATE that priced it: the ledger
	// serves it from Row.Currency, part of its row key, and the in-memory ring from a per-bucket
	// tally of the same rule (pricing.UnitOf), so both kinds of window break down alike.
	GroupCurrency Group = "currency"
	GroupStatus   Group = "status"
	GroupPlugin   Group = "plugin"
	GroupHost     Group = "host"
)

func ParseGroup

func ParseGroup(s string) (Group, error)

ParseGroup validates a group parameter. Empty means GroupNone.

func (Group) Reconcilable

func (g Group) Reconcilable() bool

Reconcilable reports whether a client can reconcile this group's series against Totals — whether sum(series CostMicros) + Snapshot.UngroupedCostMicros equals Totals.CostMicros.

FALSE FOR GroupNone, which asks for no breakdown: there is nothing to reconcile, and a residual equal to the entire total would then appear on every group-less request — the default one — and read as a fault.

FALSE FOR GroupPlugin, whose series counts one request once per plugin that touched it, so its dollars intentionally sum to MORE than the total (see the note on GroupPlugin's accumulator). Totals-minus-series is not a residual for that axis at all, and it is not merely useless: in a window where some requests touched no plugin and others touched several, the shortfall and the duplication cancel and produce a plausible zero. So it is not computed there rather than computed and clamped.

Exported because both producers — Aggregator.Snapshot and the ledger's fold — have to make the same call, and a predicate written twice is a predicate that drifts.

NOT SUFFICIENT ON ITS OWN — treated as such, it publishes a residual equal to an entire total. This says whether a group's series WOULD reconcile against Totals; it cannot say whether the source being read can produce that series at all. The second question belongs to the source: the ring keeps a status series, a plugin series and per-session rings, while a cost-ledger row is (endpoint, model, agent, provenance) per minute and has no column for status or session. ledger.Groupable answers it there, and ledger.Fold requires BOTH — "the breakdown falls short by this much" and "there is no breakdown to fall short" are different answers, and only the first is a residual.

So: reconcilability is a property of the SOURCE AND the group. This half is the group's, and a true here is a necessary condition rather than a licence.

type Option

type Option func(*Aggregator)

Option configures an Aggregator.

func WithClock

func WithClock(now func() time.Time) Option

WithClock overrides time.Now, for deterministic tests.

func WithMaxSessions

func WithMaxSessions(n int) Option

WithMaxSessions bounds the number of per-session rings retained. Each ring is NumBuckets buckets, so this is the knob that bounds worst-case memory.

n == 0 means track NO per-session rings: /v1/usage?session=... returns zeroed buckets, while the all-sessions aggregate keeps counting everything. That is the reading the name implies, and the safe one if this is ever wired to operator config — a 0 in a ConfigMap should not silently mean "unlimited". Pass a negative n to leave the default in place.

func WithPricing

func WithPricing(r pricing.Resolver) Option

WithPricing supplies the rate table used for requests that carry no cost event.

The resolver is long-lived and its table swaps in place, which matters here: the aggregator is created once at startup while the pipeline is rebuilt on every config reload, so holding the Registry keeps it on current rates without being rebuilt itself. See pricing.Registry.

type ResolutionWindowReason

type ResolutionWindowReason int

ResolutionWindowReason names WHY a resolution was rejected against a window, for a caller that has to explain it in terms of a span the requester never named.

const (
	// ResolutionWindowNone: the rejection was about the resolution alone — unparseable, finer than
	// the storage bucket, or not a multiple of it — and its own wording is already correct.
	ResolutionWindowNone ResolutionWindowReason = iota
	// ResolutionTooCoarseForWindow: the resolution is wider than the span being served.
	ResolutionTooCoarseForWindow
	// ResolutionIndivisibleByWindow: the resolution fits, but does not divide the span evenly, so the
	// newest bucket would be narrower than the width reported for it.
	ResolutionIndivisibleByWindow
)

func ResolutionWindowCause

func ResolutionWindowCause(err error) ResolutionWindowReason

ResolutionWindowCause reports which window-dependent rejection produced err, or ResolutionWindowNone.

ONE FUNCTION RATHER THAN A PREDICATE PLUS A LOOKUP, so a caller cannot ask "was it the window?" without being handed the answer to "which one?". The version this replaces answered only the first question, and the caller then wrote one message for both.

type Snapshot

type Snapshot struct {
	// Window is the span this snapshot ACTUALLY covers, e.g. "10m", "6h0m0s" or
	// "today". Not necessarily the span requested.
	//
	// The difference matters: the symbolic windows ("today", "7d", "month") are served from the
	// durable cost ledger, and a proxy with no ledger — Kubernetes by design — answers
	// them from the ring's maximum window instead and reports THAT here. A client must
	// read this field rather than echo its own request, or it will label six hours of
	// spend as a day's.
	Window string `json:"window"`
	// BucketSeconds is the resolution of the buckets actually returned, which for a
	// ring-backed window is the requested resolution rounded to a whole multiple of
	// BucketWidth. A client reads this rather than assuming: asking for a resolution
	// the storage cannot divide evenly gets the nearest one that works, not an error.
	//
	// For a LEDGER-backed window it is the whole window's span, because that response
	// is one bucket rather than a series — the ledger answers "what did today cost",
	// and synthesising per-minute buckets from disk for a 7-day span would read
	// millions of rows to draw a chart nothing asks for. Reading this field is how a
	// client tells the two apart.
	BucketSeconds int `json:"bucketSeconds"`
	// Session is the session this covers, or "" for all sessions combined.
	Session string `json:"session,omitempty"`
	Group   Group  `json:"group"`

	// Currencies is every distinct unit behind a figure in Totals — a priced request or a
	// saving — sorted.
	//
	// IT TRAVELS BESIDE THE FIGURES BECAUSE IT CANNOT LIVE INSIDE THEM. Counts is a flat
	// summable aggregate, and it has to stay one — a unit belongs to the grouping key, not to
	// the numbers, or every consumer would be invited to add across it. So the fact that a
	// total spans two units is stated here, and a reader decides what it may legally add.
	//
	// MORE THAN ONE ENTRY MEANS Totals.CostMicros IS NOT A FIGURE. Summing credits into dollars
	// produces a number that is neither, and it looks exactly like a correct one — larger, not
	// obviously wrong. A consumer seeing two entries must refuse to present a single total;
	// `agentop cost` does, and says which units it found.
	//
	// ABSENT MEANS NOT COMPUTED OR NOTHING TO LABEL, and a client must not turn that into a
	// refusal: an idle window names no unit, and a producer older than the ring's unit tally omits
	// it for ring windows. Both the ledger and the ring fill it now. One entry is fine. Only two or
	// more is a claim.
	Currencies []string `json:"currencies,omitempty"`

	// Agent is the agent= filter this snapshot was narrowed to, set only when the producer applied it,
	// so a client can tell a narrowed answer from a server that ignored the parameter.
	Agent string `json:"agent,omitempty"`
	// Project is the project= filter this snapshot was narrowed to, set only when the producer
	// applied it, with the same contract as Agent: absent means "not applied".
	Project model.LenientString `json:"project,omitempty"`
	// SeriesCurrencies names, for group=model, endpoint and agent, the units EACH series is in —
	// the cross-tabulation Currencies cannot carry, so one agent's (or model's, or endpoint's)
	// figure can be labelled and summed without borrowing another's units. Keyed like the series;
	// absent for every other grouping and from older producers, which a client reads as "unknown"
	// and falls back to Currencies for.
	SeriesCurrencies map[string][]string `json:"seriesCurrencies,omitempty"`
	// Buckets runs oldest to newest. For a ring-backed window it always has
	// Window/BucketWidth entries, including zeroed ones for idle minutes, so a client
	// can distinguish an idle minute from one that fell off the end of the ring.
	//
	// A LEDGER-backed window (see BucketSeconds) returns exactly ONE bucket spanning
	// the request. A client dividing len(Buckets) into the window to recover a
	// resolution must read BucketSeconds instead.
	Buckets []Bucket `json:"buckets"`
	// Totals sums every bucket, so a client need not re-add them to render a
	// summary line.
	Totals Counts `json:"totals"`
	// Priced reports whether ANY request in this window produced a cost. False
	// means CostMicros is absent everywhere, and a client must say "cost
	// unavailable" rather than display $0.00 — which would read as "this traffic
	// was free".
	//
	// True does NOT mean every request was priced. Compare Totals.PricedRequests
	// against Totals.PriceableRequests: cost comes from a plugin that may not be in
	// the pipeline for all traffic, and once rates are per-endpoint a deployment can
	// price some endpoints and not others. Where those differ the dollar total
	// covers only the priced subset, and a client showing it must say so.
	//
	// PRICEABLE, not Requests. Requests counts every proxied response — MCP tool
	// calls, health checks, tunnels — none of which can ever carry a price, so that
	// denominator makes a correctly configured deployment report itself incomplete
	// forever. See Counts.PriceableRequests, which exists for this.
	//
	// Nor does it mean the total is EXACT. Totals.IncompleteRequests counts priced
	// requests whose figure is a lower bound (a stream truncated before its output
	// count) or an approximation (a gateway reporting only a total). While that is
	// non-zero the dollar total is inexact, and a client rendering it as an exact figure
	// is making a claim the data does not support. It is a SUBSET of PricedRequests, not
	// a deduction from it — the coverage question and the exactness question are
	// separate, and this field answers neither on its own.
	Priced bool `json:"priced"`
	// DaysOutsideRetention is how many days of the REQUESTED window fall before the durable
	// ledger's retention horizon. A COVERAGE statement, and a CEILING: the configuration does
	// not promise those days, so spend on them may be missing from the total.
	//
	// NOT A LOSS, AND DELIBERATELY NOT IN Degraded, whose downstream meaning is "rows are
	// missing from the sum". Nothing in the ledger records its own inception or what prune
	// deleted, so an absent old day is indistinguishable from a day that was never written — a
	// three-day-old install with retention_days=10 has twenty-two absent days before its cutoff
	// and lost nothing. Reporting that as damage would make the disclosure fire when nothing
	// was pruned, and noise on a disclosure is how a real one gets ignored.
	//
	// What it states instead is the part a client can act on and the server can prove: this
	// window asked for N days the configuration does not reach. Whether spend happened on them
	// is unknowable here, and so is whether the total includes it.
	//
	// AN EARLIER VERSION OF THIS SAID "that the total cannot include it is certain". It is not,
	// and the state that breaks it is ordinary rather than exotic: cost/ledger's prune floors its
	// reference day at the NEWEST day file, so a ledger nothing has written to keeps its last
	// retainDays files however long ago they were written — while this figure is measured from
	// the clock. A query then sums day files this field has already called outside. Reproduced
	// in cost/ledger's TestSnapshot_ADayReportedOutsideRetentionCanStillBeInTheTotal:
	// retention_days 10, files for 21 consecutive days, read ten days after the last write —
	// 21 days reported outside, and ten days of spend in the total.
	//
	// A CLIENT MUST THEREFORE RENDER THIS AS "may be missing", never as a deduction from the
	// figure beside it. Both shipped consumers do: the band marks the total a floor, and
	// `agentop cost` prints a coverage line.
	//
	// SAME SHAPE AS THE UNPRICED COVERAGE GAP beside it — Unpriced over Priceable — which is
	// why it sits here rather than with the damage counters: both say "this figure covers less
	// than the question implied", and neither says anything was destroyed.
	//
	// ZERO DOES NOT MEAN THE TOTAL IS COMPLETE, and a client must not read it that way. It is
	// measured against retention_days AS CONFIGURED NOW, so a day pruned while the setting was
	// SHORTER is inside today's horizon and reported by nothing: set retention_days to 9, run
	// for a week, set it back to 31, and the month's total is short with this field at 0. The
	// same is true of a day prune deleted for any other reason. Closing that needs a persisted
	// inception date or a prune record and the ledger keeps neither — and inferring one from the
	// files present is the false-positive design this field replaced.
	DaysOutsideRetention int64 `json:"daysOutsideRetention,omitempty"`
	// UnpricedBy counts the requests that could NOT be priced, keyed
	// "<endpoint> <model>". Present only when something was unpriced — and never
	// present at all on a ledger-backed window, where a per-minute row carries only
	// its own labels and cannot distinguish the unpriced pairs from the priced ones.
	// Absence is therefore not a claim that there were no gaps; compare
	// Totals.PricedRequests with Totals.PriceableRequests for that.
	//
	// A gap has to be nameable, not just countable. "Cost is incomplete" gives an
	// operator nothing to act on; "api.openai.com gpt-5: 412" names the pair to
	// investigate. Traffic carrying no model is excluded — naming every non-LLM
	// call the proxy handled would bury the real gaps.
	//
	// "ADD A PRICING ENTRY" IS NOT ALWAYS THE REMEDY, and this field cannot say which it
	// is. A pair lands here when no rate covers it, when the rate covers only some of the
	// tiers the request used, AND when the figure the rates produced was refused as
	// implausible — an absurd rate, or a token count that cannot be one. In that last case
	// the entry already exists and the fix is upstream of it. See usage.Aggregator.costOf,
	// which is where the causes converge, and event.RejectedImplausible, which keeps
	// them apart on the path that CAN report per request.
	//
	// Summed across the window from the raw buckets, so it is unaffected by the
	// requested resolution, exactly like Totals.
	UnpricedBy map[string]int64 `json:"unpricedBy,omitempty"`
	// PricedBy counts priced requests by the provenance of their figure —
	// "authoritative" when the gateway reported it, otherwise the rate table's level
	// ("configured", "discovered", "bundled").
	//
	// Without it a total is unqualified, and the spec's own success criterion asks
	// for cost "labelled with provenance": $12.40 assembled from a gateway's own
	// numbers and $12.40 modelled from a shipped vendor-list table are not equally
	// trustworthy figures, and nothing else in the response distinguishes them.
	//
	// Summed from the raw buckets alongside Totals, so it is unaffected by the
	// requested resolution.
	PricedBy map[string]int64 `json:"pricedBy,omitempty"`
	// IncompleteBy counts the priced requests whose figure is INEXACT, keyed by WHICH WAY
	// it is inexact — "output-uncounted" for a lower bound (a stream that died before its
	// output count, so the true figure is HIGHER), "split-unreported" for an approximation
	// (a gateway reporting only a total, so it is off in no known direction), or
	// "unlabelled" for a caveat a producer disclosed without naming its kind. See
	// pricing.ReasonOutputUncounted and pricing.ReasonSplitUnreported.
	//
	// Totals.IncompleteRequests answers HOW MANY; this answers IN WHICH WAY, and the two
	// are different claims about money. "At least $12.40" and "roughly $12.40" cannot be
	// rendered the same way: one is a bound that will be exceeded and is usually a
	// transient failure worth chasing, the other a standing property of a gateway that
	// holds for every request it answers. A client that can see only the count has to
	// present them identically, which is how a permanent caveat comes to read as an
	// incident.
	//
	// Its counts SUM to Totals.IncompleteRequests. An inexact figure whose producer named
	// no reason is counted under "unlabelled" rather than omitted, so a client subtracting
	// the map from the counter gets zero and cannot mistake a dropped row for a request
	// whose figure is exact.
	//
	// Present only when something was inexact — and never present at all on a
	// LEDGER-backed window, where a per-minute row carries IncompleteRequests but not the
	// reason: the reason is no part of that row's (endpoint, model, agent, provenance) key,
	// so a persisted row cannot say which way its inexact figures were inexact. Absence is
	// therefore not a claim that every figure is exact; Totals.IncompleteRequests answers
	// that, and both window kinds populate it.
	//
	// Summed across the window from the raw buckets, so it is unaffected by the requested
	// resolution, exactly like Totals and the two maps above.
	IncompleteBy map[string]int64 `json:"incompleteBy,omitempty"`
	// UngroupedCostMicros is the part of Totals.CostMicros that NO entry in this
	// response's series carries — the amount by which summing the breakdown falls short
	// of the total printed beside it.
	//
	// The dominant instance is a GATEWAY-PRICED RESPONSE THE INFERENCE PARSER COULD NOT
	// READ: /v1/embeddings and /v1/rerank are not among the paths it parses, so the event
	// carries no model while the gateway's own header settles a cost, and that spend counts
	// toward Totals and drops out of group=model. Per-axis that is the honest answer — there
	// is no model to attribute it to, and moving it into a made-up bucket or out of the
	// totals would each be worse. Undisclosed, though, it makes the response contradict
	// itself with nothing to explain the difference.
	//
	// WHAT A CLIENT DOES WITH IT: render it as its own residual band — "unattributed", or
	// the (other) band a table already collapses into — and never present the sum of a
	// series as the window's total. The arithmetic it restores is exact:
	// sum(series CostMicros) + UngroupedCostMicros == Totals.CostMicros, for every group
	// where Group.Reconcilable is true AND the source answering could group by it — read
	// the Group this response reports, not the one that was requested, since a
	// ledger-backed window reports GroupNone for an axis its rows have no column for. See
	// Group.Reconcilable for why one predicate was not enough.
	//
	// BOTH WINDOW KINDS POPULATE IT, verified rather than assumed — which is why this is not
	// ledger-only the way Degraded is, and it has to hold on both or a client would come to
	// trust the reconciliation and then have it break at whichever window boundary switches
	// storage:
	//   - a LEDGER window, because such a response is stored as a row with Model "" and
	//     ledger.labelFor then returns ok=false for group=model. Pinned by
	//     TestFold_GatewayPricedRowWithNoModelIsDisclosedAsUngrouped, which lives with the ledger
	//     reader.
	//   - a RING window, because Aggregator.costOf prices any SETTLED cost record whether or
	//     not the event carries an Inference extension, while foldInto guards byMethod on a
	//     non-empty model — so the same spend lands in the bucket total and in no series
	//     entry. Pinned by
	//     TestSnapshot_GatewayPricedTrafficWithNoModelIsDisclosedAsUngrouped.
	//
	// A POINTER, absent rather than zero on a window whose series accounts for
	// everything — the Degraded convention, for the reason its doc gives. A zero would
	// have to carry two meanings: "the breakdown accounts for every dollar" and "this
	// group offers no reconciliation at all". group=none asks for no series, and
	// group=plugin's series counts one request once per plugin, so neither sets this; a
	// client must read Group before concluding anything from its absence. See
	// Group.Reconcilable.
	//
	// COST, not a request count, and not keyed like UnpricedBy. The question it answers is
	// arithmetic — a breakdown that does not add up to the total above it — and requests
	// cannot be subtracted from dollars. A key would have to come from a DIFFERENT axis
	// than the one the client grouped by (the endpoint, for a row with no model), and the
	// ring cannot produce that key without a label map it does not keep, so the two window
	// kinds would then disagree about the shape as well as the number.
	//
	// Summed from the raw buckets alongside Totals, so it is unaffected by the requested
	// resolution.
	UngroupedCostMicros *int64 `json:"ungroupedCostMicros,omitempty"`
	// SeriesOvershootMicros is the residual with the WRONG SIGN: the amount by which this
	// response's series summed to MORE than Totals.CostMicros.
	//
	// It is not a property of the traffic. Every event lands in at most one entry of a
	// reconcilable group's map, so the entries can only sum to the total or to less than it —
	// a negative residual means this process is wrong about its own arithmetic. There are
	// exactly two ways: a Group was marked Reconcilable when its series double-counts (which
	// is why GroupPlugin is excluded), or a series accumulator counts one event twice.
	//
	// IT MUST NOT COLLAPSE INTO "no residual". A `micros <= 0` guard treats "the breakdown
	// accounts for everything" and "the breakdown accounts for MORE than everything" as the
	// same clean answer, and the second is a defect report. Reconcilability is now a property
	// of the SOURCE as well as the group (see Group.Reconcilable), so a disagreement between
	// the two predicates is a live possibility, and this residual going negative is how it
	// would show.
	//
	// A SEPARATE FIELD rather than a negative UngroupedCostMicros, because the two are
	// different claims and a client acts on them differently. UngroupedCostMicros is a
	// residual band to render — real spend with no key on this axis. This is "do not trust
	// the breakdown in this response, and file a bug", and no chart should draw it. Signing
	// one field would have every consumer branch on the sign to tell a normal response from a
	// broken one, and the ones that forgot would render a negative band.
	//
	// ABSENT unless it happened, on the same rule as UngroupedCostMicros and Degraded: it
	// should never appear in a healthy deployment, and a zero would have to mean both "checked
	// and fine" and "not checked".
	SeriesOvershootMicros *int64 `json:"seriesOvershootMicros,omitempty"`
	// UngroupedAvoidedMicros is UngroupedCostMicros for the OTHER money field: the part of
	// Totals.AvoidedMicros that no entry in this response's series carries.
	//
	// It exists because Counts.AvoidedMicros ships per label automatically — Series is a map
	// of Counts and Counts.Add carries the field — so the moment a client renders a per-model
	// "saved" breakdown, that breakdown can sum to LESS than the total beside it. Without
	// this field there is nothing to explain the gap, which is the exact failure
	// UngroupedCostMicros exists to prevent, arriving through a field added later.
	//
	// REACHABLE, and by a route the cost residual mostly is not: a row can carry a saving
	// with no model at all. ledger.Writer.Record admits a cost record whose only figure
	// is an applied saving even when the response had no inference extension to read a model
	// from — deliberately, because a saving on a request nothing could price is the case
	// event.Record was split out to serve. Under group=model that row has no label, so
	// its saving lands here and nowhere else.
	//
	// Same absent-not-zero rule as its twin: a zero would have to mean both "checked, the
	// breakdown is complete" and "nothing computed a residual on this path".
	UngroupedAvoidedMicros *int64 `json:"ungroupedAvoidedMicros,omitempty"`
	// SeriesAvoidedOvershootMicros is SeriesOvershootMicros for avoided cost: the amount by
	// which this response's series summed to MORE than Totals.AvoidedMicros.
	//
	// A SEPARATE FIELD FROM SeriesOvershootMicros, and not redundant with it, which is the
	// question to ask of any second defect-report field. The shared cause — a reconcilable
	// group whose series double-counts — moves both residuals and would fire both. But a row
	// carrying a saving and NO COST double-counted moves only this one: the cost residual
	// stays at zero, which reads as "the breakdown accounts for everything". So the cost
	// field alone cannot report an avoided overshoot, and collapsing them would make a real
	// defect invisible in exactly the case this PR made reachable.
	//
	// Nothing should render it. See SeriesOvershootMicros: this is "do not trust the
	// breakdown in this response, and file a bug".
	SeriesAvoidedOvershootMicros *int64 `json:"seriesAvoidedOvershootMicros,omitempty"`
	// Degraded reports that this answer is known to be MISSING ROWS, and is absent
	// whenever it is not.
	//
	// A DIFFERENT CLAIM from Totals.IncompleteRequests, and the two must not be merged.
	// That counter says a figure this response CARRIES is inexact — a floor, or an
	// approximation — and the request is still counted and still priced. This field says
	// rows the answer needed could not be read at all, so the total is short by an
	// amount nothing here can state. One qualifies a number; the other says a number is
	// missing from the sum.
	//
	// A POINTER, so a clean read serialises nothing rather than zeros a client has to
	// interpret. Absence means the read was clean; presence means look at it. Zeros in
	// an always-present object would read as "checked, fine" from a producer that never
	// checked, which is the same class of false reassurance as a $0.00 over unpriced
	// traffic.
	//
	// Only a ledger-backed window can populate it. The ring is memory: it has no lines
	// to fail to decode and no files to abandon, so a duration window leaves this nil
	// and that absence is the truth rather than a gap in the reporting.
	Degraded *Degraded `json:"degraded,omitempty"`
}

Snapshot is the wire shape of GET /v1/usage.

func NarrowToAgent

func NarrowToAgent(snap Snapshot, agent string) Snapshot

NarrowToAgent is ScopeToAgent for a producer answering agent=: a group=agent snapshot becomes one agent's, with the echo set. An agent with no traffic in the window gets zeroed buckets rather than an error. The narrowed buckets carry no series, so any grouping is served as none, and Group says so.

func NarrowToLabel

func NarrowToLabel(snap Snapshot, label string) Snapshot

NarrowToLabel is NarrowToAgent for any series axis: a grouped snapshot becomes one series's, served as group none. It KEEPS snap.Agent, so a group=project read for one agent narrowed to one project still says which agent it is. A label with no series gets zeroed buckets, not an error.

func ScopeToAgent

func ScopeToAgent(snap *Snapshot, agent string, buckets BucketScope) (*Snapshot, error)

ScopeToAgent narrows a group=agent snapshot to one agent's figures.

IT REWRITES Totals AND HANDS BACK A SNAPSHOT, rather than rendering the agent itself, so callers apply their existing writers to it with no second implementation and no chance of the two drifting: `agentop cost`'s negative-total refusal, coverage-gap disclosure and incomplete-read admission each read one agent's numbers, and the TUI's chart reads the same narrowing. Which fields do NOT survive, and why, is stated at each narrowing below. A COPY, never the caller's snapshot mutated in place.

The fold is FoldSeriesAcrossWindow, the same one agentop's AGENTS pane uses, so the figure printed by the CLI and the row shown in the pane cannot disagree.

AN UNKNOWN AGENT IS AN ERROR THAT NAMES THE KNOWN ONES. The labels are User-Agents, so they are neither short nor guessable — "bob" is the obvious thing to try and is not what Bob sends. The set is already in hand, so withholding it would be a choice.

func (*Snapshot) SetUngroupedAvoided

func (s *Snapshot) SetUngroupedAvoided(sum event.CostSum)

SetUngroupedAvoided is SetUngroupedCost for avoided cost.

Split from it rather than folded into one two-argument call because the two are published on different fields and a caller may legitimately have only one to report — the ledger path computes both, the ring path computes both, and a future source that breaks down only spend should not be forced to pass a zero that this method cannot distinguish from a real one. The SHARED half — saturation, the sign split, the MinInt64 guard — lives in setResidual so the two cannot drift.

NOT SPEND, and this method changes nothing about that: it publishes a residual for a counterfactual so a breakdown of it reconciles, on the same rule that forbids adding it to any dollar total. See Counts.AvoidedMicros.

func (*Snapshot) SetUngroupedCost

func (s *Snapshot) SetUngroupedCost(sum event.CostSum)

SetUngroupedCost records the residual, whichever way it went, and leaves both fields ABSENT when there is none.

The single implementation of the absent-not-zero rule, called by the ring in Snapshot and by the ledger in sessionapi, so neither can serialise a zero that would read as "checked, complete" from a path that computed nothing. See Snapshot.UngroupedCostMicros.

A NEGATIVE RESIDUAL IS A DEFECT REPORT, not "nothing to disclose": only a shortfall can happen to correct code, since a reconcilable group's series sums to the total or to less. A negative means a Group is marked reconcilable while its series double-counts, or an accumulator counted an event twice, so it travels as Snapshot.SeriesOvershootMicros rather than being discarded at the one place that could see it.

Both callers get that for free, which is why the disclosure lives here rather than in an error return: an error would need every caller to hold a logger (this package has none) and would let a caller drop the signal again.

IT TAKES AN event.CostSum RATHER THAN AN int64 so a clamped residual cannot arrive looking like an exact one. Accumulated with a bare `+=`, a wrap produces a NEGATIVE figure, which the second case below then publishes as SeriesOvershootMicros — so correct-but-saturated data fabricates a defect report while the real residual is lost. A parameter that carries its own saturation flag is what stops the two conditions being confused; an int64 plus a bool a caller could forget is the shape that produced it.

type Spec

type Spec struct {
	// Label is what the response echoes back, so a client always learns which
	// window it actually got — which matters most when it is not the one asked for.
	Label string
	// Dur is non-zero for a fixed-length window.
	Dur time.Duration
	// From and To bound a symbolic window. Zero when Dur is set.
	From, To time.Time
}

Spec is a parsed window request. Either Dur is set (a fixed length the ring can serve) or From/To are (a boundary only the ledger can serve).

Two representations in one type rather than two functions, because the handler's job is exactly to choose between them and a caller that forgets to ask which kind it has would silently serve the wrong span.

func ParseWindowSpec

func ParseWindowSpec(s string, now time.Time) (Spec, error)

ParseWindowSpec parses any window the API accepts, including the symbolic ones.

now is passed rather than read from the clock so a test can pin a day boundary, and so "today" is computed once per request instead of drifting between the bound calculation and the response label.

"today" is the START OF THE LOCAL DAY to now. Local, not UTC: a laptop that crosses a timezone must not have its day reset mid-afternoon, which a UTC day would do. Just after the day starts it is a five-minute window, not a 24-hour one — that is the point of a boundary rather than a length.

The start of the day, NOT "local midnight", and the distinction is not pedantry: midnight does not exist on the spring-forward day of any zone whose transition is at 00:00, and it occurs twice on the autumn one. StartOfLocalDay states which instant is meant and why, and it is the same day boundary the cost ledger names its files by.

"7d" is exactly 7x24h back from now, ROLLING rather than seven calendar days. The label is echoed as "7d" so a client can read it that way; a "last 7 days" that silently meant "since last Monday" would be a different number, and the two differ by up to a day of spend.

Delegates every fixed-length case to ParseWindow, so the duration set is defined in one place and the two cannot drift.

func (Spec) Symbolic

func (s Spec) Symbolic() bool

Symbolic reports whether this window needs the ledger.

Jump to

Keyboard shortcuts

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