accrec

package
v0.7.9 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 21 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 (
	// 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

This section is empty.

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.BilledOneHour's, which ResolveTier uses: a write bills its tier on the tokens it wrote; 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 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 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 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 is priced, so its cost is on its row, but its facts are not stored. The write it avoided is already booked on its own row as ManualSavedUSD, from the user's estimate. Storing the facts too would let the next real request credit the same write again as a library rescue, and the total would count it 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 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 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 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 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
	// 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) 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.

Jump to

Keyboard shortcuts

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