usage

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 17 Imported by: ? 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

This file (issue #324) rebuilds an auditable savings breakdown purely from counters the proxy actually recorded: the response governor's GovernorStats (#319-#321), the schema/discovery counters (#324) and telemetry's plain counters (#317), all read from this package's JSONL store (Store.Load). Every number is either measured (an exact count or a size the pipeline computed from a real payload) or explicitly labeled estimated, and the estimator is always named: the whole proxy, the response governor and the benchmark harness all use the same chars/4 heuristic (reporter.DefaultCharsPerToken), so runtime accounting and harness numbers are directly comparable. Nothing here invents or extrapolates a number that was not measured.

Package usage is the auditable savings record store (issue #324): an append-only, offline, per-day JSONL log of the real counters the proxy already records (pkg/metrics.Snapshot: the response governor's GovernorStats, the telemetry counters, and the cost tracker's breakdown). It never stores a payload, argument or secret — only numbers, server/tool names and timestamps — so `leanproxy-mcp report` can rebuild an auditable savings report without a live process and without re-estimating anything that was not actually measured.

This file turns the usage store into the today / week-to-date windows the dashboard and /metrics serve (metrics.UsageSummary). Each Record is a session's cumulative total, so a window is, per session, the session's latest record minus its last record before the window started: a proxy that has been running since yesterday only contributes today what it recorded today. The totals are then built with BuildSavingsReport, so they are exactly `report`'s numbers for the same deltas.

Index

Constants

View Source
const DefaultRetentionDays = 90

DefaultRetentionDays is how long usage files are kept before Prune removes them, matching the acceptance criteria's default of 90 days.

Variables

This section is empty.

Functions

func DayStart

func DayStart(t time.Time) time.Time

DayStart returns 00:00 UTC of t's day: the start of the "today" window, and the same day boundary the store's per-day files use.

func Summarize

func Summarize(records []Record, now time.Time) metrics.UsageSummary

Summarize computes the today / week-to-date windows at now from records (in any order). Records before the week's start are only used as baselines.

func WeekStart

func WeekStart(t time.Time) time.Time

WeekStart returns 00:00 UTC of the Monday of t's ISO week: the start of the week-to-date window.

Types

type Live

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

Live is an incrementally updated reader of a Store for Summary: it reads only the lines appended since its previous call (every front end appends a record every 5 seconds, so re-reading a week of files on each dashboard refresh would not scale) and decodes in full only the few records per session a window needs. It reads the files from the day before the week's start onwards, so a session running across the week boundary has its baseline; on a new day it starts over. Safe for concurrent use.

func NewLive

func NewLive(store *Store) *Live

NewLive returns a Live reader over store.

func (*Live) Summary

func (l *Live) Summary() (metrics.UsageSummary, error)

Summary reads what was appended to the store since the previous call and returns the windows at the current time.

type MechanismSavings

type MechanismSavings struct {
	Mechanism string `json:"mechanism"`
	// Measured is true when every field below comes directly from a
	// counter the pipeline incremented from a real payload; it is false
	// only for derived rows that combine measured counters with a stated
	// assumption (currently none do — kept for forward compatibility with
	// e.g. a future price-derived row).
	Measured bool `json:"measured"`
	// IsCost marks a row that is a token cost, not a saving (discovery):
	// it is never added into TotalSavedTokens.
	IsCost bool `json:"is_cost,omitempty"`
	// Estimator names the token-counting heuristic (empty when the row
	// carries no *_tokens field, e.g. a pure call count).
	Estimator       string `json:"estimator,omitempty"`
	OriginalTokens  int64  `json:"original_tokens"`
	ResultingTokens int64  `json:"resulting_tokens"`
	SavedTokens     int64  `json:"saved_tokens"`
	Calls           int64  `json:"calls"`
	Notes           string `json:"notes,omitempty"`
}

MechanismSavings is one row of the report's breakdown by mechanism: a single savings (or cost) category, always labeled measured or estimated.

func (MechanismSavings) SavedPercent

func (m MechanismSavings) SavedPercent() float64

SavedPercent returns the row's saving as a percentage of OriginalTokens (0 when OriginalTokens is 0).

type Record

type Record struct {
	Timestamp time.Time `json:"timestamp"`
	SessionID string    `json:"session_id"`
	PID       int       `json:"pid"`
	Estimator string    `json:"estimator"`

	Snapshot metrics.MetricsSnapshot `json:"snapshot"`
}

Record is one point-in-time snapshot of the real counters the proxy has recorded, appended to the usage store. Estimator names the token-counting heuristic every *_tokens field in Snapshot was computed with (reporter.DefaultCharsPerToken, "chars/4"): the same primitive the runtime cost tracker, the response governor and the benchmark harness all use, so runtime accounting and harness numbers are directly comparable.

func NewRecord

func NewRecord(sessionID string) Record

NewRecord builds a Record from the process-global counters (metrics.Snapshot) at the moment it is called. sessionID identifies the front-end run (e.g. the status file's PID-derived id); it is never a payload or a secret.

type SavingsReport

type SavingsReport struct {
	GeneratedAt time.Time `json:"generated_at"`
	// Since is the --since cutoff used to select usage records (zero: no
	// cutoff, every retained record).
	Since time.Time `json:"since,omitempty"`
	// SessionCount is the number of distinct front-end processes
	// (session ids) whose latest snapshot contributed to this report.
	SessionCount int `json:"session_count"`
	// Estimator names the single token-counting heuristic used
	// everywhere in this report (see DefaultCharsPerToken): the runtime
	// pipeline, the response governor and tests/bench all use it, so this
	// report's numbers and the harness's are directly comparable.
	Estimator string `json:"estimator"`

	Mechanisms []MechanismSavings `json:"mechanisms"`

	TotalOriginalTokens int64   `json:"total_original_tokens"`
	TotalSavedTokens    int64   `json:"total_saved_tokens"`
	TotalSavedPercent   float64 `json:"total_saved_percent"`

	// ExtraTurnsEstimate is the number of discovery calls (search_tools,
	// list_tools, list_servers): each implies roughly one extra LLM turn.
	// The call count itself is measured; converting it into a number of
	// "extra turns" is the estimate, and it is never folded into a token
	// number (per the issue: "do not convert it into tokens silently").
	ExtraTurnsEstimate int64 `json:"extra_turns_estimate"`

	TopToolsByResponseSize []ToolSize `json:"top_tools_by_response_size,omitempty"`
	// TopServersByResponseSize is the same breakdown grouped by upstream
	// server (the part of the tool identity before the first '.'), for
	// --by server.
	TopServersByResponseSize []ToolSize `json:"top_servers_by_response_size,omitempty"`

	// PricePerMTok and EstimatedCostSaved are only present when --price-per-mtok
	// was given: there is no built-in price table (see the issue), so this
	// is always the caller's own number, clearly derived (never presented
	// as a "measured" cost).
	PricePerMTok       *float64 `json:"price_per_mtok,omitempty"`
	EstimatedCostSaved *float64 `json:"estimated_cost_saved,omitempty"`

	// Methodology is a short, human-readable statement of how the numbers
	// above were produced, repeated in every output format so a report
	// read outside its original context is still self-explanatory. See
	// docs/savings-report.md for the full methodology.
	Methodology string `json:"methodology"`

	// PerSession is one row per contributing session (--by session), each
	// a total across every mechanism, from that session's own latest
	// snapshot only.
	PerSession []SessionSummary `json:"per_session,omitempty"`
}

SavingsReport is the full auditable savings report (issue #324).

func BuildSavingsReport

func BuildSavingsReport(records []Record, since time.Time, pricePerMTok *float64) SavingsReport

BuildSavingsReport aggregates records (already filtered to --since by the caller) into a SavingsReport. Records are grouped by SessionID and only the latest (by Timestamp) record of each session is used, since each Record.Snapshot is a cumulative total for its own process -- summing every snapshot of the same session would double count.

func (SavingsReport) CSV

func (r SavingsReport) CSV(w io.Writer) error

CSV renders the mechanism breakdown as CSV (one row per mechanism, plus a trailing TOTAL row), for finance/spreadsheet consumption.

func (SavingsReport) JSON

func (r SavingsReport) JSON() ([]byte, error)

JSON renders the report as indented JSON: the documented, stable schema for --export json (see docs/savings-report.md).

func (SavingsReport) Markdown

func (r SavingsReport) Markdown(by string) string

Markdown renders the report as a Markdown document. by selects the extra breakdown table, as Text does.

func (SavingsReport) Text

func (r SavingsReport) Text(by string) string

Text renders the report as a human-readable, fixed-width summary. by selects the extra breakdown table ("tool" (default), "server" or "session"); an unknown value falls back to "tool".

type SessionSummary

type SessionSummary struct {
	SessionID           string    `json:"session_id"`
	Timestamp           time.Time `json:"timestamp"`
	TotalOriginalTokens int64     `json:"total_original_tokens"`
	TotalSavedTokens    int64     `json:"total_saved_tokens"`
}

SessionSummary is one contributing session's totals (--by session).

type Store

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

Store is the JSONL usage log: one file per UTC day under its directory, mode 0600, append-only.

func NewStore

func NewStore() (*Store, error)

NewStore returns a Store rooted at ~/.leanproxy/usage (creating it if needed), matching HOME the same way pkg/statusfile does: os.UserHomeDir first, falling back to the OS user database, so a sandboxed HOME (tests, the benchmark harness) never touches the real one.

func NewStoreWithDir

func NewStoreWithDir(dir string) (*Store, error)

NewStoreWithDir returns a Store rooted at dir (creating it if needed). Tests and --usage-dir use this to avoid touching the real home directory.

func (*Store) Append

func (s *Store) Append(rec Record) error

Append writes one record to the day's file (UTC), creating it at mode 0600 if needed. Concurrent-safe across processes: each write is a single O_APPEND write of one JSON line, which is atomic for lines under the platform pipe buffer size on POSIX systems.

func (*Store) Dir

func (s *Store) Dir() string

Dir returns the store's root directory.

func (*Store) Load

func (s *Store) Load(since time.Time) ([]Record, error)

Load returns every record with Timestamp >= since (UTC), sorted oldest first. A zero since loads every retained record. Malformed lines are skipped rather than failing the whole load (one truncated write, e.g. from a crash mid-append, should not lose the rest of the day).

func (*Store) Prune

func (s *Store) Prune(retention time.Duration) (int, error)

Prune removes usage files whose whole day is older than retention (default DefaultRetentionDays), relative to now (UTC). It returns the number of files removed.

type ToolSize

type ToolSize struct {
	Tool           string `json:"tool"`
	OriginalTokens int64  `json:"original_tokens"`
	Calls          int64  `json:"calls"`
}

ToolSize is one row of "top tools by response size" — a hint for writing projection rules (#320).

Jump to

Keyboard shortcuts

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