Documentation
¶
Index ¶
- Constants
- func BilledBody(forwarded []byte, own map[string]bool) (billed []byte, ok bool)
- func BilledTTL(tiers *TierStore, key string, f accountant.EntryFacts, ...) (lower bool)
- func DeferredNames(body []byte) map[string]bool
- func DeferredStub(name string) string
- func EntryFacts(provider bschemas.ModelProvider, model string, forwarded []byte, ...) accountant.EntryFacts
- func EnvelopeOpsFor(client, billed, preDefer []byte) []accountant.Operation
- func IsStub(billed []byte, i int) bool
- func NoResultWhy(hasRecord, usageOK bool, noResult string, rounds int) string
- func OwnDeferred(forwarded, preDefer []byte) map[string]bool
- func PingFromReport(r components.KeepAliveReport) accountant.Ping
- func PingKey(session, threadID string) string
- func PingSavings(r components.KeepAliveReport, st PingSink, calls PingCalls) (res accountant.Result, ok bool)
- func Rejected(status int) bool
- func ShouldCompute(status, rounds int, noResult string) (compute bool, reason string)
- func ThreadID(id string) string
- type PingCalls
- type PingLookup
- type PingSink
- type SiblingStore
- type TierStore
Constants ¶
const ( BaseTTL = modelinfo.AnthropicCacheTTL5m OneHourTTL = modelinfo.AnthropicCacheTTL1h )
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).
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.
Variables ¶
This section is empty.
Functions ¶
func BilledBody ¶
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 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 ¶
DeferredNames is the set of names of the definitions the body defers.
func DeferredStub ¶
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 ¶
IsStub says whether the tool at i of the billed body is a deferred stub: a bare name and the defer_loading mark.
func NoResultWhy ¶
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 ¶
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 ¶
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 ¶
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 ¶
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).
Types ¶
type PingCalls ¶
type PingCalls struct {
Ops func(accountant.Ping, accountant.Billing) (accountant.RequestOps, accountant.PingFacts)
Standalone func(accountant.RequestOps) accountant.Result
}
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 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 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