meterd

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 26 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

Package meterd implements a reference token-metering price server for aperture's dynamicprice.metered mode. It sells prepaid bundles of LLM tokens over L402: a client pays one Lightning invoice for a bundle of tokens, draws it down across requests, and receives a fresh 402 challenge once the bundle is spent.

Index

Constants

View Source
const (
	// DefaultListenAddr is the address the daemon serves its gRPC
	// interface on when no other address is configured.
	DefaultListenAddr = "127.0.0.1:10010"

	// DefaultBundleTokens is the number of LLM tokens sold per bundle
	// when no other bundle size is configured.
	DefaultBundleTokens = 1_000_000

	// DefaultEstimatedTokens is the per-request token estimate reserved on
	// authorization when the request body carries no max_tokens hint. It
	// bounds how far concurrent requests on a near-empty bundle can
	// overdraw.
	DefaultEstimatedTokens = 4_096

	// DefaultPromptBytesPerToken is the body bytes counted as one prompt
	// token. One is an upper bound for text under byte-level BPE, but not
	// for inputs the upstream expands, such as images.
	DefaultPromptBytesPerToken = 1

	// DefaultMaxUnauthorizedBundles caps the number of never-authorized
	// (un-paid) bundles retained at once, bounding the state an
	// unauthenticated challenge-mint spammer can accumulate.
	DefaultMaxUnauthorizedBundles = 10_000

	// DefaultUnauthorizedBundleTTL is how long a never-authorized bundle is
	// retained before the janitor reaps it. Un-paid mint spam is reaped far
	// sooner than a paid, drawn-down bundle.
	DefaultUnauthorizedBundleTTL = 10 * time.Minute

	// DefaultReservationTTL is how long a reservation is held before it is
	// presumed leaked and dropped.
	DefaultReservationTTL = 30 * time.Minute

	// MinReservationTTL is the shortest reservation TTL accepted, to catch
	// a value given in the wrong unit.
	MinReservationTTL = time.Minute

	// MaxUsageTailBytes is the upper bound accepted for the configured
	// usage tail size, guarding against an unbounded per-request capture.
	MaxUsageTailBytes = 1 << 20
)
View Source
const Subsystem = "METR"

Subsystem is the logging tag of the meterd daemon.

Variables

This section is empty.

Functions

func AdmitReservation added in v0.6.1

func AdmitReservation(remaining, reserved, estimate int64) bool

AdmitReservation reports whether a request reserving estimate tokens may proceed. It is admitted when the balance left after in-flight reservations covers it, or when nothing else is in flight and any balance is left, so a remainder is not stranded. Stores apply it under their own lock.

The estimate only bounds a request's cost when it has a max_tokens the price server could read.

func Main

func Main()

Main is the true entry point of the meterd daemon. It is factored out so that a thin main package can call it.

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger overrides the package level logger, for example to silence the daemon from tests.

Types

type Authorization added in v0.6.1

type Authorization struct {
	// Remaining is the bundle's unspent balance at decision time.
	Remaining int64

	// Available is Remaining minus other in-flight reservations.
	Available int64

	// Admitted is whether the request may proceed, and so whether its
	// estimate was reserved.
	Admitted bool
}

Authorization is the outcome of a Store.Authorize call.

type Bundle

type Bundle struct {
	// Model is the configured model the bundle was booked for.
	Model string `json:"model"`

	// PriceSats is the price in satoshis the bundle was quoted at.
	PriceSats int64 `json:"price_sats"`

	// RemainingTokens is the number of unspent LLM tokens.
	RemainingTokens int64 `json:"remaining_tokens"`

	// CreatedAt is when the bundle was booked.
	CreatedAt time.Time `json:"created_at"`

	// Authorized is whether the bundle was ever used by an authorized
	// request. Bundles that are never authorized are expired by the
	// janitor, since their challenge was most likely never paid.
	Authorized bool `json:"authorized"`

	// Reserved is the number of tokens currently reserved by in-flight
	// requests that have been authorized but not yet reported. It is an
	// estimate that bounds concurrent overdraw, and is not persisted since
	// it only tracks live requests.
	Reserved int64 `json:"-"`
	// contains filtered or unexported fields
}

bundle tracks the prepaid token balance purchased with a single L402 payment.

type Config

