accrec

package
v0.7.11 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 23 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

Index

Constants

BaseTTL and OneHourTTL are the two Anthropic lifetimes, from the one table (modelinfo). The proxy reads them here and writes no duration of its own (#1350).

View Source
const (
	GateCheckSum          = accountant.WithheldCheckSum          // library: the sum check failed (not one that no operation claims)
	GateCheckUniqueChange = accountant.WithheldCheckUniqueChange // library: two operations share a ChangeID
	GateCheckSpans        = accountant.WithheldCheckSpans        // library: an operation's spans do not add up to its sizes
	GateCheckOther        = accountant.WithheldCheckOther        // library: a fatal check with no reason of its own
	GateUnpriced          = accountant.WithheldUnpriced          // library: an operation or effect is unpriced
	// The size bound is the library's too (accountant v0.11.0): the message tokens the operations saved, less the ones
	// they caused, must fit the request's message tokens, all at the request ratio. Tool declarations are in no
	// SavedMessages, so a deferral or a tool filter is not withheld (#907).
	GateImplausibleSize = accountant.WithheldImplausibleSize // library: the operations saved more message tokens than the request had
	// The other host gates: what only the host knows, the change list, the run mode and its own rows.
	GateOpsDropped         = "ops_dropped"          // host: a change could not be placed as an operation
	GateObserve            = "observe"              // host: the run was observe mode
	GateFigureWithoutRow   = "figure_without_row"   // host: a library figure for a component with no row
	GateDuplicateName      = "duplicate_name"       // host: two rows share a component name
	GateActedWithoutFigure = "acted_without_figure" // host: a component acted and the library has no figure for it
)

The reasons a request books no accountant figure (Gate). The dashboard stores them as requests.acc_fallback, and the /stats ledger counts the same requests as unpriced (#1441, #1465). One decision, so a request the row refuses is unpriced on /stats too.

The library's reasons are the ones accountant.Withhold returns, so the dashboard row, /stats and the metrics push gate with one rule, and the accountant decides alone: checks, unpriced operations and the size bound.

View Source
const (
	EndedChangeComponent = "ended_change"
	InteractionComponent = "interaction"
)

The rows a host adds for a figure that no pipeline component owns.

View Source
const (
	// DeferralUnplaced: a deferral whose stub cannot be placed (a stub that would not be smaller than its
	// definition). Computing on the bodies as they are would fail the sum check, so no figure is computed.
	DeferralUnplaced = "deferral_unplaced"
	// RejectedStatus: the provider answered with a status that is not 2xx.
	RejectedStatus = "rejected_status"
	// ComputePanicked: the library panicked while it priced the request.
	ComputePanicked = "compute_panicked"
)

The reasons a request books no accountant figure. The log line acc_fallback names one of them.

View Source
const (
	// StateMaxAge is how old a snapshot may be and still be restored. No cache entry outlives the longest
	// TTL (1h), so an older snapshot holds only expired state.
	StateMaxAge = time.Hour
	// StateEvery is how often a host should save the state while running, so a kill -9 or a crash loses minutes, not all.
	StateEvery = time.Minute
	// StateVersion is the version of the host's own part of the state: how accwire hashes a body. Change it
	// whenever that hash changes. The library snapshot has its own version inside. A file with another version is
	// ignored (issue #917). Version 1 was the unwrapped library snapshot, so a file from before the wrap fails the
	// check too. Version 2 is the wrap with the hash that leaves out cache marks, nested ones included.
	StateVersion = 2
	// ThinkingMaxAge is how old a state file may be and still give back its thinking counts. A count is
	// keyed by a signature's hash, not by a time, and a block can come back long after its cache entry expired
	// (it is billed as fresh input then), so the counts outlive the snapshot's hour.
	ThinkingMaxAge = 24 * time.Hour
)

A thread's state lives in memory in the library. Without a save, every restart drops the active changes of every live session: the next request of each one is priced as an estimate (context-guru#768, major 2). The snapshot holds hashes and sizes, no message text (accountant persist.go). This file holds the format and the rules of that state. The host reads and writes the file.

View Source
const PingStoreMax = 4096

PingStoreMax bounds PingStore. It is keyed by session and thread, so without a bound a long-running proxy would hold one entry per thread that was ever pinged and never asked again.

Variables

EnvelopeComponents are the operators that change the request envelope (tools, system, cache marks) and may have no pipeline row: the proxy reports them from a body diff (accwire/envelope.go). expand, adjudicate and expand_restore are never pipeline components; headttl is a host option; toolschema and toolfilter are components whose row can be absent when the rewrite ran from an equivalent gate.

Functions

func BilledBody

func BilledBody(forwarded []byte, own map[string]bool) (billed []byte, ok bool)

BilledBody returns the forwarded body as the provider bills it, with the definitions in own cut to stubs. ok=false means the accountant should not be given a stub-sized copy: nothing in own is in the body, or a stub would not be smaller than the definition it replaces. A stub that grows the tool is not a deferral the provider billed less for, and an operation that reports it as a shrink would book a saving nothing measured. The caller then keeps the forwarded body as it is, and the event books no figure (the log line says acc_fallback deferral_unplaced) instead of booking a wrong one. The tools array is rebuilt in one pass: a copy of the body for each stub is O(body x tools).

func BilledForwarded added in v0.7.9

func BilledForwarded(forwarded, preDefer []byte) (body []byte, noResult string)

BilledForwarded is the body the accountant records for a request. A request that tool deferral did not change returns the forwarded body. A deferral whose stub cannot be placed (a stub that would not be smaller than its definition) also returns the forwarded body, and noResult is DeferralUnplaced, so the event books no figure and the sum check does not turn it into a wrong one. A tool the client deferred itself is left as it is (OwnDeferred). preDefer is the body deferral read, nil on a request it did not change.

func BilledTTL

func BilledTTL(tiers *TierStore, key string, f accountant.EntryFacts, cacheWrite, cacheWrite1h int64) (lower bool)

BilledTTL decides the entry TTL after the response, when a gateway downgraded the tier the request asked for (1h). It runs after the usage arrives and before Compute, which reads the facts' TTL for the verdict and stores it as the entry's TTL. Without it the library treats a gap of 5 to 60 minutes as hot and can overstate a rescue by up to 55 minutes of idle time.

The rule is keepalive.HeadLifetimeOneHour's (the accountant lowers only when nothing was billed at 1h): a write lives 1 hour when any token of it was billed at 1 hour, so the 1-hour head of a head-TTL write keeps its tier and only a write with no 1h token lowers the entry. The keeper keeps its own whole-entry rule for the ping plan (keepalive.BilledOneHour). A turn that wrote nothing bills none and keeps the thread's last billed tier (issue #1078). A thread with no earlier write has none to keep, so the asked tier stands. Only an exact lifetime has a TTL that can be lowered: a minimum (OpenAI) has no tier. SharedWarm was judged with the asked TTL at the start and is not redone; it matters only when another thread of the session touched the entry.

key is the thread's PingKey. It returns lower=true when the caller must set the facts' TTL to 5 minutes and lower the TTL of every 1h breakpoint of the record with it. The tier store learns from the usage.

func BookPing added in v0.7.10

BookPing is the always-on path of a ping (#1457). It prices the ping (PingSavings), stores its facts for the thread's next real request, and books the result into the savings counters. It needs no dashboard. ok is false when the ping is not converted, and then nothing is booked. A panic in the sink costs the metric only: the result is returned either way. obs may be nil.

func ComponentFigure added in v0.7.10

func ComponentFigure(res accountant.Result, fig accountant.USDFigure, rows []GateRow) (by, first, replay map[string]float64)

ComponentFigure maps the library's ByComponent, ByComponentFirst and ByComponentReplay to the host's component names (the operator prefix off). An operator with no row and 0 tokens in all of its operations is left out: it would get an envelope row of $0. A name with a row keeps its key at $0: a component that acted can have counted operations of 0 tokens (the byte ratio truncates), and without its key the whole request's saving would be dropped. The mark premium no operation owns goes to the tail breakpoint row, which adds the mark in every default preset.

func DeferMoney added in v0.7.10

func DeferMoney(f accountant.USDFigure) tooldefer.Money

DeferMoney maps the accountant's figure for tool deferral to the ledger's three numbers (#1441). The figure is ByComponent at the tooldefer operator. The library books a spend call as a separate bill, so the search turns are its spend lines on that operator, and they come off the net. Gross is the saved side (first plus replay). Cost is gross less net. No pricing here: it only reads the library's figure.

func DeferSpendOps added in v0.7.10

func DeferSpendOps(s tooldefer.SearchSpend, ratio *accountant.Ratio) []accountant.Operation

DeferSpendOps turns the search-turn costs of one deferred request into accountant spend operations on the tooldefer operator (#1441). Each is a Call with its own usage:

  • defer-search-output: the search calls' output tokens;
  • defer-search-second-pass: the API's second pass reads the loaded definitions once without the cache (input);
  • defer-search-next-write: the next request writes the loaded definitions to the cache once (cache write).

With a ratio (the request's own, accrec.Recorder.RatioFor) the loaded definitions are priced from their bytes. The library prices each Call at its own usage and size. The second and third are estimates. The first is an estimate too when usage did not give the output. A cost of 0 tokens makes no operation. The ChangeID is empty: a spend is booked once, on the request that paid it.

func DeferSpendUSD added in v0.7.10

func DeferSpendUSD(f accountant.USDFigure) float64

DeferSpendUSD is the cost of the search turns in the library's figure: its spend lines on the tooldefer operator. The library books a spend call as a separate bill, so a host takes it off the deferral figure with this sum. The Call names no model, so the library prices it on the request's own model (the host pricer prices that one model only).

func DeferredNames

func DeferredNames(body []byte) map[string]bool

DeferredNames is the set of names of the definitions the body defers.

func DeferredStub

func DeferredStub(name string) string

DeferredStub is what the accountant's copy of a deferred definition keeps. The provider bills no definition, so the stub is as small as a tool can be and still be a tool. Our own tokenizer does not enter here: the library converts the bytes with the request's own ratio, billed tokens over body bytes.

func EntryFacts

func EntryFacts(provider bschemas.ModelProvider, model string, forwarded []byte, pings PingLookup,
	session string, t accountant.Thread) accountant.EntryFacts

EntryFacts builds the facts the library needs about the entry this request wrote. A keep-alive ping for the thread since its last request is read from pings (nil = none; the capture drops it once the request is priced) and supplies LastPing, PingWindow and the ping's usage. PingRead stays nil: the keeper replays the previous request's forwarded body, so the library derives the extent the ping read from its usage (accountant design §5.2).

The Lifetime kind comes from apply.CacheLifetime, the same rule the cold gate uses: an exact expiry for a provider with explicit breakpoints, a minimum for OpenAI's 30-minute entries, else unknown. An unknown lifetime cannot prove an expiry, so the library would never rescue after a gap past the TTL (design §5.2). The TTL is 1h only when EVERY breakpoint of the forwarded body asks for it, as the keeper decides: a 1h head over a 5m tail leaves a tail that expires in five minutes. The keeper also needs the billed tier, which is known only after the response. These facts are written before it, so they hold the ASKED tier. BilledTTL corrects it once the usage arrives, before the library prices the request (context-guru#919).

func EnvelopeOpsFor

func EnvelopeOpsFor(client, billed, preDefer []byte) []accountant.Operation

EnvelopeOpsFor is the wire's EnvelopeOps for the body the accountant records, with tool deferral's edits attributed to the tooldefer operator so its row does not land on toolschema (#908). client is the body the agent sent, billed the body BilledBody gave, and preDefer the body deferral read (nil when deferral did not run). Deferral's edits are two: the definitions the proxy deferred, each now a stub (R56), and the search tool it adds, an ordinary added declaration.

Each keeps the ChangeID EnvelopeOps gave it, and only the operator changes. The ChangeID is what the library replaces by, so a thread whose state was written before this change (per-tool cg:toolschema:decl-rewritten and decl-added operations) has them replaced on its next request instead of kept beside a second copy, and a deferred set that grows or shrinks mid-thread re-reports each surviving tool under its own stable ID. One merged operation would carry a hash of the whole set, so any change of the set would orphan it.

func Gate added in v0.7.10

func Gate(res accountant.Result, fig accountant.USDFigure, in GateIn) (reason, detail string)

Gate says why a request books no accountant figure, or "" when it does. detail is the library's "opID:reason" for GateUnpriced. fig is the library's own figure for res. The gates, in order: a change dropped, an observe run, the library's (accountant.Withhold: a fatal check, an unpriced operation or effect, or more message tokens saved than the request had; penalty_unknown does not gate: see Held), then the rows: a figure for a component with no row, a row that the host adds for the ended change or the interaction when a component has that name already, two rows with one name, and a component that acted with no figure.

It is the one decision the dashboard row and the /stats ledger share. It reads no price.

func Held added in v0.7.10

func Held(res accountant.Result) bool

Held says that the library could not rule out a break (penalty_unknown): the thread had no history. The dashboard books no saving for such a request (issue #915), the deferral's figure with the rest, so the /stats ledger books none either: one figure on every surface (#1441).

func HeldFloorUSD added in v0.7.10

func HeldFloorUSD(fig accountant.USDFigure, ceiling float64, skip ...string) float64

HeldFloorUSD is the lower bound of a held figure (policy of context-guru, not of the accountant).

The held ceiling prices each removed token as the write the provider would have made on a cold cache. If the cache was warm, the client would have paid the read rate for the tokens in the warm prefix, so the saving is lower. The read rate is the least a client token costs. The floor prices the same removed tokens at the read rate: it takes the ceiling and subtracts, for each operation, the Saved dollars minus the same tokens priced as reads (ByComponentSaved, ByComponentSavedAsRead). Caused tokens and the cache effects stay as they are.

ceiling is the figure that the floor lowers. skip is a list of keys of fig (the operator as the host gave it) whose tokens are not in that ceiling. The floor is never above the ceiling: with a price table whose read is dearer than its write, it equals the ceiling.

func IsStub

func IsStub(billed []byte, i int) bool

IsStub says whether the tool at i of the billed body is a deferred stub: a bare name and the defer_loading mark.

func MetricComponents added in v0.7.9

func MetricComponents() []string

MetricComponents is the component allow-list for an accountant metrics sink (acmetrics.WithComponents): every registered component and every operator outside the registry (accwire.OperatorsOutsideRegistry). The sink pushes a name outside the list as component="other", so with this list each operator context-guru books keeps its own `component` label, and the central dashboard can split the net saving by it.

func NoResultWhy

func NoResultWhy(hasRecord, usageOK bool, noResult string, rounds int) string

NoResultWhy names the branch that left an event with no accountant Result, for the acc_fallback line. The reason no_result covers four unrelated things, and the log line used to say only that. hasRecord is false when the pipeline did not run: no session, or no record was opened.

func OwnDeferred

func OwnDeferred(forwarded, preDefer []byte) map[string]bool

OwnDeferred is the names the PROXY deferred on this request: deferred in the forwarded body, and not already deferred in the body deferral read. A tool the client deferred itself (Claude Code does) is free in the baseline too, because the provider bills no definition for it whoever set the mark, so it is no saving of ours and it keeps its definition, with its cache_control, in the accountant's copy.

func PingFromReport

func PingFromReport(r components.KeepAliveReport) accountant.Ping

PingFromReport maps a keeper report to the library's Ping. r.CostUSD is deliberately not carried: the host prices the ping with its own rates.

func PingKey

func PingKey(session, threadID string) string

PingKey is the key the ping store keeps one thread's ping facts under: the session and the thread id as the accountant sees it ("main" for the primary thread).

func PingObservation added in v0.7.10

PingObservation is the savings-counter observation of a priced ping. Output stays unset on purpose: a ping books only a spend operation, and its output is priced through the spend call.

func PingSavings

func PingSavings(r components.KeepAliveReport, st PingSink, calls PingCalls) (res accountant.Result, ok bool)

PingSavings prices one keep-alive ping as a spend operation and stores its facts in st for the thread's next real request. ok is false, and nothing is stored, for a ping that is not converted: no Window (its ChangeID would be shared by every such ping), a status outside 200-299, or no usage (it billed nothing). Manual and sweep-substitute pings are converted.

A MANUAL ping works like a scheduled one: its facts are stored, and the accountant credits the rescue on the thread's next real request (#1460). Its row books no estimate (ManualSavedUSD), so the write it avoided is counted once, as that rescue. Before #1460 the row booked the user's estimate and the facts were not stored, because both together counted the write twice (context-guru#768 B3: $0.0200 booked, about $0.0096 true).

A panic in the library is recovered and logged, and the ping is reported as not converted. The keeper runs this in its own goroutine, so an unrecovered panic would end the process (issue #918).

func ProviderTokens added in v0.7.11

func ProviderTokens(model string, hostTokens, bytes int64, c RatioCounts) (provider float64, live bool)

ProviderTokens converts a removal into the provider's tokens (#1533). With the row's own ratio and the removed bytes, it is Ratio.Tokens of the bytes: live is true, and the host's own count is not read. Without them, it is the host's own token count scaled by the legacy table (tokens.LegacyFactor), the documented fallback for a row written before the ratio existed: live is false.

func Rejected

func Rejected(status int) bool

Rejected is true when the provider answered with a status that is not 2xx. Status 0 means no upstream answered (such as /compact), and is not a rejection.

func RequestFactor added in v0.7.11

func RequestFactor(hostRemoved, bytes int64, c RatioCounts) (factor float64, ok bool)

RequestFactor is the provider's tokens for each of the host's tokens of what one request removed, from the request's own ratio and the bytes the removal took out (#1533). hostRemoved is the host's count of the same removal (tokens_before - tokens_after). ok is false when the request has no ratio or no bytes, or the removal is empty or the answer is outside 1..tokens.MaxBilledRatio (the bound the warm gate trusts: the bytes and the host tokens are paired only by design, and a bad pair must not scale a figure): the caller then keeps the legacy table (tokens.LegacyFactor), the fallback for a row written before the bytes were stored.

func ShouldCompute

func ShouldCompute(status, rounds int, noResult string) (compute bool, reason string)

ShouldCompute decides whether the accountant prices a request that has a record and a usage. A rejected request (a status that is not 0 and not 2xx) books no saving, in tokens or in dollars: the body of a 4xx or 5xx can still carry a usage object, but the provider billed none of the request. A deferral that could not be placed books no figure either. Neither does a request that took several upstream rounds: its usage is not one request's. The thread state is left as the previous request left it; the next request then sees a longer gap, which the library handles (a phase it cannot prove is unknown and falls back too).

noResult is the reason an earlier step already set. When compute is false, reason is the noResult to record: the given one, or RejectedStatus (which replaces it).

func ThreadID

func ThreadID(id string) string

ThreadID maps the primary thread to "main", the library's name for it.

func ThreadOf added in v0.7.9

func ThreadOf(id string, parent string, hasParent bool) accountant.Thread

ThreadOf is the library thread for a thread id and, when the thread continues another by content, its parent. A continuing thread starts with no state of its own: accountant carries Thread.Parent and does not read it (design §4.1).

Types

type EndRecord added in v0.7.9

type EndRecord struct {
	Client, Forwarded accountant.Body
	Breakpoints       []accountant.Breakpoint
}

EndRecord is what End gave EndRequest. The library keeps its record in unexported fields, so a test that checks the bodies the library saw reads them here.

type GateIn added in v0.7.10

type GateIn struct {
	Observe    bool // the run was observe mode
	OpsDropped int  // changes that could not be placed as operations
	Rows       []GateRow
}

GateIn is what the gate needs besides the Result and the library's figure.

type GateRow added in v0.7.10

type GateRow struct {
	Name  string
	Acted bool
}

GateRow is one component row of the request, as the gate needs it.

func GateRowsOf added in v0.7.10

func GateRowsOf(run *components.RunReport) []GateRow

GateRowsOf is the component rows of a run, as the dashboard row builds them: a component acted when it was neither reverted nor skipped and saved tokens.

type PingCalls

PingCalls are the two library calls PingSavings makes. A host passes its own to wrap or replace them, as a test does to make them panic. A zero value uses the library's.

type PingLookup

type PingLookup interface {
	Peek(key string) (accountant.PingFacts, bool)
}

PingLookup reads the ping facts a thread's next request takes. A nil store has none.

type PingSink

type PingSink interface {
	Put(key string, f accountant.PingFacts)
	NotePriced()
}

PingSink keeps the facts of a priced ping for the thread's next real request, and counts the pings priced. The host owns the store. A nil sink is allowed.

type PingStore added in v0.7.9

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

PingStore remembers, per session and thread, the facts of the latest keep-alive ping until the thread's next real request takes them. A host gives the same instance to its ping emitter (writer) and to its request path (reader). A nil *PingStore is a no-op.

func NewPingStore added in v0.7.9

func NewPingStore() *PingStore

NewPingStore returns an empty store holding at most PingStoreMax threads.

func (*PingStore) Drop added in v0.7.9

func (s *PingStore) Drop(key, window string)

Drop deletes the facts for key: they belong to the next priced request only. window is the PingWindow the request read; facts with another window are a newer ping, put after the request read, and stay for the next request. An empty window drops whatever is there.

func (*PingStore) Len added in v0.7.9

func (s *PingStore) Len() int

Len is how many threads the store holds. Nil-safe.

func (*PingStore) NotePriced added in v0.7.9

func (s *PingStore) NotePriced()

NotePriced counts one priced ping. Nil-safe.

func (*PingStore) Peek added in v0.7.9

func (s *PingStore) Peek(key string) (accountant.PingFacts, bool)

Peek returns the facts for key and keeps them. A request reads them before it is sent; it takes them (Drop) only once it is priced, so a request that books nothing leaves them for the next one.

func (*PingStore) Priced added in v0.7.9

func (s *PingStore) Priced() int64

Priced is how many pings PingSavings priced. Nil-safe: a host with no store reads 0.

func (*PingStore) Put added in v0.7.9

func (s *PingStore) Put(key string, f accountant.PingFacts)

Put keeps the latest facts for key; a second ping overwrites the first. When the store is full and key is new, an arbitrary other entry is evicted (map order), which only costs the evicted thread its LastPing gap on its next request.

func (*PingStore) Take added in v0.7.9

func (s *PingStore) Take(key string) (accountant.PingFacts, bool)

Take is Peek and Drop in one step.

type PriceIn added in v0.7.9

type PriceIn struct {
	Status, Rounds int
	// NoResult is the reason an earlier step gave for booking no figure (a deferral that could not be placed). "" if none.
	NoResult string
	Usage    Usage
	// BeforeCompute, when set, runs once, just before the library prices the request and only when it will. The
	// host uses it to set the entry's billed tier on its facts (BilledTTL), which Compute reads.
	BeforeCompute func()
	// AfterCompute, when set, runs once with the result, right after the library priced the request and before the
	// rescue counter and the ping-facts drop. It does not run when the request books no figure. The host books the
	// result here (event, metrics), so those side effects keep their order.
	AfterCompute func(accountant.Result)
	// Session and Thread are the ping store's key. KaPings is how many pings went out in the gap this request ended.
	// PingWindow is the window of the ping facts the request read when it opened, "" if it read none.
	Session, Thread string
	KaPings         int
	PingWindow      string
	Pings           *PingStore
}

PriceIn is what Price needs of one finished request.

type PriceOut added in v0.7.9

type PriceOut struct {
	Result   accountant.Result
	Priced   bool // Result is set
	NoResult string
}

PriceOut is what Price decided. NoResult is PriceIn.NoResult, or the reason the request books no figure.

type RatioCounts added in v0.7.11

type RatioCounts struct {
	// BilledTokens and TextBytes are Ratio.Text: the tokens and the bytes of the forwarded text.
	BilledTokens, TextBytes int64
	// Capped is Ratio.Capped.
	Capped bool
	Known  bool
}

RatioCounts are the three stored counts of a request's ratio. Known is false when the request has none: it was not priced, or it was written before the columns existed.

func RatioCountsOf added in v0.7.11

func RatioCountsOf(res accountant.Result) RatioCounts

RatioCountsOf reads the counts off a priced Result. Known is false for a Result with no ratio. It never panics.

func (RatioCounts) ApplyTo added in v0.7.11

func (c RatioCounts) ApplyTo(in *accountant.RemovalInput, hostTokens, bytes int64) (providerPerHost float64)

ApplyTo sets the row's own ratio and the removed bytes on a removal that the accountant prices (RemovalSaving), when the row has both (#1533). It returns the provider's tokens for each of the host's tokens of this removal, for a caller that holds a host token weight per item: 1 when it set nothing, so the input keeps today's answer (factor 1). hostTokens is the host's own count of the same removal.

func (RatioCounts) Ratio added in v0.7.11

func (c RatioCounts) Ratio() *accountant.Ratio

Ratio rebuilds the ratio from the stored counts. nil when the row has none, so a caller keeps its fallback.

type RecordIn added in v0.7.9

type RecordIn struct {
	Meta accountant.RequestMeta
	// Client is the body the agent sent. PreDefer is the body tool deferral read, nil on a request it did not change.
	Client, PreDefer []byte
	// Forwarded is the body sent upstream. Ops are the pipeline's operations; Record appends the envelope ones.
	Forwarded []byte
	Ops       []accountant.Operation
	// ThreadID is the thread's id. Parent is the thread it continues by content, when HasParent.
	ThreadID, Parent string
	HasParent        bool
	Provider         bschemas.ModelProvider
	Endpoint, Route  string
	// ReadSets tells whether a read sets the entry's TTL on this route (the keeper's readSetsTTL). nil: never.
	ReadSets func(provider bschemas.ModelProvider, endpoint, route, model string, pinged bool) bool
	Pings    *PingStore
}

RecordIn is what Record needs of one request, after the pipeline ran.

type RecordOut added in v0.7.9

type RecordOut struct {
	Thread   string
	Facts    accountant.EntryFacts
	NoResult string
}

RecordOut is what Record decided. NoResult is set only when the request books no figure (a deferral that could not be placed).

type Recorder added in v0.7.9

type Recorder struct {
	// Trackers holds each thread's state. Exported so a host test can break it on purpose.
	Trackers *accountant.Trackers
	// Siblings holds each thread's last forwarded body, for EntryFacts.SharedWarm.
	Siblings *SiblingStore
	// Tiers is the tier each thread's last write was billed at, for BilledTTL (issue #1078).
	Tiers *TierStore
	// Thinking holds the token count of each thinking block a response made, by its signature's key, so a block
	// the client sends back is priced at its own count (issue #1187, accountant design D16). Saved with the state.
	Thinking *thinkcount.Table
	// Clients holds the hash of each open request's client body, by request, from Begin to End.
	Clients sync.Map // *accountant.Request -> clientHash
	// Forwarded holds the forwarded body of each ended request, by request, from End to Price or Drop (#1533): the
	// request ratio is built from it, before Compute, for a cost the host reports as an operation.
	Forwarded sync.Map // *accountant.Request -> accountant.Body
	// OnEnd, when set, is called with each record after EndRequest. Tests only.
	OnEnd func(*accountant.Request, EndRecord)
	// contains filtered or unexported fields
}

Recorder runs the accountant calls around one request. It holds the one Trackers of a host: a thread's state lives there between requests. A host builds one with NewRecorder and calls Begin, End and Price for each request. It keeps files, logs and metrics to itself (see SnapshotState and RestoreState for the state it keeps across a restart).

func NewRecorder added in v0.7.9

func NewRecorder() *Recorder

NewRecorder returns a Recorder with empty state.

func (*Recorder) Begin added in v0.7.9

func (s *Recorder) Begin(meta accountant.RequestMeta, client []byte) *accountant.Request

Begin opens the request record with the client body, before any component ran. The Trackers bound their own memory (accountant design §6.1, Memory), so there is nothing to sweep here.

func (*Recorder) Compute added in v0.7.9

func (s *Recorder) Compute(req *accountant.Request, u Usage) accountant.Result

Compute prices the request. It stores the new ThreadState (so a shadow run still advances it).

func (*Recorder) ComputeSafe added in v0.7.9

func (s *Recorder) ComputeSafe(req *accountant.Request, u Usage) (res accountant.Result, ok bool)

ComputeSafe is Compute for the request path. The library asks the host to wrap Compute, and the rule is to fail open: a panic here would unwind through the host's finish and lose the log line and the dashboard row of a request that was already forwarded. It reports ok=false instead, the request is recorded with no saving (PriceMode falls back with no_result), and the panic is logged. Tests call Compute, so a panic still fails them.

func (*Recorder) Drop added in v0.7.9

func (s *Recorder) Drop(req *accountant.Request)

Drop forgets the client hash of a request that will never end: a panic between Begin and End makes the host send the original body, and End is the only other place that removes the entry. Nil-safe.

func (*Recorder) End added in v0.7.9

func (s *Recorder) End(req *accountant.Request, th accountant.Thread, forwarded []byte, ops []accountant.Operation, facts accountant.EntryFacts) EndRecord

End records the operations, then the thread and the forwarded body. Every op is added, replays included: the library replaces an active change by the reported op with the same ChangeID (accountant internal/engine/compute.go, items()), so a change is priced once and unique_change never fires. Skipping a replay here would lose the op whenever Compute ends the change on this request.

func (*Recorder) LowerTTL added in v0.7.9

func (s *Recorder) LowerTTL(req *accountant.Request, session, thread string, f accountant.EntryFacts, cacheWrite, cacheWrite1h int64) accountant.EntryFacts

LowerTTL sets the entry TTL to the tier the response billed, when a gateway downgraded the tier the request asked for (1h), and returns the facts. It applies BilledTTL, which holds the rule. It runs after the usage arrives and before Compute, which reads the facts' TTL for the verdict and stores it as the entry's TTL. The library lowers the facts' TTL and the TTL of every 1h breakpoint together, on a copy. Nil-safe: a nil request changes nothing.

func (*Recorder) NoteRescueFactsMissing added in v0.7.9

func (s *Recorder) NoteRescueFactsMissing()

NoteRescueFactsMissing counts one priced request that followed pings and found no ping facts. Nil-safe.

func (*Recorder) Price added in v0.7.9

func (s *Recorder) Price(req *accountant.Request, in PriceIn) PriceOut

Price prices one finished request, or says why it books no figure. The rules for which request books none are ShouldCompute's (a rejected status, a deferral that could not be placed, several upstream rounds) and a panic in the library (ComputePanicked). It also counts a request that followed pings and found no ping facts, and spends the ping facts it read: they belong to the next priced request only.

func (*Recorder) RatioFor added in v0.7.11

func (s *Recorder) RatioFor(req *accountant.Request, u Usage) *accountant.Ratio

RatioFor is the request ratio of an ended request, before Compute: the provider's billed tokens of the forwarded text (accountant.NewRatio), the same ratio Compute builds. A host uses it to convert the bytes of a cost it reports as an operation, so the operation and the figure share one ratio (#1533). nil when the request has no forwarded body here, the usage bills nothing, or the ratio is out of range (accountant check 9): the host keeps its fallback. Nil-safe.

func (*Recorder) RatioTextFor added in v0.7.11

func (s *Recorder) RatioTextFor(req *accountant.Request, u Usage, status, rounds int) (tokens, bytes int)

RatioTextFor is the request ratio's text counts that a thread keeps for its next turn (#1533): the provider's billed tokens of the forwarded text and its bytes. It is the rule for which ratio a thread keeps, so a host only calls it. 0, 0 (keep none) when the request books no figure (ShouldCompute: a rejected status, or several upstream rounds, where the body is the first round's and the usage is the last's), when the ratio is out of range or missing (RatioFor), or when it is capped (its text ratio is a floor). Nil-safe.

func (*Recorder) Record added in v0.7.9

func (s *Recorder) Record(req *accountant.Request, in RecordIn) RecordOut

Record records the thread, the forwarded body and the operations of an open request. A thread that continues another by content names it as its parent, but starts with no state of its own: accountant carries Thread.Parent and does not read it (design §4.1).

func (*Recorder) RecordThinking added in v0.7.9

func (s *Recorder) RecordThinking(r thinkcount.Response)

RecordThinking stores the thinking counts of one billed response. Nil-safe.

func (*Recorder) RescueFactsMissing added in v0.7.9

func (s *Recorder) RescueFactsMissing() int64

RescueFactsMissing is the count NoteRescueFactsMissing keeps. Nil-safe.

func (*Recorder) RestoreState added in v0.7.9

func (s *Recorder) RestoreState(data []byte, age time.Duration) RestoreResult

RestoreState loads the bytes SnapshotState made. age is how old the file is; the host checks it against ThinkingMaxAge before it reads the file. The thinking counts are restored on their own: from a file up to ThinkingMaxAge old, and also when the snapshot is refused.

func (*Recorder) SnapshotState added in v0.7.9

func (s *Recorder) SnapshotState() ([]byte, error)

SnapshotState returns the bytes a host writes to its state file.

type RestoreResult added in v0.7.9

type RestoreResult struct {
	// Restored is true when the snapshot was loaded.
	Restored bool
	// ThinkingErr is set when the thinking counts were bad. They only refine a price, so the snapshot is still read.
	ThinkingErr error
	// TooOld is true when the snapshot was older than StateMaxAge: only the thinking counts were restored.
	TooOld bool
	// Err is why the state was not restored, when it was not and TooOld is false.
	Err error
}

RestoreResult is what RestoreState did, for the host to log. It fails open: Restored is false for a state it could not use, and the host starts with empty state.

type SiblingStore

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

SiblingStore remembers, per session, the last forwarded body each thread sent and when. It gives EntryFacts.SharedWarm: the prefix of a request's forwarded body that another thread of the session kept warm inside the TTL, which a keep-alive rescue must not credit (accountant R54). It holds the library's Body (hashes and sizes only, R2) and the breakpoints, never content.

The store lock is held only to find or create a session; each session has its own lock, so requests of different sessions do not wait on each other's scans.

func NewSiblingStore

func NewSiblingStore() *SiblingStore

func (*SiblingStore) SharedWarm

func (s *SiblingStore) SharedWarm(session, thread string, at time.Time, ttl time.Duration,
	fwd accountant.Body, bps []accountant.Breakpoint) *accountant.Position

SharedWarm returns the last position of fwd that a sibling of thread kept warm inside ttl before at, then records this request as the thread's last. The host chooses the siblings: another thread of the session, last seen inside the TTL and not after this request. The library decides where the shared prefix ends (accountant.SharedWarmFrom, R54). Nil when no sibling did.

type StateFile added in v0.7.9

type StateFile struct {
	Version  int             `json:"cgStateVersion"`
	Snapshot json.RawMessage `json:"snapshot"`
	// Thinking is the count of each thinking block (Recorder.Thinking): a key and a number each. A file
	// written before it has none, and restores with an empty table.
	Thinking json.RawMessage `json:"thinking,omitempty"`
}

StateFile is the file on disk: the host version around the library snapshot.

type TierStore

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

TierStore remembers, per thread, whether its last write was billed at the one-hour tier. It is keyed like the ping store (accPingKey) and holds one bool per thread: no content.

func NewTierStore

func NewTierStore() *TierStore

func (*TierStore) Get

func (s *TierStore) Get(key string) (oneHour, ok bool)

get returns the remembered tier and whether the thread has one. Nil-safe.

func (*TierStore) Set

func (s *TierStore) Set(key string, oneHour bool)

set remembers the tier. Nil-safe.

type Usage added in v0.7.9

type Usage struct {
	FreshInput, CacheRead, CacheWrite, CacheWrite1h int64
}

Usage is what one response billed, in tokens.

func ReportUsage added in v0.7.11

func ReportUsage(r components.KeepAliveReport) Usage

ReportUsage is the billed usage of a keeper report.

func (Usage) Accountant added in v0.7.11

func (u Usage) Accountant() accountant.Usage

Accountant is the usage in the library's type. It is the one conversion: every host site that builds an accountant.Usage from a billed usage calls it.

Jump to

Keyboard shortcuts

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