Documentation
¶
Overview ¶
Package usagereport builds the token ledger read model: what each provider burned, which projects and people it was burned for, and where a given provider is actually used.
It lives here, rather than inside the providers page that first needed it, because the same ledger is read from two places that have nothing else in common — the Svelte providers UI and the server-rendered admin analytics page. Two renderers over one report is fine; two reports that "should" agree is how a host ends up with a $29.08 on one page and a $31.40 on another, with nobody able to say which is wrong.
Everything here is derived from the per-session usage.json files. The roll-up walks one small file per session, so it is cached per window: an analytics view that is a few seconds stale costs nobody anything, while re-walking thousands of sessions on every poll shows up as disk churn on a small box.
Index ¶
- Constants
- Variables
- func KeepsProviders(selected, used []string) bool
- func MatchesAny(selected, used []string, none string) bool
- func ParseDate(s string, loc *time.Location) time.Time
- func ParseInstant(s string, loc *time.Location) time.Time
- func SortSlices(rows []Slice)
- type Builder
- func (b *Builder) Provider(key string, w Window, sc Scope, force bool) (ProviderReport, error)
- func (b *Builder) Report(w Window, sc Scope, force bool) (Report, error)
- func (b *Builder) Rollup(w Window, sc Scope, force bool) (store.UsageRollup, error)
- func (b *Builder) Sessions(w Window, sc Scope, force bool, sortBy string, limit int) (SessionsReport, error)
- type Option
- type ProviderReport
- type Report
- type Scope
- type SessionRow
- type SessionUse
- type SessionsReport
- type Slice
- type Subject
- type TextMatch
- type TextMatches
- type Totals
- type TrendPoint
- type Window
Constants ¶
const ( SortTokens = "tokens" // most tokens first (the default) SortCost = "cost" // highest cost first SortTurns = "turns" // most turns first SortRecent = "recent" // most recently used first )
Sort orders for Builder.Sessions.
const ( MatchInTitle = "title" MatchInSession = "session" MatchInAny = "any" MatchInModel = "model" MatchInProvider = "provider" MatchInPerson = "person" MatchInChannel = "channel" MatchInProject = "project" MatchInAgent = "agent" MatchContains = "contains" MatchExact = "exact" MatchRegex = "regex" )
Condition fields and modes, as the page sends them.
const CacheTTL = 15 * time.Second
CacheTTL is how long a computed roll-up is reused. Short enough that a finished turn shows up while the user is still looking at the page, long enough that a dashboard polling every second does not walk the session tree every second.
const NoPerson = "(unattributed)"
NoPerson is the key for sessions with nobody attributed: machine callers from before ownership was stamped, channels with no account.
const NoProvider = "(none)"
NoProvider is the key a session with no provider recorded is filed under, so a filter can select it instead of silently dropping it. The model filter uses it the same way.
Variables ¶
var WindowKeys = []string{"today", "7d", "30d", "90d", "1y", "all"}
WindowKeys lists the ranges in the order a UI should offer them — narrowest first, because the narrow ones are what people check repeatedly and the wide ones are what they check once.
Functions ¶
func KeepsProviders ¶ added in v1.18.0
KeepsProviders reports whether a session that ran on `used` passes a selection of provider keys. A session that switched provider matches when ANY of its providers is selected, and one with none recorded matches only NoProvider.
func MatchesAny ¶ added in v1.18.0
MatchesAny is the rule every multi-value filter shares: a session passes when ANY of its values is selected, and one with no value passes only when the `none` bucket is.
func ParseDate ¶
ParseDate reads a YYYY-MM-DD from a query string in the given location. A value it cannot read is a zero time, i.e. "no bound", which is the safe reading of a malformed date on a reporting page.
func ParseInstant ¶ added in v1.18.1
ParseInstant reads a bound that may carry a time of day; a date alone is that day's midnight. Without a zone the value is read in loc. Unreadable is a zero time, the same "no bound" ParseDate answers.
func SortSlices ¶
func SortSlices(rows []Slice)
SortSlices orders by cost, then by tokens, then by key — cost first because that is the question being asked, key last so the order is stable when two rows tie (a list that reshuffles between polls is unreadable).
Types ¶
type Builder ¶
type Builder struct {
Layout config.Layout
UserName func(id string) string
// Tags resolves a session id to what the roll-up groups and filters
// by. Optional: the default reads the session from disk. A caller
// that already keeps a cache of session facts (the admin analytics
// page does) should supply it and save the second walk — same data,
// read once.
Tags func(id string) store.SessionTags
// contains filtered or unexported fields
}
Builder computes and caches reports for one host.
UserName resolves a wick user id to a name; it comes from the caller because the mapping lives in the database and this package must stay free of it. Nil is fine — rows then show the id, which is still the truth about who spent it.
func (*Builder) Provider ¶
Provider builds the one-provider report, naming every session it was used in. A bare session id told a reader nothing — whose work it was and which project it belonged to is the whole question behind "where is this provider used".
func (*Builder) Rollup ¶
Rollup returns the cached roll-up for a window, recomputing when stale or when force is set (the explicit Refresh button, never a poll).
func (*Builder) Sessions ¶ added in v1.18.1
func (b *Builder) Sessions(w Window, sc Scope, force bool, sortBy string, limit int) (SessionsReport, error)
Sessions lists the conversations of a window, merged across providers and ordered by sortBy (SortTokens when empty or unknown). limit <= 0 returns every row.
type ProviderReport ¶
type ProviderReport struct {
Provider string `json:"provider"`
Window string `json:"window"`
WindowLabel string `json:"window_label"`
Since string `json:"since,omitempty"`
Windows []Option `json:"windows"`
Totals Totals `json:"totals"`
Turns int `json:"turns"`
// ByModel is this provider's own spend split by model — the same
// rows the fleet report carries, narrowed to this one door.
ByModel []Slice `json:"by_model,omitempty"`
Sessions []SessionUse `json:"sessions"`
Partial bool `json:"partial,omitempty"`
Note string `json:"note,omitempty"`
}
ProviderReport answers "what did THIS provider cost, and where was it used" for one provider key ("claude/default").
type Report ¶
type Report struct {
Window string `json:"window"`
WindowLabel string `json:"window_label"`
Since string `json:"since,omitempty"`
Until string `json:"until,omitempty"`
Windows []Option `json:"windows"`
Totals Totals `json:"totals"`
Turns int `json:"turns"`
Sessions int `json:"sessions"`
ByProvider []Slice `json:"by_provider"`
// ByModel goes one level below the provider: a provider is a door,
// and which model answered behind it is what decides both the bill
// and whether the answer was any good. Rows are (provider, model)
// pairs — see store.ModelRowKey.
ByModel []Slice `json:"by_model"`
ByProject []Slice `json:"by_project"`
ByUser []Slice `json:"by_user"`
// Trend is the window over time, oldest first, quiet buckets included
// as zeros so a gap reads as a gap. TrendUnit is its grain: "hour" for
// a window of two days or less, "day" up to a year, "month" beyond.
Trend []TrendPoint `json:"trend,omitempty"`
TrendUnit string `json:"trend_unit,omitempty"`
// Partial says the window could not be reconstructed in full for
// every session — see store.UsageRollup.Partial. Carried into the
// DTO so the UI can say "at least" instead of implying a total.
Partial bool `json:"partial,omitempty"`
Note string `json:"note,omitempty"`
}
Report is the whole-fleet answer for one window.
type Scope ¶
type Scope struct {
Channels []string
// Instances narrows to specific bots ("slack:<owner id>"). It only
// means anything when the Builder's Tags resolver fills
// SessionTags.Instance — the default one cannot, so a caller using it
// must leave this empty rather than get an empty report that reads
// like a real answer.
Instances []string
// Providers narrows to sessions that ran on any of these provider keys
// ("claude/work"). NoProvider selects the sessions with none recorded.
// Like Instances, it needs a Tags resolver that fills
// SessionTags.Providers.
Providers []string
// People narrows to sessions any of these wick user ids took part in;
// NoPerson selects the ones nobody is attributed to. Models narrows to
// sessions run on any of these models, NoProvider for none recorded.
People []string
Models []string
// Text is the page's conditions (title, session id, model, channel…);
// see TextMatches. Instance-free, so it works with any Tags resolver.
Text TextMatches
}
Scope narrows the ledger the way a page's filter bar does: to certain channels, or to specific bots within them. Empty means everything.
It exists so a page with one filter bar has ONE answer below it. A token figure that ignored the channel filter would sit next to a chart that honoured it, and the two would disagree without either being wrong — the worst kind of dashboard bug, because nothing looks broken.
type SessionRow ¶ added in v1.18.1
type SessionRow struct {
SessionUse
Channel string `json:"channel,omitempty"`
Agent string `json:"agent,omitempty"`
Providers []string `json:"providers,omitempty"`
}
SessionRow is one conversation's spend in the window. Share is its percentage of the report total, the number that says "this one session is a third of the bill".
type SessionUse ¶
type SessionUse struct {
ID string `json:"id"`
Label string `json:"label,omitempty"`
ProjectID string `json:"project_id,omitempty"`
ProjectName string `json:"project_name,omitempty"`
UserID string `json:"user_id,omitempty"`
UserName string `json:"user_name,omitempty"`
LastAt string `json:"last_at,omitempty"`
Turns int `json:"turns,omitempty"`
Totals Totals `json:"totals"`
}
SessionUse is one line of "where is this provider used": which conversation, whose, under what project, and what it spent there.
type SessionsReport ¶ added in v1.18.1
type SessionsReport struct {
Window string `json:"window"`
WindowLabel string `json:"window_label"`
Since string `json:"since,omitempty"`
Until string `json:"until,omitempty"`
Sort string `json:"sort"`
Totals Totals `json:"totals"`
Turns int `json:"turns"`
// Total is how many sessions matched; Sessions holds at most the limit
// asked for, so a caller can say "top 20 of 263".
Total int `json:"total"`
Sessions []SessionRow `json:"sessions"`
Partial bool `json:"partial,omitempty"`
Note string `json:"note,omitempty"`
}
SessionsReport answers "which conversations spent it": every session in the window and scope, one row each, across all providers it ran on.
type Slice ¶
type Slice struct {
Key string `json:"key"`
Label string `json:"label,omitempty"`
Totals Totals `json:"totals"`
Sessions int `json:"sessions,omitempty"`
// Turns is how many turns this row ran. Cost answers "what is
// expensive"; turns answer "what do we actually use" — and on a flat
// -rate plan, where every cost is zero, turns are the only answer
// there is.
Turns int `json:"turns,omitempty"`
// Group is the row this one hangs under: for a model row, the
// provider it was reached through. The same model id through two
// providers is two rows, and without this the UI cannot say why.
Group string `json:"group,omitempty"`
// drawn without the client summing the list first.
Share float64 `json:"share"`
}
Slice is one row of a breakdown, sorted by cost then tokens so the expensive row is always first.
func ModelSlices ¶
func ModelSlices(roll store.UsageRollup, grand int, provider string) []Slice
ModelSlices turns the roll-up's (provider, model) buckets into rows.
`provider` narrows to one door, or is empty for the whole fleet. The row's Label is the model id — the thing anyone reading this actually asked about — and Group names the provider it came through, so a model reached through two accounts reads as two rows rather than as a mystery duplicate.
type Subject ¶ added in v1.18.0
type Subject struct {
ID, Title, Channel, Project, Agent string
Models, Providers, People []string
}
Subject is what a condition can read off one conversation. The list fields hold every value the conversation had — a session that switched model ran on both — and a condition hits when ANY of them does, so "model is X" keeps it and "model is not X" drops it.
type TextMatch ¶ added in v1.18.0
type TextMatch struct {
Pattern string
// In is the field to read: one of the MatchIn* constants. "any" is
// the title or the session id.
In string
// Mode is how: "contains", "exact" or "regex". Case never matters —
// a title typed by a person is not something to match case-exactly.
Mode string
// Not inverts the rule: "not contains", "not exact", "not regex".
// Sent as the mode with a "not_" prefix.
Not bool
// Err is set when the regex does not compile. Such a match keeps
// nothing: falling back to "everything" would print the unfiltered
// totals under a filter the reader believes is applied.
Err string
// contains filtered or unexported fields
}
TextMatch is one condition of the page's condition builder: a field of the conversation (its title, id, model, channel…), an operator and a value. Chips answer "which account, which model"; conditions answer "which use case" — every conversation one workflow opens shares a title shape ("daily-2026-10-…"), so "title contains X AND model is Y" is how a reader follows one use case across days and sees it grow or shrink.
The zero value matches everything.
func ParseTextMatch ¶ added in v1.18.0
ParseTextMatch builds a TextMatch from the query values. Unknown fields and modes fall back to the defaults (title, contains) rather than to an error: a stale link should still open.
type TextMatches ¶ added in v1.18.0
type TextMatches struct {
Rules []TextMatch
// Any joins the rules with OR; false joins them with AND.
Any bool
// Alias, when set, names an id-valued field ("person", "project") so
// a condition can be written with the name a reader sees on the page.
// Not part of the cache key: it only resolves, never narrows.
Alias func(field, key string) []string
}
TextMatches is several conditions joined by AND (every one must hold) or OR (any one is enough) — "title contains daily-2026-10 AND title contains shift-1 AND model is not haiku" without writing a regex. The zero value matches everything.
func ParseTextMatches ¶ added in v1.18.0
func ParseTextMatches(values []string, legacyIn, legacyMode, matchOp string) TextMatches
ParseTextMatches reads the rules off the query. Each "match" value is "<field>:<mode>:<pattern>"; a value without that prefix is the older single-rule form, read with match_in / match_mode as before, so a link shared before rules could be stacked still opens the same view. matchOp "or" joins with OR, anything else with AND.
func (TextMatches) Empty ¶ added in v1.18.0
func (m TextMatches) Empty() bool
Empty reports whether any rule narrows anything.
func (TextMatches) Err ¶ added in v1.18.0
func (m TextMatches) Err() string
Err is the first rule whose regex did not compile, "" when none. Such a set keeps nothing, whichever way it is joined: an OR that quietly dropped the broken rule would answer a narrower question than the one on screen.
func (TextMatches) Keep ¶ added in v1.18.0
func (m TextMatches) Keep(id, title string) bool
Keep reports whether a session with this id and title passes.
func (TextMatches) KeepSubject ¶ added in v1.18.0
func (m TextMatches) KeepSubject(s Subject) bool
KeepSubject reports whether one conversation passes every condition (AND) or any of them (OR).
func (TextMatches) Op ¶ added in v1.18.0
func (m TextMatches) Op() string
Op is "and" or "or", as the page sends it.
func (TextMatches) Values ¶ added in v1.18.0
func (m TextMatches) Values() []string
Values is the rules in their query form, for echoing back.
type Totals ¶
type Totals struct {
Input int `json:"input"`
CacheRead int `json:"cache_read"`
CacheWrite int `json:"cache_write"`
Output int `json:"output"`
Total int `json:"total"`
CostUSD float64 `json:"cost_usd"`
// CacheHitPct is cache reads as a share of all input tokens — the
// single most actionable number here, because a collapsing hit rate
// is what turns a cheap session expensive.
CacheHitPct float64 `json:"cache_hit_pct"`
}
Totals mirrors store.UsageTotals plus the two derived numbers every renderer would otherwise recompute for itself.
func TotalsOf ¶
func TotalsOf(t store.UsageTotals) Totals
TotalsOf derives the presentation totals from the stored flows.
type TrendPoint ¶ added in v1.18.0
type TrendPoint struct {
Key string `json:"key"`
Totals Totals `json:"totals"`
Turns int `json:"turns"`
Sessions int `json:"sessions"`
}
TrendPoint is one bucket of Report.Trend. Turns and Sessions are what a "per turn" or "per conversation" view divides the totals by.
type Window ¶
type Window struct {
Key string `json:"key"`
Label string `json:"label"`
Since time.Time `json:"-"`
Until time.Time `json:"-"`
}
Window is one selectable range. A zero Since means all time; a zero Until means "up to now".
func CustomWindow ¶
CustomWindow bounds the ledger by explicit dates, so "1-7 Sep" on a page means the same seven days in its token figures.
Dates are whole days in the server's timezone, the way a date picker means them: `from` starts at its midnight, `to` ends at the last instant of its day. A `to` earlier than `from` is treated as no upper bound rather than as an empty range — an inverted pair is a typo, and answering "zero" to it looks like a fact.
func ExactWindow ¶ added in v1.18.1
ExactWindow bounds the ledger by two instants, kept as given: a provider's rate-limit window starts mid-afternoon, not at midnight, and a question about it must not be widened to whole days. An inverted pair drops the upper bound, as CustomWindow does.
func ParseWindow ¶
ParseWindow resolves a key to a window, falling back to all time for anything unrecognised (including ""). An unknown range must not be an error: it arrives from a URL, and answering the broadest question is more useful than refusing to answer.
func WindowFromQuery ¶
WindowFromQuery resolves the range a request asked for: explicit dates win, otherwise a named window, otherwise all time. One function so the two mounts that serve this report cannot disagree about what a query string means.