type Config struct {
	// ConfigFile points to an optional YAML config file.
	ConfigFile string `yaml:"-" long:"config" description:"Path to a YAML config file"`

	// ListenAddr is the address the gRPC server listens on.
	ListenAddr string `yaml:"listenaddr" long:"listenaddr" description:"Address to serve the prices gRPC interface on"`

	// BundleTokens is the number of LLM tokens sold per bundle. One L402
	// payment purchases one bundle.
	BundleTokens int64 `yaml:"bundletokens" long:"bundletokens" description:"Number of LLM tokens sold per bundle"`

	// DefaultModel is the model used to price requests whose model is
	// missing or not present in the models map. When empty, such requests
	// cannot be priced.
	DefaultModel string `yaml:"defaultmodel" long:"defaultmodel" description:"Model to price requests with an unknown or missing model as"`

	// EstimatedTokens is the per-request token estimate reserved on
	// authorization when the request carries no max_tokens hint. It bounds
	// concurrent overdraw on a near-empty bundle.
	EstimatedTokens int64 `` /* 141-byte string literal not displayed */

	// PromptBytesPerToken is the body bytes counted as one prompt token.
	// Raising it trades overdraw protection for concurrency. Zero uses the
	// default.
	PromptBytesPerToken int64 `` /* 142-byte string literal not displayed */

	// MaxUnauthorizedBundles caps the number of never-authorized (un-paid)
	// bundles retained at once. When zero, the default is used.
	MaxUnauthorizedBundles int `` /* 155-byte string literal not displayed */

	// UnauthorizedBundleTTL is how long a never-authorized bundle is
	// retained before the janitor reaps it. When zero, the default is
	// used.
	UnauthorizedBundleTTL time.Duration `` /* 138-byte string literal not displayed */

	// ReservationTTL is how long a reservation is held before it is
	// presumed leaked and dropped. Zero uses the default, negative
	// disables expiry. Only the built-in JSON store uses it; a custom store
	// reports its own expiry through ReservationExpirer.
	ReservationTTL time.Duration `` /* 148-byte string literal not displayed */

	// Models maps a model identifier to its per-token rates.
	Models map[string]*ModelConfig `yaml:"models"`

	// TLSCertPath is the path to the TLS certificate to serve with. The
	// server speaks plaintext when unset, matching aperture's
	// dynamicprice.insecure mode.
	TLSCertPath string `yaml:"tlscertpath" long:"tlscertpath" description:"Path to the TLS certificate to serve with, plaintext when unset"`

	// TLSKeyPath is the path to the TLS key belonging to the certificate.
	TLSKeyPath string `yaml:"tlskeypath" long:"tlskeypath" description:"Path to the TLS key to serve with"`

	// StatePath is the path to a JSON file the bundle balances are
	// persisted to on every change. Persistence is disabled when empty.
	StatePath string `` /* 127-byte string literal not displayed */
}

Config holds the daemon configuration. Values are read from an optional YAML config file and can be overridden through command line flags. The models map can only be configured through the YAML file.

func LoadConfig

func LoadConfig(args []string) (*Config, error)

LoadConfig parses the given command line arguments, merges in the YAML config file when one is provided and validates the result. Command line flags take precedence over values from the config file.

func NewConfig

func NewConfig() *Config

NewConfig returns a Config populated with all default values.

type JSONStore

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

store keeps the bundle balances, keyed by the hex-encoded L402 token ID, and optionally persists them to a JSON file. Persistence is coalesced: mutations set a dirty flag that a periodic flush and shutdown drain to disk, rather than rewriting the whole file synchronously on every change.

func NewJSONStore

func NewJSONStore(cfg JSONStoreConfig) (*JSONStore, error)

NewJSONStore creates a store from the given configuration, loading any persisted bundle state.

func (*JSONStore) Authorize

func (s *JSONStore) Authorize(tokenID string, estimate int64) (Authorization,
	bool, error)

Authorize marks the token's bundle as used and, under one lock, decides by AdmitReservation whether the request is admitted, reserving its estimate only if so.

func (*JSONStore) Book

func (s *JSONStore) Book(tokenID, model string, tokens, priceSats int64) (bool,
	error)

Book records a fresh bundle for the given token ID. Booking is idempotent: a token that already has a bundle is left untouched. The boolean return value indicates whether a new bundle was created. Booking only marks the store dirty rather than persisting synchronously, so a burst of un-paid challenge mints cannot amplify into a full-file rewrite per request.

func (*JSONStore) Debit

func (s *JSONStore) Debit(tokenID string, tokens, releaseEstimate int64) (Bundle,
	bool, error)

Debit subtracts the actual tokens consumed from the token's balance, clamping at zero, and releases the given reservation estimate taken at authorization time. It returns a copy of the bundle after the debit and whether the token is known. A real debit is flushed to disk immediately, since it moves money.

The proto does not correlate a report with the authorization that preceded it, so the release is matched by size; see releaseReservationLocked.

func (*JSONStore) ExpireStale

func (s *JSONStore) ExpireStale(ttl time.Duration) int

ExpireStale removes bundles that were never used by an authorized request within the given TTL and returns the number of removed bundles. It also drops expired reservations.

func (*JSONStore) Flush

func (s *JSONStore) Flush() error

Flush persists the current state if it has diverged from the file since the last flush. It is safe to call on an unchanged store.

