metrics

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 16 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 metrics provides an asynchronous, SQLite-backed system for recording and querying operational measurements across LLM calls, tool executions, and file changes, and for aggregating them into per-session and cross-session usage summaries.

Core Types

A Record is one observed occurrence with a Kind (llm_call, tool_call, or file_change), a Status, descriptive Attr dimensions, and numeric Measurement values. A Recorder persists records; the Store is the SQLite-backed implementation.

A Entry is a Record after attribution: it carries the identity, timestamp, and scope fields (scope.Scope) that the recorder fills in. Callers never construct an Entry directly; they call NewEntry or use the convenience helpers RecordLLMCall, RecordToolCall, and RecordFileChange.

Asynchronous Batched Writes

Store (created via NewStore) queues records in a bounded in-memory channel and writes them in batched transactions on a background goroutine. Store.Record never blocks: when the queue is full the record is dropped with a warning. Store.Flush blocks until every queued record is written, and Store.Close flushes and stops the writer.

Querying & Aggregation

[Query] describes a generic aggregation over records and measurements, supporting AggSum, AggMin, and AggMax over named Metric values, grouping by Dimension columns or attribute keys, and optional time [Bucket]ing. Store.Query (or the standalone RunQuery) executes a query and returns a [Result] of [Row]s.

Usage Accumulation

Usage accumulates the records of one session into an github.com/masterkeysrd/tasksmith/api.SessionUsage, tracking LLM token counts, costs, latency, tool-call statistics, code-change totals, and prompt-cache behavior. Store.SessionUsage loads and accumulates all records for a session and its children.

Store.Summary aggregates LLM, tool, and code-change usage across sessions for a workspace or globally, with grouping by model, provider, agent, purpose, cost tier, or day, plus top-session rankings and period-over-period comparison.

Live Totals

Live decorates a Store with running per-session totals. After each record it updates the affected sessions' Usage accumulators and calls a publish callback with the updated github.com/masterkeysrd/tasksmith/api.SessionUsage, enabling real-time usage display without polling the database.

Index

Constants

View Source
const (
	AttrProvider   = "provider"
	AttrModel      = "model"
	AttrPurpose    = "purpose"
	AttrCostTier   = "cost_tier"
	AttrPriced     = "priced"
	AttrBilling    = "billing"
	AttrErrorKind  = "error_kind"
	AttrTool       = "tool"
	AttrToolCallID = "tool_call_id"
	AttrPath       = "path"
	AttrSource     = "source"
	AttrChange     = "change"
	AttrRevert     = "revert"

	AttrOutcome      = "outcome"
	AttrRequestClass = "request_class"
	AttrDecision     = "decision_scope"
	AttrRubricDigest = "rubric_digest"
)

Attribute keys written by TaskSmith.

View Source
const (
	BillingToken = "token"
	BillingQuota = "quota"
)

Billing modes recorded on llm_call records. A quota-billed call has no price by design rather than a missing one, which is why it is recorded separately from an unpriced per-token call.

View Source
const (
	ReviewOutcomeApproved        = "approved"
	ReviewOutcomeDeferred        = "deferred"
	ReviewOutcomeBelowThreshold  = "below_threshold"
	ReviewOutcomeNoModel         = "no_model"
	ReviewOutcomeOversize        = "oversize"
	ReviewOutcomeInvalidManifest = "invalid_manifest"
	ReviewOutcomeTimeout         = "timeout"
	ReviewOutcomeCanceled        = "canceled"
	ReviewOutcomeError           = "error"
)

Review outcomes recorded on permission_review records. Everything other than ReviewOutcomeApproved fell back to the human permission flow.

View Source
const AttrPrefix = "attr."

AttrPrefix prefixes attr keys used as a Dimension.

View Source
const BaseTierKey = "base"

BaseTierKey is the group key used for calls billed at base pricing.

View Source
const MigrationScope = "metrics"

MigrationScope is the sqlite.Migrate scope of the metrics tables.

View Source
const TimeLayout = "2006-01-02T15:04:05.000000000Z"

TimeLayout is the fixed-width UTC layout used for created_at so that text ordering is chronological.

Variables

View Source
var ErrClosed = errors.New("metrics: store is closed")

ErrClosed is returned by Store.Record after Store.Close.

View Source
var ErrInvalidQuery = errors.New("metrics: invalid query")

ErrInvalidQuery is returned for malformed queries.

Functions

func BuildSQL

func BuildSQL(q api.MetricsQuery) (string, []any, error)

BuildSQL returns the parameterized SQL for q and the group dimensions in select order. It is exported for testing.

func RecordFileChange

func RecordFileChange(ctx context.Context, r Recorder, c api.FileChange) error

RecordFileChange records a file_change. A nil recorder disables recording.

func RecordLLMCall

func RecordLLMCall(ctx context.Context, r Recorder, c LLMCall) error

RecordLLMCall records an llm_call. A nil recorder disables recording.

func RecordPermissionReview

