query

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: MIT Imports: 17 Imported by: 0 modules, 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 query is the read API shared by the UI and the CLI (docs/ARCHITECTURE.md#query). Service includes cost provenance and additive 0.4.x endpoint identity queries. NewService implements the API on top of internal/store.

Index

Constants

View Source
const (
	SortRecent = "recent" // UpdatedAt desc (default)
	SortTokens = "tokens" // Tokens.Total() desc
	SortCost   = "cost"   // CostUSD desc
)

Session sort keys.

Variables

View Source
var ErrAmbiguousInstance = errors.New("query: session exists in more than one instance; use SessionIn or SessionCacheIn")

ErrAmbiguousInstance reports that a session id exists in more than one instance, so the instance-less Session(ctx, h, id) and SessionCache(ctx, h, id) calls cannot choose. Callers must retry with an explicit instance through SessionIn or SessionCacheIn; the legacy calls never silently pick an arbitrary instance, because that would attribute another data source's requests to this session.

Functions

func BranchKey

func BranchKey(project, branch string) string

BranchKey builds the grouping key for the branch dimension. A branch is only meaningful together with the repository it was checked out in — two repositories may both be on "main" — so the key is the pair and the two parts are joined with a byte that cannot appear in a path or a branch name. The repository part is the store's canonical project, so linked worktrees of one repository already fold together before the branch is appended.

func LoadPricingSettings

func LoadPricingSettings(ctx context.Context, st *store.Store, p *pricing.Pricer) error

func SessionIn

func SessionIn(ctx context.Context, s Service, h model.Harness, instance, id string) (SessionRow, []SessionRow, []AttributedEvent, error)

SessionIn resolves one session in one explicit instance. It is a free function so that callers holding a plain Service do not have to know about InstanceService, and it fails clearly when the implementation is not the SQL-backed service instead of silently falling back to an instance-less read.

func SplitBranchKey

func SplitBranchKey(key string) (project, branch string)

SplitBranchKey reverses BranchKey. An empty branch returns as an empty string rather than as a missing value, because "no branch was recorded" is itself a reportable state and must stay distinguishable from a wrong branch.

Types

type AttributedEvent

type AttributedEvent struct {
	model.UsageEvent
	CostSource CostSource `json:"costSource"`

	ResolvedProvider string             `json:"resolvedProvider"`
	Attrib           model.AttribSource `json:"attrib"`
	Cost             float64            `json:"cost"`
	Priced           bool               `json:"priced"` // false: no log cost and no known price
	// InstanceID is the data source instance the request was ingested from,
	// additive provenance for the same reasons as SessionRow.InstanceID.
	InstanceID string `json:"instanceId"`
	// contains filtered or unexported fields
}

AttributedEvent is a usage event with its resolved provider and cost.

type Bucket

type Bucket struct {
	Key      string       `json:"key"`
	Label    string       `json:"label"`
	Tokens   model.Tokens `json:"tokens"`
	CostUSD  float64      `json:"costUsd"`
	Requests int64        `json:"requests"`
	Sessions int64        `json:"sessions"`
	Unpriced int64        `json:"unpriced"` // see Totals.Unpriced
}

Bucket is one row of a ranking. Key is the stable id, Label the display name.

type CostSource

type CostSource string

CostSource identifies monetary provenance, independently of provider attribution. relay-bill is reserved for authoritative relay billing integrations.

const (
	CostSourceLog      CostSource = "log"
	CostSourceEstimate CostSource = "estimate"
	CostSourceUnpriced CostSource = "unpriced"
)

type DiagnosticsObservation

type DiagnosticsObservation struct {
	// Harness is the harness the record belongs to, decoded from the settings
	// key. It is empty only for a Missing entry, where no record proves it.
	Harness model.Harness `json:"harness,omitempty"`
	// Instance is the instance id after normalisation, in index spelling.
	Instance string `json:"instance"`
	// Key is the exact settings key the record was stored under.
	Key string `json:"key,omitempty"`
	// Missing is true when no record exists for a requested instance. The
	// counts below are then absent, not zero.
	Missing bool `json:"missing,omitempty"`
	// Corrupt is true when a record exists but is not a valid record for this
	// harness and instance. It is reported instead of dropping the row.
	Corrupt bool `json:"corrupt,omitempty"`
	// Detail explains Missing or Corrupt in words.
	Detail string `json:"detail,omitempty"`
	// Record is the decoded record; nil when Missing or Corrupt.
	Record *scan.Diagnostics `json:"record,omitempty"`
}

DiagnosticsObservation is one harness instance's persisted collection diagnostics, read read-only: what the last scan of that instance attempted, what it reached, and why.

A record is keyed by harness *and* instance, and both are reported unchanged. Two harnesses can share an instance id (the built-in default), so collapsing them would put two different sources into one line. A zero count is only ever reported from a stored record: when nothing was stored, Missing is true and Record is nil, so "no data collected" can never be read as "zero usage".

func ReadDiagnostics

func ReadDiagnostics(ctx context.Context, ro *store.Store, instanceIDs []string) ([]DiagnosticsObservation, error)

ReadDiagnostics reads the stored collection diagnostics read-only.

With no instance filter it returns every stored record, ordered by harness then instance. With a filter it reports exactly the requested instances, in the order asked and deduplicated after normalisation: an instance with nothing stored is still reported, with Missing true, so an instance filter cannot hide a source that never collected anything. A stored record that does not decode is reported as Corrupt rather than failing the whole read, but a failure of the index itself is returned, because it says nothing about any single instance.

type Envelope

type Envelope struct {
	Totals    Totals
	Freshness Freshness
	// Groups holds the extra rankings requested through EnvelopeOptions, in the
	// order they were asked for. Empty unless options requested them.
	Groups []Group
}

Envelope is a consistent multi-field read of the index: totals, the cache ledger and the freshness signals all come from one read-only transaction, so a snapshot can never pair today's totals with yesterday's cache numbers.

It is additive to Service: existing callers keep using Totals/CacheTotals.

func ReadEnvelope

func ReadEnvelope(ctx context.Context, st *store.Store, f Filter, opts ...EnvelopeOptions) (Envelope, error)

ReadEnvelope reads one consistent envelope for f. The handle may be a read-only store (store.OpenReadOnly) — nothing here writes.

type EnvelopeOptions

type EnvelopeOptions struct {
	// Groups lists the dimensions to rank, in output order. An unknown
	// dimension is an error rather than a silently empty ranking.
	Groups []GroupDim
	// SessionLimit caps a GroupBySession ranking; 0 means every root session.
	SessionLimit int
}

EnvelopeOptions requests extra rankings. The zero value reads exactly the envelope Totals/Cache/Freshness, so existing callers are unaffected.

type Filter

type Filter struct {
	Range     Range
	Harnesses []model.Harness
	// Providers matches the resolved pricing provider name. It keeps the
	// historical pricing identity and never merges different endpoints.
	Providers []string
	// ProviderIDs matches the display identity keys returned by
	// ProviderGroups: "endpoint:v1:…" for a recognized endpoint and
	// "unresolved:v1:…" for one that cannot establish equivalence. It is
	// orthogonal to Providers: when both are set only events matching both are
	// returned. Matching is exact, so a malformed or unknown ID yields no
	// results rather than everything, and an unknown endpoint stays selectable
	// through the exact ID ProviderGroups returned for it.
	//
	// Endpoint identity is not stored in the daily_usage or cache_daily rollups,
	// so a non-empty ProviderIDs always reads facts from events instead of the
	// rollup. Session(ctx, h, id) and SessionCache(ctx, h, id) take no Filter and
	// therefore cannot express this filter.
	ProviderIDs []string
	// InstanceIDs matches the data source instance an event was ingested from.
	// It is optional and orthogonal to every other field: an empty slice means
	// "all instances", which is today's behaviour when only one exists, and a
	// set slice narrows every aggregate (totals, series, buckets, sessions,
	// cache and provider groups) to those instances. Old input that never
	// carried an instance is stored under store.DefaultInstanceID, so
	// Filter{InstanceIDs: []string{store.DefaultInstanceID}} selects exactly the
	// pre-0.4 history.
	InstanceIDs []string
	Models      []string
	Project     string
}

Filter narrows every query. Empty slices mean "all".

type Freshness

type Freshness struct {
	// EventsThrough is max(events.timestamp); nil when the index holds no events.
	EventsThrough *time.Time
	// SessionsThrough is max(sessions.updated_at); nil when no session has one.
	SessionsThrough *time.Time
	// RollupZone is the persisted daily_timezone setting; "" when never recorded.
	RollupZone string
	// LocalZone is the zone this process would write rollups in.
	LocalZone string
	// RollupsCurrent reports whether the persisted rollup zone matches LocalZone.
	// A never-recorded zone is reported as current: nothing to invalidate yet.
	RollupsCurrent bool
	// StatsTimezone is the persisted stats_timezone setting, empty when absent.
	StatsTimezone string
	// StatsTimezoneRecorded is false when no stats_timezone key exists, which is
	// different from a recorded empty value and must be reported as such.
	StatsTimezoneRecorded bool
}

Freshness is derived from read-only signals only. Every field is optional: an index that never recorded a timezone or holds no events reports zero values instead of inventing a default.

type Group

type Group struct {
	Dim      GroupDim     `json:"dim"`
	Buckets  []Bucket     `json:"buckets,omitempty"`
	Sessions []SessionRow `json:"sessions,omitempty"`
	Total    int          `json:"total,omitempty"`
}

Group is one extra ranking computed inside the envelope's transaction, so it always describes exactly the same events and filters as Totals.

Buckets is set for GroupByProject and Sessions for GroupBySession. Total is the number of sessions the ranking was cut from, which is how a truncated session list stays honest about what it left out.

type GroupDim

type GroupDim string

GroupDim names one extra ranking an Envelope can carry.

const (
	// GroupByProject ranks the filter's events by canonical project identity.
	// The key is the stored `project` dimension, which the store already
	// resolved to the repository root when the row was written; nothing here
	// re-derives or guesses a project.
	GroupByProject GroupDim = "project"
	// GroupBySession ranks the filter's root sessions by usage.
	GroupBySession GroupDim = "session"
	// GroupByBranch ranks the filter's events by repository and the branch the
	// log itself recorded for each request. The branch is metadata attached to a
	// request, never the working tree's current HEAD, so a checkout that moves
	// does not relabel history. The key is the canonical project joined with the
	// branch (see BranchKey): a bare branch name is not a group because two
	// repositories can share it. A request whose log stated no branch is kept as
	// an explicit unknown bucket.
	GroupByBranch GroupDim = "branch"
)

type InstanceService

type InstanceService interface {
	Service
	// SessionIn is Session for one explicit instance.
	SessionIn(ctx context.Context, h model.Harness, instance, id string) (SessionRow, []SessionRow, []AttributedEvent, error)
}

InstanceService is the instance-aware extension of Service. It is deliberately a separate interface so that existing Service implementations (the GUI demo, test doubles) keep compiling unchanged: callers type-assert when they need an explicit instance, and Service itself is untouched.

type ModelAlias

type ModelAlias struct {
	From     string `json:"from"`
	To       string `json:"to"`
	Provider string `json:"provider,omitempty"` // "" = any provider
}

ModelAlias maps a model name as the harness logged it (often a user-defined alias in a gateway or config, e.g. "claude-opus-5-5-high", "deepseek-v41") to the catalog model it really is. An alias affects pricing AND display: every query (ByModel, Breakdown, events' Model) reports To instead of From, so the two merge in rankings. The raw name stays in the index; removing the alias restores it.

type Point

type Point struct {
	Day     time.Time    `json:"t"`
	Tokens  model.Tokens `json:"tokens"`
	CostUSD float64      `json:"costUsd"`
}

Point is one bucket of a time series. Day is the local start of the day (Daily) or of the hour (Hourly).

type PriceRule

type PriceRule struct {
	Provider string `json:"provider,omitempty"`
	Model    string `json:"model,omitempty"`
	// Custom prices in USD per 1M tokens; nil = use the catalog's.
	Input      *float64  `json:"input,omitempty"`
	Output     *float64  `json:"output,omitempty"`
	CacheRead  *float64  `json:"cacheRead,omitempty"`
	CacheWrite *float64  `json:"cacheWrite,omitempty"`
	Source     string    `json:"source,omitempty"` // "user" (legacy rows are normalized)
	From       time.Time `json:"from,omitzero"`    // zero = always effective
}

PriceRule adjusts computed costs (docs/ARCHITECTURE.md#pricing). Rules never touch a cost the log itself reported.

  • Model != "": a custom per-1M-token price for that model (optionally only under Provider), used instead of the catalog price.
  • Provider != "" && Model == "": provider-wide rates, used as the last custom-price fallback for that provider's models.

Prices walk provider+model → model → provider → catalog, class by class, so a narrower rule overrides one rate while a wider one fills the rest. From is when the rule starts applying (zero = always). Several rules may share (provider, model); the one with the latest From ≤ the event's timestamp wins.

type ProviderGroup

type ProviderGroup struct {
	Bucket
	Identified bool             `json:"identified"`
	Members    []ProviderMember `json:"members"`
}

type ProviderMember

type ProviderMember struct {
	Harness  model.Harness `json:"harness"`
	Provider string        `json:"provider"`
}

ProviderMember retains original attribution for pricing/account drilldown. It is not a billing account identity; balances must never be summed here.

type ProviderModel

type ProviderModel struct {
	Provider string             `json:"provider"`
	Model    string             `json:"model"`
	Attrib   model.AttribSource `json:"attrib"`
	Tokens   model.Tokens       `json:"tokens"`
	CostUSD  float64            `json:"costUsd"`
	Requests int64              `json:"requests"`
	Unpriced int64              `json:"unpriced"` // see Totals.Unpriced
}

ProviderModel is a session's usage split by provider × model.

type Range

type Range struct {
	From, To time.Time
}

Range is a half-open local-time interval [From, To). Zero values mean unbounded.

type Service

type Service interface {
	Totals(ctx context.Context, f Filter) (Totals, error)
	Daily(ctx context.Context, f Filter) ([]Point, error)  // one point per local day in range, zero-filled
	Hourly(ctx context.Context, f Filter) ([]Point, error) // one point per local hour in range, zero-filled
	ByProvider(ctx context.Context, f Filter) ([]Bucket, error)
	// ProviderGroups groups display identities without changing pricing labels.
	ProviderGroups(ctx context.Context, f Filter) ([]ProviderGroup, error)
	ByModel(ctx context.Context, f Filter) ([]Bucket, error)
	ByProject(ctx context.Context, f Filter) ([]Bucket, error)
	ByHarness(ctx context.Context, f Filter) ([]Bucket, error)
	// Usage is the range grouped by local day, tool, model and provider.
	Usage(ctx context.Context, f Filter) ([]UsageRow, error)
	// HourlyUsage is Usage bucketed by local hour: each row's Day is the start
	// of a local clock hour (time.Local), grouped by harness, model and provider.
	HourlyUsage(ctx context.Context, f Filter) ([]UsageRow, error)
	Sessions(ctx context.Context, f Filter, sort string, limit, offset int) (rows []SessionRow, total int, err error)
	// Session returns the session, its children, and its own events (not children's), time-ordered.
	Session(ctx context.Context, h model.Harness, id string) (SessionRow, []SessionRow, []AttributedEvent, error)
	// Subscribe notifies (throttled to ≤1/s) whenever new data is committed.
	Subscribe() (<-chan struct{}, func())
}

Service is the read API. Sessions lists only top-level sessions (ParentID == "") whose events intersect the filter.

func NewService

func NewService(st *store.Store) Service

type SessionRow

type SessionRow struct {
	model.SessionMeta
	// InstanceID is the data source instance this session was read from. It is
	// additive provenance: two instances can hold the same harness and session
	// id as two independent sessions, and this field tells them apart. Rows
	// written before 0.4 report store.DefaultInstanceID.
	InstanceID string          `json:"instanceId"`
	Tokens     model.Tokens    `json:"tokens"`
	CostUSD    float64         `json:"costUsd"`
	Requests   int64           `json:"requests"`
	Unpriced   int64           `json:"unpriced"` // see Totals.Unpriced
	Children   int             `json:"children"`
	Breakdown  []ProviderModel `json:"breakdown"` // sorted by Tokens.Total() desc
}

SessionRow is a session with its aggregates. For a parent session, Tokens, CostUSD and Requests INCLUDE its children (subagents); Breakdown too.

type Settings

type Settings interface {
	PriceRules(ctx context.Context) ([]PriceRule, error)
	// SetPriceRules replaces all rules.
	SetPriceRules(ctx context.Context, rules []PriceRule) error
	ModelAliases(ctx context.Context) ([]ModelAlias, error)
	// SetModelAliases replaces all aliases; reprices and notifies.
	SetModelAliases(ctx context.Context, aliases []ModelAlias) error
	// UnpricedModels lists models lacking a price, most tokens first, each with
	// fuzzy-matched catalog suggestions (normalize, strip -high/-preview/-expires…
	// suffixes, version digits like v41 ≈ v4.1).
	UnpricedModels(ctx context.Context) ([]UnpricedModel, error)
	// SearchCatalog returns catalog model ids matching q (substring/fuzzy), ≤limit.
	SearchCatalog(ctx context.Context, q string, limit int) ([]string, error)
	// Providers lists every resolved provider seen in the index, for pickers.
	Providers(ctx context.Context) ([]string, error)
}

Settings is the write side used by the Settings page and the CLI. Every mutation that changes costs reprices the index and notifies subscribers.

func NewSettings

func NewSettings(st *store.Store, p *pricing.Pricer) Settings

type Totals

type Totals struct {
	Tokens   model.Tokens `json:"tokens"`
	CostUSD  float64      `json:"costUsd"`
	Requests int64        `json:"requests"`
	Sessions int64        `json:"sessions"`
	// Unpriced counts requests with neither a log cost nor a known price;
	// CostUSD excludes them. The UI shows "—" when Unpriced == Requests.
	Unpriced int64 `json:"unpriced"`
	// CacheHit = CacheRead / (Input + CacheRead + CacheWrite); 0 when denominator is 0.
	CacheHit float64 `json:"cacheHit"`
}

Totals is the aggregate over a filter.

type UnpricedModel

type UnpricedModel struct {
	Model       string   `json:"model"`
	Provider    string   `json:"provider"`
	Requests    int64    `json:"requests"`
	Tokens      int64    `json:"tokens"`
	Suggestions []string `json:"suggestions"` // closest catalog ids, best first (≤5)
}

UnpricedModel is a logged model name with no price, for the "fix it" hint.

type UsageRow

type UsageRow struct {
	Day      time.Time // local midnight (Usage) or local clock-hour start (HourlyUsage)
	Harness  model.Harness
	Model    string // after model aliases
	Provider string // resolved provider
	Tokens   model.Tokens
	CostUSD  float64
	Requests int64
	Unpriced int64
}

UsageRow is one local day's usage of one tool, model and provider. HourlyUsage reuses it for one local clock hour, with Day set to the start of that hour.

Jump to

Keyboard shortcuts

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