func (*JSONStore) Get

func (s *JSONStore) Get(tokenID string) (Bundle, bool)

Get returns a copy of the token's bundle.

func (*JSONStore) ReservationsExpire added in v0.6.1

func (s *JSONStore) ReservationsExpire() bool

ReservationsExpire reports whether reservations are dropped after the configured reservation TTL.

type JSONStoreConfig

type JSONStoreConfig struct {
	// StatePath is the path to the JSON file bundle balances are persisted
	// to. Persistence is disabled when empty.
	StatePath string

	// MaxUnauthorized is the maximum number of never-authorized (un-paid)
	// bundles retained at once. When a fresh booking would exceed the cap,
	// the oldest un-authorized bundle is evicted. A non-positive value
	// disables the bound.
	MaxUnauthorized int

	// MinEvictionAge is the age below which a never-authorized bundle is
	// immune to count-based eviction. Payment happens at the proxy, so a
	// just-paid bundle is indistinguishable from mint spam until its
	// first authorized request; the age floor keeps a spam burst from
	// evicting it in that window. The janitor still reaps bundles older
	// than the TTL, so with the floor set to the TTL the worst-case
	// retained state under spam is the mint rate times the TTL. A
	// non-positive value disables the floor.
	MinEvictionAge time.Duration

	// ReservationTTL is how long a reservation is held before it is
	// presumed leaked by a lost usage report and dropped. A non-positive
	// value disables expiry.
	ReservationTTL time.Duration
}

JSONStoreConfig holds the tunables that govern persistence coalescing and the bound on un-paid bundles.

type ModelConfig

type ModelConfig struct {
	// InputMsatPerToken is the price in millisatoshi of a single input
	// (prompt) token.
	InputMsatPerToken int64 `yaml:"inputmsatpertoken" long:"inputmsatpertoken" description:"Price in millisatoshi per input token"`

	// OutputMsatPerToken is the price in millisatoshi of a single output
	// (completion) token.
	OutputMsatPerToken int64 `yaml:"outputmsatpertoken" long:"outputmsatpertoken" description:"Price in millisatoshi per output token"`

	// InputMsatPerThousandTokens is the price in millisatoshis of one
	// thousand input tokens. When positive, it takes precedence over
	// InputMsatPerToken and permits sub-msat per-token pricing.
	InputMsatPerThousandTokens int64 `` /* 160-byte string literal not displayed */

	// OutputMsatPerThousandTokens is the price in millisatoshis of one
	// thousand output tokens. When positive, it takes precedence over
	// OutputMsatPerToken and permits sub-msat per-token pricing.
	OutputMsatPerThousandTokens int64 `` /* 164-byte string literal not displayed */

	// CachedInputPermille is the price of a cached input token in
	// thousandths of the input rate. Zero selects the full input rate.
	CachedInputPermille int64 `` /* 147-byte string literal not displayed */
}

ModelConfig holds the per-token rates of a single model.

type RateSource

type RateSource interface {
	// ResolveModel maps a model identifier to a canonical model name and
	// its per-token rates. An empty identifier resolves to the default
	// model. A non-empty identifier the source does not know MUST return
	// an error rather than fall back: the server's model mismatch guard
	// relies on unknown models failing resolution, otherwise a bundle
	// bought for a cheap model could be spent on an upstream-hosted model
	// the seller never priced.
	ResolveModel(model string) (string, *ModelConfig, error)

	// BundleTokens returns the number of tokens sold per bundle for the
	// given canonical model.
	BundleTokens(model string) int64
}

RateSource supplies the model rate table and the bundle sizing policy the server prices with. The default implementation is a static table built from the config's models map. A daemon that builds on meterd as a library can supply a dynamic implementation instead, e.g. one refreshed from an upstream provider's price list with a margin applied.

type ReservationExpirer added in v0.6.1

type ReservationExpirer interface {
	// ReservationsExpire reports whether leaked reservations are
	// eventually dropped.
	ReservationsExpire() bool
}

ReservationExpirer is an optional interface a Store implements to report that it drops reservations whose usage report never arrives. Only then can a funded bundle whose balance is all reserved be told to retry later, since without expiry a leaked reservation would never clear and the buyer would retry forever. A store that does not implement it keeps the 402 quote.

type Server

type Server struct {
	pricesrpc.UnimplementedPricesServer
	// contains filtered or unexported fields
}

Server implements the pricesrpc.Prices service with token bundle metering. A client purchases a bundle of Config.BundleTokens LLM tokens with a single L402 payment and draws it down across requests. Once the bundle is spent, AuthorizeRequest denies further requests and quotes the price of the next bundle, prompting aperture to mint a fresh 402 challenge.

func NewServer

func NewServer(cfg *Config, opts ...ServerOption) (*Server, error)