func RecordPermissionReview(ctx context.Context, r Recorder, c PermissionReview) error

RecordPermissionReview records a permission_review outcome. A nil recorder disables recording.

func RecordToolCall

func RecordToolCall(ctx context.Context, r Recorder, c ToolCall) error

RecordToolCall records a tool_call. A nil recorder disables recording.

func RunQuery

func RunQuery(ctx context.Context, db *sql.DB, q api.MetricsQuery) (api.MetricsResult, error)

RunQuery runs q against db.

Types

type AggFunc

type AggFunc string

AggFunc is an aggregate function over a metric.

const (
	AggSum   AggFunc = "sum"
	AggMin   AggFunc = "min"
	AggMax   AggFunc = "max"
	AggCount AggFunc = "count"
)

Aggregate functions. COUNT is per-metric: it counts only records that recorded the metric, so sum/COUNT is the mean over the calls that measured it rather than over all calls.

type Attr

type Attr struct {
	Key   string
	Value string
}

Attr is a descriptive string dimension of a record.

type Bucket

type Bucket string

Bucket is a time bucket size.

const (
	BucketNone  Bucket = ""
	BucketHour  Bucket = "hour"
	BucketDay   Bucket = "day"
	BucketWeek  Bucket = "week"
	BucketMonth Bucket = "month"
)

Time buckets.

type Cost

type Cost struct{ Input, Output, CacheRead, CacheWrite, Reasoning, Total int64 }

Cost is the nano-USD cost breakdown of an LLM call.

type Dimension

type Dimension string

Dimension is a column name (workspace_root, session_id, parent_session_id, turn_id, message_id, agent, status, kind) or an attr key prefixed with "attr." (e.g. "attr.model").

type Entry

type Entry struct {
	ID              string
	CreatedAt       time.Time
	WorkspaceRoot   string
	SessionID       string
	ParentSessionID string
	TurnID          string
	MessageID       string
	Agent           string
	Record
}

Entry is a Record after attribution: it carries the identity, timestamp and scope fields that the Recorder fills in. Callers never construct it.

func NewEntry

func NewEntry(ctx context.Context, r Record) Entry

NewEntry attributes r using the scope.Scope in ctx.

type Kind

type Kind string

Kind identifies what a record describes (free-form).

const (
	KindLLMCall    Kind = "llm_call"
	KindToolCall   Kind = "tool_call"
	KindFileChange Kind = "file_change"
	// KindPermissionReview records one auto-mode permission-reviewer outcome
	// (including deferrals), separate from the llm_call inference record.
	KindPermissionReview Kind = "permission_review"
)

Kinds written by TaskSmith.

type LLMCall

type LLMCall struct {
	Provider  string
	Model     string
	Purpose   Purpose
	Status    Status
	ErrorKind string

	Tokens   api.UsageTokens
	Cost     Cost   // nano-USD
	CostTier string // empty = base pricing
	Priced   bool
	// Billing is [BillingQuota] for subscription-billed calls and
	// [BillingToken] (or empty) otherwise.
	Billing string

	Duration   time.Duration
	TTFT       time.Duration
	Processing time.Duration
	Generation time.Duration
}

LLMCall describes one LLM request for RecordLLMCall.

type Live

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

Live decorates a Store with running per-session totals. After each record it calls publish with the updated usage of the affected sessions.

func NewLive

func NewLive(store *Store, publish func(sessionID string, usage api.SessionUsage)) *Live

NewLive wraps store. publish is called outside of any lock.

func (*Live) Record

func (l *Live) Record(ctx context.Context, r Record) error

Record attributes and stores r, then updates and publishes live totals.

func (*Live) SessionUsage

func (l *Live) SessionUsage(ctx context.Context, sessionID string) (api.SessionUsage, error)

SessionUsage returns the live usage of sessionID, loading it on first access.

func (*Live) Store

func (l *Live) Store() *Store

Store returns the wrapped store.

func (*Live) TurnUsage

func (l *Live) TurnUsage(ctx context.Context, turnIDs ...string) (api.UsageGroup, error)

TurnUsage returns the LLM usage recorded for the given turns.

type Measurement

type Measurement struct {
	Metric Metric
	Value  int64
}

Measurement is a single integer value of a metric.

type Metric

type Metric string

Metric is the name of a measurement (free-form).

const (
	TokensInput      Metric = "tokens.input"
	TokensOutput     Metric = "tokens.output"
	TokensCacheRead  Metric = "tokens.cache_read"
	TokensCacheWrite Metric = "tokens.cache_write"
	TokensReasoning  Metric = "tokens.reasoning"

	CostInput      Metric = "cost.input"
	CostOutput     Metric = "cost.output"
	CostCacheRead  Metric = "cost.cache_read"
	CostCacheWrite Metric = "cost.cache_write"
	CostReasoning  Metric = "cost.reasoning"
	CostTotal      Metric = "cost.total"

	LatencyDuration   Metric = "latency.duration_ms"
	LatencyTTFT       Metric = "latency.ttft_ms"
	LatencyProcessing Metric = "latency.processing_ms"
	LatencyGeneration Metric = "latency.generation_ms"

	LinesAdded   Metric = "lines.added"
	LinesRemoved Metric = "lines.removed"
	FilesChanged Metric = "files.changed"
)