NewServer creates a Server from the given configuration, loading any persisted bundle state. Without options, bundles live in the JSON file store and prices come from the config's static models map.

func (*Server) AuthorizeRequest

AuthorizeRequest allows a request through while the token's bundle still has tokens left. Unknown tokens and exhausted bundles are denied together with a quote for the next bundle, so aperture can mint a fresh challenge without a round trip through GetPrice. A request whose model does not match the bundle's booked model is also denied, so a cheap-model bundle cannot be spent on an expensive model. Business logic denials are never errors; errors are reserved for internal failures.

func (*Server) ChallengeMinted

ChallengeMinted books a fresh token bundle for the minted challenge's token ID, remembering the model and the quoted price. Booking is idempotent per token ID.

func (*Server) GetPrice

GetPrice quotes the price of a token bundle for the model named in the JSON body of the serialized HTTP request. Requests naming no model are priced as the default model; requests naming an unknown model are rejected with an InvalidArgument error, since a model the seller never priced must not be quoted (or proxied) at another model's rate.

func (*Server) QuoteSession

QuoteSession prices one request drawn against a prepaid MPP session balance.

Where GetPrice quotes a whole token bundle, this quotes the single request in hand, at the same blended per-token rate the bundle is priced at. The estimate is the request's max_tokens when it declares one and the configured default otherwise, the completion part of a bundle reservation. A session and a bundle charge the same rate for the same work; what differs is only who holds the balance.

Nothing is booked or reserved here. The session's balance lives in aperture, which deducts this estimate itself and refunds whatever is left when the session closes, so a quote the buyer never uses costs the pricer nothing to have given.

func (*Server) ReportUsage

ReportUsage extracts the final usage object from the captured response tail and debits the token's bundle by the number of consumed tokens. The informational satoshi amounts of the response are derived from the booked model's rates: the debit is rounded up and the remaining balance is rounded down, so rounding never favors the client.

func (*Server) SettleSession

SettleSession costs a response that was served against a session balance and returns what the request should actually have cost.

The cost is derived from the same trailing usage object ReportUsage reads, and priced exactly per direction when the prompt and completion split is known: an all-completion workload costs the full output rate rather than the blended one the estimate assumed. Millisatoshis round up to satoshis, so rounding never favours the client.

A response that carries no usage object settles at the estimate rather than at zero. Returning zero would make every unparseable response free, which turns a truncated stream or an unexpected content type into an unmetered request. Leaving the estimate in place charges what the challenge told the buyer a request would cost, which is the honest answer when nothing better is known.

func (*Server) Start

func (s *Server) Start() error

Start begins listening on the configured address and serving the prices gRPC interface, and launches the janitor.

func (*Server) Stop

func (s *Server) Stop()

Stop shuts down the gRPC server, the janitor and the flusher, draining any pending state to disk.

type ServerOption

type ServerOption func(*serverOptions)

ServerOption customizes a Server beyond its config. The options exist so that a daemon building on meterd as a library can swap in its own storage and pricing while reusing the metering logic unchanged.

func WithRateSource

func WithRateSource(rates RateSource) ServerOption

WithRateSource makes the server price with the given rate source instead of the static table built from the config's models map.

func WithStore

func WithStore(store Store) ServerOption

WithStore makes the server track bundles in the given store instead of the default JSON file store.

type Store

type Store interface {
	// Book records a fresh bundle for the given token ID. Booking is
	// idempotent: a token that already has a bundle is left untouched,
	// and the boolean return value reports whether a new bundle was
	// created.
	Book(tokenID, model string, tokens, priceSats int64) (bool, error)

	// Authorize marks the token's bundle as used and atomically decides,
	// by AdmitReservation, whether a request reserving the estimate is
	// admitted, reserving it only if so. It returns the outcome and
	// whether the token is known.
	Authorize(tokenID string, estimate int64) (Authorization, bool, error)

	// Get returns a copy of the token's bundle.
	Get(tokenID string) (Bundle, bool)

	// Debit subtracts the actual tokens consumed from the token's
	// balance, clamping at zero, and releases the reservation of the
	// given estimate taken at authorization time, or nothing if none
	// matches. It returns a copy of the bundle after the debit and whether
	// the token is known.
	Debit(tokenID string, tokens, releaseEstimate int64) (Bundle, bool,
		error)

	// ExpireStale removes bundles that were never used by an authorized
	// request within the given TTL and returns the number of removed
	// bundles. It should also drop reservations held past their TTL.
	ExpireStale(ttl time.Duration) int

	// Flush drains any pending state to durable storage. It is safe to
	// call on an unchanged store.
	Flush() error
}

Store tracks the prepaid token bundles the server meters against, keyed by the hex-encoded L402 token ID. The JSONStore implementation persists the balances to a single JSON file; a daemon embedding meterd can supply a database-backed implementation instead.

Jump to

Keyboard shortcuts

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