Metric names written by TaskSmith.

type PermissionReview

type PermissionReview struct {
	Outcome      string // one of the ReviewOutcome* constants
	RequestClass string // bypass_sandbox | net | unsafe | outside | delete
	Model        string // "<provider>/<model>" when inference ran
	Decision     string // decision manifest scope (system/user/workspace/local)
	RubricDigest string // short rubric fingerprint
	Duration     time.Duration
}

PermissionReview describes one auto-mode permission-reviewer outcome for RecordPermissionReview. Only bounded classification attributes are recorded; raw commands, paths, summaries, and diffs never are.

type Purpose

type Purpose string

Purpose identifies why an LLM call was made.

const (
	PurposeChat       Purpose = "chat"
	PurposeCompaction Purpose = "compaction"
	PurposeTitle      Purpose = "title"
	// PurposePermissionReview labels inference performed by the auto-mode
	// permission reviewer rather than the conversational agent.
	PurposePermissionReview Purpose = "permission_review"
)

Purpose values.

type Record

type Record struct {
	Kind         Kind
	Status       Status
	Attrs        []Attr
	Measurements []Measurement
}

Record is one observed occurrence and its measurements.

func (Record) Attr

func (r Record) Attr(key string) string

Attr returns the value of the attribute with key, or "".

func (Record) Value

func (r Record) Value(m Metric) int64

Value returns the value of metric m on the record, or zero.

type Recorder

type Recorder interface {
	Record(ctx context.Context, r Record) error
}

Recorder persists metric records. Implementations must not block the caller.

type Service

type Service interface {
	Recorder
	// TurnUsage returns the LLM usage recorded for the turns started by the
	// given user message IDs, after all queued records are written.
	TurnUsage(ctx context.Context, turnIDs ...string) (api.UsageGroup, error)
}

Service is a Recorder that can also report the usage of a single turn.

type Status

type Status string

Status is the outcome of the recorded occurrence.

const (
	StatusOK       Status = "ok"
	StatusError    Status = "error"
	StatusCanceled Status = "canceled"
	StatusDenied   Status = "denied" // tool calls rejected by permissions
)

Status values.

type Store

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

Store is the asynchronous SQLite Recorder. Records are queued in memory and written in batched transactions by a background goroutine.

func NewStore

func NewStore(ctx context.Context, db *sql.DB, logger log.Interface) (*Store, error)

NewStore migrates the metrics schema on db and starts the background writer. The caller keeps ownership of db and must call Store.Close before closing it.

func (*Store) Close

func (s *Store) Close() error

Close flushes the queue and stops the writer. It does not close the database.

func (*Store) DB

func (s *Store) DB() *sql.DB

DB returns the underlying database handle.

func (*Store) Flush

func (s *Store) Flush(ctx context.Context) error

Flush blocks until every record queued before the call is written.

func (*Store) LoadEntries

func (s *Store) LoadEntries(ctx context.Context, sessionID string) ([]Entry, error)

LoadEntries reads every record of sessionID and of its child sessions.

func (*Store) Query

Query runs q against the database.

func (*Store) Record

func (s *Store) Record(ctx context.Context, r Record) error

Record attributes r from the scope in ctx and queues it for writing. It never blocks: when the queue is full the record is dropped with a warning.

func (*Store) SessionUsage

func (s *Store) SessionUsage(ctx context.Context, sessionID string) (api.SessionUsage, error)

SessionUsage computes the persisted usage of sessionID.

func (*Store) Summary

func (s *Store) Summary(ctx context.Context, workspaceRoot string, req api.UsageRequest) (api.UsageSummary, error)

Summary aggregates LLM, tool and code-change usage across sessions.

func (*Store) TurnUsage

func (s *Store) TurnUsage(ctx context.Context, turnIDs ...string) (api.UsageGroup, error)

TurnUsage returns the LLM usage recorded for the given turns.

func (*Store) Write

func (s *Store) Write(e Entry) error

Write queues an already attributed entry.

type ToolCall

type ToolCall struct {
	Tool       string
	ToolCallID string
	Status     Status
	ErrorKind  string
	Duration   time.Duration
}

ToolCall describes one tool execution for RecordToolCall.

type Usage

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

Usage accumulates the metrics of one session into an api.SessionUsage.

func NewUsage

func NewUsage(sessionID string) *Usage

NewUsage returns an empty accumulator for sessionID.

func (*Usage) Apply

func (u *Usage) Apply(e Entry)

Apply adds one record to the accumulator. Kinds it does not know are ignored.

func (*Usage) Snapshot

func (u *Usage) Snapshot() api.SessionUsage

Snapshot returns a copy of the accumulated usage with groups sorted by key.

Jump to

Keyboard shortcuts

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