engine

package
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 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 engine is the implementation of package accountant, which re-exports its public names. It prices context operations in tokens for each billing tier.

Context operators report what they changed as facts (RequestOps, Operation). Compute turns those facts and the provider's cache state into tokens. The host turns tokens into money.

The module imports only the standard library, so any host and any other AI framework can use it (docs/spec.md R3, docs/design.md D7). boundary_test.go in the module root enforces that.

Implementation decisions

The design leaves some rules open. This implementation decides them as follows. Each one is the simplest rule that the design allows.

  1. Tokens from bytes. A Size is bytes (§4.2 rule 7), or tokens when the host sets Size.Tokens: those are used as they are and are not Estimated. The ratio is the billed prompt tokens (input + cache read + cache write) divided by the bytes of the forwarded body, because the billed tokens bill the forwarded body (§5.3). Base64 media (PosHash.Media, Size.MediaBytes) and opaque bytes such as thinking signatures (PosHash.Opaque, Size.OpaqueBytes) are left out of the ratio and priced at a fixed 250 bytes a token. A thinking block the host counted (NewBodyCounted, PosHash.OpaqueTokens, Size.OpaqueTokens) is priced at its count instead (design D16). Every priced rewrite that converts bytes and every effect that uses the ratio is Estimated.
  2. No usage. A response with no usage prices nothing (§8): every operation goes to Unpriced with ReasonNoUsage. The fixed fallback ratio of §4.2 rule 7 is not used.
  3. Extents from usage. The provider reports token counts, not positions. The read extent is the last candidate position whose prefix, converted with the ratio, fits in Usage.CacheRead, with a tolerance of one read step (EntryFacts.Provider.ReadGranularity, default 128) tokens plus 2%. The candidates are the breakpoints of this and the previous request and the previous extent; with no forwarded breakpoint in this request, every position. The extent this request leaves cached (Fingerprint.Cached) is found the same way from CacheRead + CacheWrite, plus Input when this request has no forwarded breakpoint and its whole prompt (Input + CacheRead + CacheWrite) reaches EntryFacts.MinCacheable, because the provider then caches the whole prompt it processed. A shorter prompt is not cached.
  4. The end of a change (§11 question 12). An active rewrite ends when a later splice removes its position, when the client body first differs from the previous one at or before its position (a client edit or compaction, §4.3), or when a valid rewrite or setting with the same ChangeID is reported again (that one replaces it: observe to enforce, §4.6). A spend, or a malformed report, with that ChangeID does not replace it. An active setting has no position and stays until it is replaced. A restore does not bring an ended change back.
  5. Pipeline order of an active and a reported operation. The library cannot see it. It reads it from the sizes: when a splicing operation's SizeBefore equals the client bytes of the range it removed, it saw the original content, so it ran first and the active changes inside have ended. Otherwise they ran before it and keep their credit (§4.5 table). The guess is made once, on the request that reports the splice; while both stay active the result holds. A wrong guess fails the sum check. A DryRun or malformed splice changed nothing upstream, so it moves no position.
  6. Active operations are stored in client space, and are applied before the reported ones in pipeline order. Result.Ops lists the reported ones first, then the active ones (§6.3).
  7. B* (§5.1) is the last candidate at or before x = min(prevCachedExtent, clientFirstDiff - 1), or the end of prevCachedExtent when the usage read all of it (the hashes then moved with no change in content, #21), where x is first snapped down to this request's last client breakpoint at or before it, unless a breakpoint of this request is at or after x (the provider reads only from a breakpoint). The candidates are the previous extent and the client breakpoints of this and the previous request. prevCachedExtent stops at the previous client's last breakpoint when a mark the host added wrote the part past it: the client body has no entry there (clientExtent, #52). The row-4 prediction snaps the same way, with the forwarded breakpoints. With no client breakpoint in this request every position is a breakpoint, so B* = x. With no forwarded breakpoint in this request, extent tries every position (no candidate list; see decision 3). The 128-token rounding of older OpenAI models is absorbed by the extent tolerance. The minimum cacheable length (EntryFacts.MinCacheable) turns a write into input when no breakpoint at or after the content reaches it. A usage with no cache tokens and some input does the same for the forwarded body (§5.1, §6.2).
  8. A break moves the forwarded tokens after the read extent, up to B* as forwarded, from read to write, at the TTL of the first forwarded breakpoint at or after B* that reaches the minimum cacheable length (5m when there is none). With no forwarded breakpoint, or on an uncacheable request (§5.1), the moved tokens are input. A setting break (§5.2 row 3) starts at the last candidate before the earliest SettingChange.At; with no At it starts at the read and adds penalty_unknown. Row 3 and row 4 need the read to be below the prediction by more than the tolerance of decision 3.
  9. Phase. The clock judges the entry the previous request wrote: each breakpoint of that request has its own TTL, and the phase is hot when any part is alive (accountant#40, #41). With no previous fingerprint, no TTL, no cached extent inside the TTL, or a gap past a minimum or unknown lifetime with no ping, the phase is unknown and penalty_unknown is added (§6.4); a read in the usage then makes it hot up to the read extent, with no rescue. The cold expiry adds an empty break (§5.2 row 5). Three rules let the usage or the thread tree beat the clock (accountant#16): a request whose At is before the stored fingerprint is unknown and does not replace it; a billed CacheRead that covers the prefix of a previous breakpoint makes the phase hot at any gap; and a thread with a Parent and no history of its own is seeded from the parent's fingerprint and cache when the gap is within the TTL of the parent's entry, the model is the same and its body keeps the parent's cached extent.
  10. A rescue (§4.4) needs a ping after the previous request, a request gap past an exact or minimum TTL, an entry gap inside it, and a read in the usage. What the request wrote does not enter the rule (#9). Its tokens are the smaller of the ping's read (converted with the ratio) and Usage.CacheRead, less the prefix EntryFacts.SharedWarm names (R54: a sibling thread kept it warm), at the TTL of EntryFacts.TTL.
  11. A spend is never priced in tokens: its Call is passed through (D4). A setting is not priced (R50); it only gives its ChangeID to a break. ComputeStandalone marks any operation that is not a spend as ReasonNotSpend.
  12. The end of an in-place change is inferred (§11 question 12): the forwarded item at its position has the client item's size again (cumulative hashes cannot be compared when another change sits earlier), or a splice or a client edit removed the position. A head-TTL change is priced as the ttlPremium and ttlRescue effects. Conservation is checked against the bill with a tolerance of the rounding plus one token.

Not implemented

These parts of the design are not implemented. Compute adds no figure for them. Compute does not recover from a panic: it leaves the ThreadState unchanged, and the host wraps the call to fail open.

  • Result.Interaction beyond the exact case (§6.2). Compute reports it only for a saved span at or before the ping's extent that the ops book at the read tier, and that the ping read (the change is new on this request). A change applied on the previous request books its span at the write tier. Any other case adds zero.
  • Checks 2 (order) and 5 (attribution) of §6.5 are reserved numbers, not checks. Attribution holds by construction: a break only takes the ChangeID of an operation of the same request.
  • The 20-block lookback (§5.1), and the long-context tier.
  • MessageSplice moves message positions only. A rewrite that removes or adds whole tools or system blocks moves no later position in its section (§4.3 gives no splice for them).

Index

Constants

View Source
const (
	ReasonEndRequestMissing = "end_request_missing"
	ReasonPingResultUnknown = "ping_result_unknown" // a spend whose call has no usage: the host never read a response (§6.3)
	ReasonUnknownKind       = "unknown_kind"
	ReasonNegativeSize      = "negative_size"
	ReasonPenaltyUnknown    = "penalty_unknown" // the boundary is unknown, so no break penalty was charged (§6.4)
	ReasonNoUsage           = "no_usage"        // the response had no usage: nothing is priced (§8)
	ReasonNotSpend          = "not_spend"       // a standalone RequestOps holds only spend operations (§6.1)
	ReasonBadUsage          = "bad_usage"       // a usage count is negative: nothing is priced (§6.5, check 8)
	ReasonRatioRange        = "ratio_range"     // tokens per byte is outside the range: nothing is priced (§6.5, check 9)
	ReasonMediaUnseen       = "media_unseen"    // tokens per byte is too high and the body holds media that its bytes do not price: nothing is priced (§6.5, check 9)
	ReasonMediaTokens       = "media_tokens"    // the operation covers media, and the bill is below the media price: only this operation is unpriced (§6.5, check 11)
	ReasonBreakpoints       = "breakpoints"     // more than 4 breakpoints, or an unknown TTL: nothing is priced (§6.5, check 10)
	ReasonSizeRange         = "size_range"      // an operation reports more bytes than the client body holds: that operation is not priced (§6.5, check 13)
)

Machine-stable reasons in Result.Unpriced.

View Source
const (
	CheckSum          = "sum"
	CheckUniqueChange = "unique_change"
	CheckSpans        = "spans"
	CheckConservation = "conservation"
	CheckSharedWarm   = "shared_warm"
	CheckBadUsage     = ReasonBadUsage
	CheckRatioRange   = ReasonRatioRange
	CheckBreakpoints  = ReasonBreakpoints
	CheckMediaUnseen  = ReasonMediaUnseen
	CheckMediaTokens  = ReasonMediaTokens
	CheckSizeTokens   = "size_tokens"
	CheckSizeRange    = ReasonSizeRange
	CheckOpaqueTokens = "opaque_tokens"
)

The names of the checks in CheckFailure.Check (§6.5). A host that switches on a check uses these. The five that equal a Reason are the same string by design (§6.5: the check name equals the reason).

View Source
const (
	UnitBytes  = "bytes"
	UnitTokens = "tokens"
)

The units of CheckFailure.Unit.

View Source
const (
	KindRewrite Kind = "rewrite"
	KindSpend   Kind = "spend"
	KindSetting Kind = "setting"

	PhaseHot     CachePhase = "hot"
	PhaseCold    CachePhase = "cold"
	PhaseUnknown CachePhase = "unknown"

	LifetimeExact   LifetimeKind = "exact"
	LifetimeMinimum LifetimeKind = "minimum"
	LifetimeUnknown LifetimeKind = "unknown"

	BillingAPI          BillingMode = "api"
	BillingSubscription BillingMode = "subscription"
	BillingUnknown      BillingMode = "unknown"

	SectionTools    Section = "tools"
	SectionSystem   Section = "system"
	SectionMessages Section = "messages"
)
View Source
const (
	DirSaved = "saved"
	DirAdded = "added"
)

Direction of a USDLine.

View Source
const (
	WithheldCheckSum          = "check_sum"           // the sum check failed
	WithheldCheckUniqueChange = "check_unique_change" // two operations share a ChangeID
	WithheldCheckSpans        = "check_spans"         // an operation's spans do not add up to its sizes
	WithheldCheckOther        = "check_other"         // a fatal check with no reason of its own
	WithheldUnpriced          = "unpriced"            // an operation, a cache effect or the request is unpriced, for a reason other than penalty_unknown
	WithheldImplausibleSize   = "implausible_size"    // the operations saved more message tokens than the request's messages had plus what they caused
)

The reasons Withhold returns. A host shows them as they are, so every host names a gate the same way.

View Source
const PingOperator = "keeper"

PingOperator is PingOps's Operation.Operator: the keep-alive ping's spend. It has no host prefix, because the library sets it itself, not a host (contrast Operation.Operator's own doc, "a host-chosen name"). Exported so a host matches it against a computed result's own operations to recognize which one is the ping's spend, instead of hardcoding the literal.

View Source
const RulesVersion = 2

RulesVersion is the version of the accountant rules (R46). Result.Version and RemovalFigure.Version carry it. It is 2: the cache split effect was removed, so a request with a cache-split item prices differently (see design §6.6). The Ratio API did not change it: the Ratio path is opt-in, and a nil Ratio changes no figure.

Variables

This section is empty.

Functions

func AvoidedMissesUSD added in v0.11.0

func AvoidedMissesUSD(n int64, missUSD float64) float64

AvoidedMissesUSD is the dollars saved when n cache misses do not happen: n x missUSD. It is never negative, so a bad miss figure or a bad count books no loss.

func HeadLifetimeOneHour added in v0.17.0

func HeadLifetimeOneHour(cacheWrite, cacheWrite1h int, prev bool) bool

HeadLifetimeOneHour reports whether a cache write billed its HEAD at the one-hour tier, from cacheWrite (the tokens the response wrote, as the provider reports them) and cacheWrite1h (the subset of cacheWrite billed at the one-hour tier, never an addition to it, matching Usage.CacheWrite1h's own doc). On a write, this is the same test HeadTier uses (CacheWrite1h > 0); if this rule ever needs to change, change that one with it. A write is sequential -- breakpoints apply from the start of the context -- so a write that mixes a one-hour breakpoint with a five-minute one has a one-hour HEAD and a five-minute tail: the tokens before the later breakpoint, which the next request that reads this entry reads first, were written at one hour regardless of what the tail got. So cacheWrite1h > 0 is enough, not cacheWrite1h == cacheWrite.

A response that wrote nothing (cacheWrite == 0) has no tier of its own to report: it answers prev, the lifetime the host itself remembers from the thread's last write, or true when the host has no earlier write to remember (a read-only turn before any write keeps the asked tier). The host decides what prev means; this function only applies the rule once cacheWrite and cacheWrite1h are known.

A host uses this, together with its own memory of the thread's last write, to decide what to pass Request.LowerTTL: HeadLifetimeOneHour(cacheWrite, cacheWrite1h, prev) == false means a one-hour ask billed at five minutes, so the host calls LowerTTL(5 * time.Minute).

func LatePingCost added in v0.11.0

func LatePingCost(in LatePingInput, p SizedPricer) (usd float64, estimated bool)

LatePingCost is the dollars of a ping that arrives too late:

Prefix x write + FreshInput x input + Output x output

It is a RequestCost with the prefix as a write, so it follows the same stored-bill rule: the prefix is priced at the 5-minute rate, and at the 1-hour tier (OneHour) it pays the premium on top. Every rate is at PromptTokens, or at Prefix + FreshInput when it is 0 or less. A negative count counts as 0.

A ping is a write here, so it follows the rule of MissCost: a write rate of 0 or less is unknown. The result is then 0 and estimated is true. With OneHour, the 1-hour rate is checked too. A ping with no prefix writes nothing and has no such check.

func MissCost added in v0.11.0

func MissCost(in MissInput, p SizedPricer) (usd float64, estimated bool)

MissCost is the extra dollars of one cache miss over a hit: the prefix at the write rate minus the prefix at the read rate. It is never negative. When PromptTokens is 0 or less, the tier is the one of a prompt of Prefix tokens. The write rate is the 5-minute rate, or the 1-hour rate when OneHour is set. Both rates are the rates at PromptTokens.

A write rate of 0 or less is unknown: the result is 0 and estimated is true. A write rate that is not above the read rate gives 0, a miss that costs nothing extra.

With HeadTokens above 0 the entry is mixed. While HeadAlive is set, the cost is the tail only: (Prefix - HeadTokens) x (write5m - read). Otherwise it is the tail at that rate plus the head at the 1-hour rate: HeadTokens x (write1h - read). Each product is rounded on its own, and the head is added last. A write rate of 0 or less for a tier that the cost needs is unknown: the result is 0 and estimated is true. A mixed entry with no tail costs 0 while the head lives, and makes no price call.

func OpaqueKey added in v0.2.0

func OpaqueKey(s string) uint64

OpaqueKey is the key of one opaque string (a thinking signature, or the data of a redacted_thinking block) in the host's table of counts: the 64-bit FNV-1a hash of the string, as JSON decodes it. A host stores a count under the key of the string it read in a response, and NewBodyCounted looks it up under the key of the same string in a later request (design D16).

func PingCost added in v0.11.0

func PingCost(in PingInput, p SizedPricer) (usd float64, estimated bool)

PingCost is the dollars of one keep-alive ping:

Prefix x read + FreshInput x input + Output x output

Every rate is the rate at the prompt size of the ping, PromptTokens, or Prefix + FreshInput when it is 0 or less, so a ping near a price line gets the tier its request gets. A negative count counts as 0.

A rate of 0 is a free rate, as in SizedPricer: it adds 0. A model with no rates gives 0 with estimated true, because the pricer must mark an unknown model as an estimate. The host reads 0 with estimated true as "unknown", never as free. A rate that the pricer marks as an estimate makes estimated true. A tier with no tokens makes no price call, so it cannot mark the cost estimated.

Each product is rounded on its own, with an explicit float64 conversion, as in RequestCost: no CPU fuses a multiply and an add, so every cost function of this file gives the same bits on every CPU.

func PingOps added in v0.1.1

func PingOps(p Ping, b Billing) (RequestOps, PingFacts)

PingOps turns a ping into a RequestOps with one spend, and returns the facts for the thread's next real request. Price the RequestOps with ComputeStandalone. The thread "" is the primary thread and becomes "main". The ChangeID is PingWindowID(thread, window start), and PingFacts.PingWindow is the same string, so the ping's cost and the rescue it earns land on one change (design §4.4).

func PingWindowID added in v0.4.0

func PingWindowID(thread string, start time.Time) string

PingWindowID gives the id of the keep-alive window that starts at start on thread: "ka:" + thread + ":" + start (RFC 3339, UTC). The thread "" becomes "main". This is the one rule for the id. PingOps uses it for the ChangeID and PingFacts.PingWindow, and a host uses it for a ping it does not send (for example a refused ping), so every id for one window is the same string. It does not check start: a zero start gives "ka:<thread>:0001-01-01T00:00:00Z", as PingOps does.

func RequestCost added in v0.11.0

func RequestCost(in RequestCostInput, p SizedPricer) (usd float64, estimated bool)

RequestCost is the dollars of one billed request, and it gives the same bits as the bill that a host stores for the request:

Input x input + CacheRead x read + CacheWrite x write5m + Output x output + CacheWrite1h x premium

premium is the 1-hour write rate minus the 5-minute write rate, and only when it is above 0. So every write token is priced at the 5-minute rate, and a token billed at the 1-hour tier pays the premium on top. A 1-hour rate below the 5-minute rate has no premium: those tokens stay at the 5-minute rate. That is the rule of the stored bill. Every rate is the rate at PromptTokens. When it is 0 or less, it is the rate at the prompt Input + CacheRead + CacheWrite.

Each product is rounded on its own, with an explicit float64 conversion, and the terms are added in the order above. A CPU that fuses a multiply and an add (FMA, as arm64 does) would otherwise give another last bit for the same request, so a host's stored bill and this figure would differ by one unit in the last place on some requests (#1128 of the host).

A tier with no tokens makes no price call, so it cannot mark the cost estimated. A negative count counts as 0. CacheWrite1h counts only as far as CacheWrite: a larger value is clamped to CacheWrite. A model that the pricer does not know gives the pricer's dollars and estimated true.

func SplitOpaqueTokens added in v0.2.0

func SplitOpaqueTokens(opaques []string, tokens int) []int

SplitOpaqueTokens splits the thinking tokens of one response between the opaque strings it made, in proportion to their lengths (design D16). Anthropic reports one count for each response (usage.output_tokens_details.thinking_tokens), so a response with two blocks needs a split. The split is an estimate. The parts add up to tokens exactly: the remainder goes to the largest fractions first, and to the earlier string on a tie. With no tokens, or no strings, every part is 0. When every string is empty, the tokens are split evenly.

func ThreadKey

func ThreadKey(session string, t Thread) string

ThreadKey is the key of a thread's Tracker: the session and the thread ID.

func Withhold added in v0.9.0

func Withhold(res Result) string

Withhold returns the first gate that res fails, or "" when a host may book its savings (design §6.7). A host books no saving for a request with a reason: no saved or caused tokens of an operation, no cache effect and no interaction. The calls of its spends are real cost, so the host still books them.

The gates, in order:

  1. A fatal check (CheckFailure.Fatal). The list of operations or its attribution is wrong. One exception: a sum failure where no applied operation has a span in the section (Claims is 0). There, a change that no operation reported changed the section (a host plugin that rewrites the body and reports nothing, or a change the lost thread state no longer applies). The reported operations of the other sections are still right, so their savings are booked. A sum failure in a section that operations claim (Claims above 0) gates, also when their bytes cancel to Got 0: two operations claim one change, a claim is false, or a reported and an unreported change share it.
  2. An entry in res.Unpriced with a reason other than ReasonPenaltyUnknown, or a cache effect of a kind the library does not know (Figure lists it in USDFigure.Unpriced and books nothing for it). penalty_unknown does not gate: every operation is priced, and the figure is an estimate (§6.4).
  3. The size bound. An operation receives the body the operations before it left: the client body plus what the inserting operations added (check 13). So the operations cannot save more message tokens than the client messages had plus the message tokens they caused. The library measures the client messages itself (Result.MessageTokens), so a host gives no size. The bound adds the SavedMessages and the CausedMessages of each operation that is not DryRun and not a spend, in every tier. Tokens of a tool declaration or of the system are not counted: they are not in the messages, and a deferral removes thousands of them (docs/design.md §6.7). It is tested only when the saved message tokens are above 0.

Types

type BaselineCompaction added in v0.16.0

type BaselineCompaction struct {
	// Point is the compaction point in tokens that applied: the lower of the host's CompactionPoint and
	// Window, whichever the host gave, else the default window of the model.
	Point int
	// Fired is true on the request where the baseline reached the point and compacted.
	Fired bool
	// At is the last client position that the baseline has summarized. nil when the baseline has not
	// compacted yet. A saved span that starts at or before it books no saving.
	At *Position
	// NotBooked is the tokens of saving that this request left out because the span lies in the
	// summarized part, by the byte ratio of the request.
	NotBooked int
}

BaselineCompaction is the record of the baseline's compaction point on one request (R58).

type Billing

type Billing struct {
	Mode BillingMode `json:"mode"`
}

Billing is a fact the host reads from the request's credential, not a price.

func BillingFrom added in v0.3.0

func BillingFrom(h http.Header) Billing

BillingFrom reads the client's upstream credential header and returns the billing mode it implies (accountant design §7.1). It reads only the credential's TYPE: it never returns, stores or logs any part of the credential itself (R2).

Rule, in order:

  1. "x-api-key" present with a non-empty value -> BillingAPI. An API key on this header is always an API key, whatever it contains. An empty value is treated the same as an absent header (falls through to rule 2) rather than as a credential of unknown type, because an empty string carries no credential to classify. When both "x-api-key" and "Authorization" are present and non-empty, "x-api-key" wins and "Authorization" is not read at all.
  2. "Authorization: Bearer <token>" (the scheme matched case-insensitively, and the two separated by any run of whitespace — a client or intermediary may send more than one space or a tab): - an OpenAI API key ("sk-..." that is not an Anthropic OAuth token and is not a JWT, including the project-scoped "sk-proj-..." and Anthropic's own "sk-ant-api..." shape, which is a case of the same "sk-" prefix) -> BillingAPI. - an Anthropic OAuth token from a subscription login ("sk-ant-oat...") or a JWT access token, as a ChatGPT login sends (three dot-separated base64url segments, RFC 7519 §3) -> BillingSubscription. - anything else -> BillingUnknown.
  3. Any other scheme (for example "Authorization: Basic ..."), or no credential at all -> BillingUnknown.

Header names are matched case-insensitively, as HTTP requires. http.Header.Get only canonicalizes the key it is asked for, not the keys already in the map — and a header map built from a non-Go source (an Envoy ext_proc header map, for example) may carry any case — so BillingFrom scans the map itself rather than relying on Get.

Prefix sources: "sk-ant-api" and "sk-ant-oat" are Anthropic's own credential prefixes (the first for an API key, the second for Claude Code's OAuth access token on a subscription login); the bare "sk-" and "sk-proj-" prefixes are OpenAI's API key formats — "sk-ant-api..." is itself an "sk-..." string, so one prefix check covers both API-key shapes. A ChatGPT login sends a JWT, which carries none of those prefixes and is instead recognized by its three-part base64url shape (RFC 7519 §3). None of this is read from the token's payload — only its prefix or gross shape.

type BillingMode

type BillingMode string // api | subscription | unknown

The enums are strings, not integers, so an unknown value from a newer operator survives a decode and can be reported as unpriced (R19).

type Body

type Body struct {
	Start [3]int    `json:"start"`
	Pos   []PosHash `json:"pos"`
	// contains filtered or unexported fields
}

Body lists every position in hash order: tools, then system, then messages. The slice index is the position. Start gives the first index of each section.

func NewBody

func NewBody(tools, system, messages [][]byte) Body

NewBody hashes one body in hash order, so every host builds the same Body for the same bytes. The host calls it for the client body (before BeginRequest) and for the forwarded body (before EndRequest).

func NewBodyCounted added in v0.2.0

func NewBodyCounted(tools, system, messages [][]byte, count OpaqueCount) Body

NewBodyCounted is NewBody with the host's token counts for opaque strings (design D16). For each thinking signature and each redacted_thinking data string it finds, it calls count with the string's OpaqueKey. A known count goes to PosHash.OpaqueCounted and PosHash.OpaqueTokens. A negative count is no count: that block keeps the fixed price. A nil count is NewBody. The hashes and the sizes do not depend on count.

type Breakpoint

type Breakpoint struct {
	Pos Position `json:"pos"`
	TTL string   `json:"ttl"` // "5m" | "1h"
}

Breakpoint is a cache breakpoint in a body.

type CacheEffect

type CacheEffect struct {
	// ID is unique inside the Result: "ce:" + a number.
	ID   string          `json:"id"`
	Kind CacheEffectKind `json:"kind"`
	// ChangeID is the change that caused a break, the keep-alive window of a rescue, or the head
	// entry of a TTL leg. Empty on a break that nobody caused (R31).
	ChangeID string `json:"changeId,omitempty"`
	// From and To are the ends of the prefix range the effect covers. A nil From is the start of the
	// prompt; a nil To is the end of the body. For a break, From is the end of what the provider
	// still read and To is B* (§6.2).
	From *Position `json:"from,omitempty"`
	To   *Position `json:"to,omitempty"`
	// TTL is the lifetime of the entry the effect is about, "5m" or "1h". Set on the TTL kinds.
	TTL string `json:"ttl,omitempty"`
	// Cause says why a break nobody reported happened, when the library can tell. Empty when it
	// cannot: an entry lost early has no visible reason. It changes no figure.
	Cause     CacheEffectCause `json:"cause,omitempty"`
	Saved     TierTokens       `json:"saved"`
	Caused    TierTokens       `json:"caused"`
	Estimated bool             `json:"estimated,omitempty"`
	// InBaseline marks a break that the client body would have had too: a client edit, an expiry,
	// an entry lost early (§5.2 rows 2, 4 and 5), or a model change that no setting operation
	// explains (rows 1, 3 and 4, case 3 of "A model change", accountant#69). It is on the record, but it is not part of the
	// bill difference (§6.3), so a host does not count it. A break that an ended change left behind
	// has no ChangeID and is not InBaseline: it counts.
	InBaseline bool `json:"inBaseline,omitempty"`
}

CacheEffect is a change in how the provider bills content that is already there (§4.4). It changes no content. It is part of the output only: the library finds it by comparing requests (§5), so no operator reports one and the input type has no form for it.

func (CacheEffect) Net added in v0.1.1

func (e CacheEffect) Net() TierTokens

Net is the effect as one signed flow of tokens: Saved minus Caused, tier by tier. A host prices it with its rates and gets the dollar value of the effect with its sign: a break (a cost), a markPremium and a ttlPremium come out negative; a rescue, a markPayback and a ttlRescue positive. The host does not need the sign rule for each kind. A host that sums Net over a Result skips an effect with InBaseline set: the client body would have had that break too, so it is not part of the bill difference (design §5.2, §6.3).

type CacheEffectCause

type CacheEffectCause string

CacheEffectCause is the reason the library can give for a break that no operation reported.

const CauseModelChanged CacheEffectCause = "model_changed"

CauseModelChanged: this request names a different model from the thread's previous one, and the provider keeps a separate cache for each model, so nothing was read. Nobody reported the change, so the break has no ChangeID (R50 says the library does not price the change itself).

type CacheEffectKind

type CacheEffectKind string

CacheEffectKind says what a CacheEffect is. The host needs it to settle the effect: a break goes to the change that caused it, a rescue goes to the keeper by its window.

const (
	EffectBreak       CacheEffectKind = "break"       // a prefix the provider read is written again: a cost
	EffectRescue      CacheEffectKind = "rescue"      // a keep-alive ping kept an entry alive: write becomes read
	EffectTTLPremium  CacheEffectKind = "ttlPremium"  // a breakpoint TTL change, cost leg: on every request that writes the head at 1h
	EffectTTLRescue   CacheEffectKind = "ttlRescue"   // a breakpoint TTL change, read leg: a request reads the 1h entry after the 5m TTL
	EffectMarkPremium CacheEffectKind = "markPremium" // a breakpoint the host added: the new tail is written, not billed as input
	EffectMarkPayback CacheEffectKind = "markPayback" // the next request reads what a host-added breakpoint wrote: input becomes read
)

type CachePhase

type CachePhase string // hot | cold | unknown

The enums are strings, not integers, so an unknown value from a newer operator survives a decode and can be reported as unpriced (R19).

type CacheState

type CacheState struct {
	CachePhase CachePhase `json:"phase,omitempty"`
	Extent     *Position  `json:"extent,omitempty"` // the last position the entry covers; nil when nothing is covered
	TTL        string     `json:"ttl,omitempty"`    // "5m" | "1h": the longest TTL of a breakpoint that wrote the entry; empty when cold or unknown
	// EntryTTL is EntryFacts.TTL of the request that wrote the entry. The next request judges the entry
	// with it, not with its own EntryFacts.TTL, because the entry lives as long as it was written for.
	// Zero when unknown (a state from before this field): the next request's own TTL is used then.
	EntryTTL time.Duration `json:"entryTtl,omitempty"`
}

CacheState is the state of the thread's provider cache entry.

type CallUsage

type CallUsage struct {
	Usage           // input, cache read, cache write (and its 1h part)
	Output  int     `json:"output,omitempty"`  // output tokens, including reasoning or thinking tokens
	CostUSD float64 `json:"costUSD,omitempty"` // the cost the response stated; 0 when it stated none
}

CallUsage is the whole bill of one call, as its response states it. CostUSD is a fact the provider or gateway reported, not a rate of ours (R1, R49).

type CheckFailure

type CheckFailure struct {
	Check    string // one of the Check constants
	Operator string // "" when the check is not about one operator
	Detail   string // numbers only, no content; built from the fields below, with some numbers they do not hold

	Section Section // set for sum and shared_warm only; "" for every other check
	Index   *int    // the position, when the check is about one position (shared_warm)

	Want, WantAfter *int // what the bodies or the bill show; the After value for a check with a before and an after side
	Got, GotAfter   *int // what the operations claim
	// Claims is set for sum only: the number of spans of applied operations in Section. Got is the net
	// of their bytes, so claims that cancel give Got 0. Claims 0 means no applied operation claims the
	// section: only a change that no operation reported moved its bytes.
	Claims *int

	Limit, LimitAfter   *int     // size_range only: the size limit before (after), in bytes
	Tokens, TokensAfter *int     // size_tokens only: the tokens of the span or operation that failed, before (after); only the side that failed is set
	Bytes, BytesAfter   *int     // size_tokens only: its bytes, the same side
	RatioMin, RatioMax  *float64 // size_tokens only: tokens / bytes must be at most RatioMax, and tokens / text bytes (bytes less media and opaque bytes) at least RatioMin
}

CheckFailure is a failed check (§6.5). A failure does not stop pricing, except size_range, which unprices the one operation (§6.5, check 13).

The number fields hold the numbers behind the failure, so a host never parses Detail (docs/events/events.md §6.8.1). A number is nil when the check has no such number; 0 is a real value. Want and Got have the same unit, Unit(), so Want - Got always has a meaning.

func (CheckFailure) Fatal added in v0.1.1

func (c CheckFailure) Fatal() bool

Fatal reports whether this failure means the list of operations or their attribution is wrong: sum, unique_change and spans. The figures of such a request follow whichever operation comes first, or add up to bytes the bodies do not hold, so a host must not show them as measured. Every other check is informational. The library decides this in one place, so a new fatal check gates every host and no host keeps a list of its own.

func (CheckFailure) Unit added in v0.4.0

func (c CheckFailure) Unit() string

Unit is the unit of Want, Got and Limit: UnitBytes, UnitTokens, or "" for a check that has no Want and Got. It depends only on Check, so no host keeps a table of its own.

type CompactionRecord added in v0.1.1

type CompactionRecord struct {
	Trigger CompactionTrigger
	// Ended holds the ChangeID of each change that ended on this request, in pipeline order. A change
	// that was already over is not listed. It can be empty: a compaction before any change.
	Ended []string
}

CompactionRecord is what the library recorded for a client compaction.

type CompactionTrigger added in v0.1.1

type CompactionTrigger string

CompactionTrigger says how a client compaction started, as the host knows it.

const (
	CompactionManual  CompactionTrigger = "manual"  // the user ran /compact
	CompactionAuto    CompactionTrigger = "auto"    // the client compacted by itself
	CompactionUnknown CompactionTrigger = "unknown" // the host saw a compaction and cannot tell which
)

type EntryFacts

type EntryFacts struct {
	TTL time.Duration `json:"ttl"` // lifetime of the entry: 5m or 1h, from the breakpoint that wrote it
	// Lifetime says whether TTL is a proven expiry (exact) or a guaranteed floor (minimum) (R45).
	Lifetime LifetimeKind `json:"lifetime"`
	// The last keep-alive ping of this thread since its previous request: when it started, the
	// extent it read, and the ChangeID of its keep-alive window. Zero values when no ping was sent.
	LastPing   time.Time `json:"lastPing,omitzero"`
	PingRead   *Position `json:"pingRead,omitempty"`
	PingWindow string    `json:"pingWindow,omitempty"`
	// PingUsage is the last ping's billed usage. When PingRead is nil, the library derives PingRead
	// from it: a ping replays the previous request's forwarded body, so the extent its CacheRead
	// covers in that body, at the ping's own bytes-to-tokens ratio, is what it read (§4.4). A host
	// that knows PingRead sets PingRead; PingUsage is for a host that only has the ping's usage.
	PingUsage *Usage `json:"pingUsage,omitempty"`
	// PingTTL is the TTL that the last ping asked on its breakpoints: 5m or 1h. The library reads it only when
	// Provider.ReadSetsTTL is true and the ping read a part of the entry. 0 = not known: the library then
	// judges the entry by the breakpoints of the previous request alone, as before.
	PingTTL time.Duration `json:"pingTtl,omitempty"`
	// SharedWarm is the longest prefix of this request's forwarded body that another thread of the same
	// session read or wrote inside the TTL before this request. That prefix was warm without the ping,
	// so a rescue does not credit it. Nil when no other thread touched the entry.
	SharedWarm *Position `json:"sharedWarm,omitempty"`
	// MinCacheable is the model's minimum cacheable length in tokens (512, 1024, 2048 or 4096). A write at a
	// breakpoint whose prefix is shorter is priced as input (§5.1). 0 = not set: no minimum applies.
	MinCacheable int `json:"minCacheable,omitempty"`
	// Provider describes the provider facts that differ by provider and model. The zero value keeps the
	// Anthropic behaviour.
	Provider Provider `json:"provider,omitzero"`
}

EntryFacts are the facts that decide the cache phase and that only the host knows. The host passes them in EndRequest. The library finds the two gaps itself (§5.2), from ThreadState.PrevPrint.At, LastPing and the time of the request.

type FigureInput added in v0.9.0

type FigureInput struct {
	Model string
	At    time.Time
	// Billed is the usage the provider billed. The size of the request sent is Input + CacheRead +
	// CacheWrite. The size without the operations derives from it.
	Billed Usage
	// Output is the output tokens the provider billed. 0 means the host does not give it, and the output
	// tier has no re-rate. Output never counts toward the prompt size.
	Output int
	Result Result
	// Unsized says that the host's rates do not depend on the prompt size. [Figure] then derives no
	// size, passes 0 to the pricer, and books no re-rate.
	Unsized bool
	// Endpoint is the upstream endpoint the request was billed on, for a host whose rates are keyed by
	// endpoint. [Figure] passes it to the pricer in [RequestContext].Endpoint, unchanged. "" (the
	// default) means the model alone decides the rate, exactly as before.
	Endpoint string
}

FigureInput is what Figure needs besides the pricer: the billed usage of the request and its Result.

type Fingerprint

type Fingerprint struct {
	Thread                                  string
	Model                                   string    // the model the request was sent for; "" when the host did not say
	ModelKey                                string    // RequestMeta.ModelKey; "" when the host gave none
	At                                      time.Time // the start of the request; the request gap is measured from it (§5.2)
	Client                                  Body      // client body, before any plugin
	Forwarded                               Body      // body as sent upstream
	ClientBreakpoints, ForwardedBreakpoints []Breakpoint
	Cached                                  Position // extent cached after its response, in forwarded space
	// contains filtered or unexported fields
}

Fingerprint is the most recent request of one thread (§5.1). The library builds it inside Compute, because Cached comes from the usage, which arrives after the response.

type Kind

type Kind string // rewrite | spend | setting (a request parameter that changes the cost or the cache and that the body does not show)

The enums are strings, not integers, so an unknown value from a newer operator survives a decode and can be reported as unpriced (R19).

type LatePingInput added in v0.11.0

type LatePingInput struct {
	PingInput
	// OneHour says that the entry was written at the 1-hour tier, so its rewrite is too.
	OneHour bool
}

LatePingInput is a keep-alive ping that fires after its entry expired. It writes the prefix again, it does not read it.

type LifetimeKind

type LifetimeKind string // exact | minimum | unknown

The enums are strings, not integers, so an unknown value from a newer operator survives a decode and can be reported as unpriced (R19).

type MessageSplice

type MessageSplice struct {
	At       int `json:"at"`
	Removed  int `json:"removed"`
	Inserted int `json:"inserted"`
}

MessageSplice describes a change to the message list.

type MissInput added in v0.11.0

type MissInput struct {
	Model string
	At    time.Time
	// Prefix is the cached tokens that the miss writes again.
	Prefix int64
	// PromptTokens is the prompt size that picks the price tier. 0 or less means Prefix.
	PromptTokens int64
	// OneHour says that the entry was written at the 1-hour tier, so its rewrite is too.
	OneHour bool
	// HeadTokens is the part of Prefix that sits at the 1-hour tier in a mixed entry (a head-TTL thread: a
	// 1-hour head, then a 5-minute tail). 0 or less means no head: the whole Prefix is one entry, as before.
	// A value above Prefix counts as Prefix. The tail is Prefix - HeadTokens.
	HeadTokens int64
	// HeadAlive says that the 1-hour head still lives. It counts only when HeadTokens is above 0.
	// While the head lives, a miss rewrites only the tail. After the head expires, a miss rewrites the head
	// at the 1-hour rate and the tail at the 5-minute rate. OneHour does not count when HeadTokens is above 0.
	HeadAlive bool
	// Endpoint is the upstream endpoint the request was billed on, for a host whose rates are keyed by
	// endpoint. It is passed to the pricer in [RequestContext].Endpoint, unchanged. "" (the default)
	// means the model alone decides the rate, as before.
	Endpoint string
}

MissInput is one cache miss on a prefix.

type ModelCall

type ModelCall struct {
	Host     string            `json:"host,omitempty"`
	Model    string            `json:"model"`
	Params   map[string]string `json:"params,omitempty"`   // the call's own settings: effort, thinking, ...
	Usage    CallUsage         `json:"usage"`              // everything the call's response bills, as billed
	Detached bool              `json:"detached,omitempty"` // finished after the request it served was answered
}

ModelCall is one upstream call an operator or the keeper made. The host's model client fills it from the call's own response, so the usage is what the provider billed.

type OpaqueCount added in v0.2.0

type OpaqueCount func(key uint64) (tokens int, ok bool)

OpaqueCount looks up the host's token count for one opaque string, by its OpaqueKey. ok false means the host has no count for it, and the library uses the fixed price.

type Operation

type Operation struct {
	ID       string `json:"id,omitempty"` // unique inside the request only; across requests, use ChangeID (R6)
	Kind     Kind   `json:"kind"`
	Operator string `json:"operator,omitempty"` // a host-chosen name, for example "acme.mask" or "tool-prune" -- or, for a ping's own spend, PingOperator, which the library sets itself
	DryRun   bool   `json:"dryRun,omitempty"`   // set by the framework: computed but not sent (R12)

	At         Position `json:"at"`              // first position touched, in this operator's output
	Spans      []Span   `json:"spans,omitempty"` // every touched range, when the change is not contiguous; nil otherwise
	SizeBefore Size     `json:"sizeBefore"`      // what the operator received over the touched ranges; the sum over Spans
	SizeAfter  Size     `json:"sizeAfter"`       // what it sent on over the same ranges

	ChangeID string `json:"changeId,omitempty"` // the same on every request that carries this change

	// kind = spend
	Call *ModelCall `json:"call,omitempty"`

	// kind = setting: the key is the setting name (model, host, or a key of Params).
	Settings map[string]SettingChange `json:"settings,omitempty"`

	// a change to the message list, for mapping positions
	MessageSplice *MessageSplice `json:"messageSplice,omitempty"`
}

Operation is one change unit a context operator reports.

type Ping added in v0.1.1

type Ping struct {
	Session, ThreadID, Model, Host string
	Usage                          CallUsage
	At                             time.Time // when the ping started
	Window                         time.Time // the start of the idle gap the ping served
	// TTL is the TTL the ping asked on its breakpoints (5m or 1h). 0 = not known.
	TTL time.Duration
}

Ping is a keep-alive ping in the library's own terms, so the library does not import a host type. The host maps its own report onto this (wiring document, W4.6).

type PingFacts added in v0.1.1

type PingFacts struct {
	LastPing   time.Time
	PingWindow string
	PingUsage  Usage
	PingTTL    time.Duration // the TTL the ping asked; 0 = not known (EntryFacts.PingTTL)
}

PingFacts are what the thread's next real request needs in EntryFacts: LastPing, PingWindow, PingUsage and PingTTL. The host keeps the last one for each thread, passes it at that request's EndRequest, then clears it. With PingUsage set and PingRead nil, the library derives the extent the ping read (EntryFacts.PingUsage).

func (PingFacts) Apply added in v0.1.1

func (p PingFacts) Apply(f *EntryFacts)

Apply copies the facts into f. A ping that billed nothing leaves PingUsage nil.

type PingInput added in v0.11.0

type PingInput struct {
	Model string
	At    time.Time
	// Prefix is the cached tokens the ping reads.
	Prefix int64
	// FreshInput is the fresh input tokens the ping sends past the prefix.
	FreshInput int64
	// Output is the output tokens the ping bills.
	Output int64
	// PromptTokens is the prompt size that picks the price tier. 0 or less means Prefix + FreshInput. A host
	// that prices the read of a prefix inside a larger request gives that request's size.
	PromptTokens int64
	// Endpoint is the upstream endpoint the ping was billed on, for a host whose rates are keyed by
	// endpoint. It is passed to the pricer in [RequestContext].Endpoint, unchanged. "" (the default)
	// means the model alone decides the rate, as before.
	Endpoint string
}

PingInput is one keep-alive ping: a cache read of the prefix, the fresh input the ping carries past the prefix, and the output it bills. The host owns the shape of its ping body, so the host gives FreshInput and Output. The library only prices them.

type PosHash

type PosHash struct {
	Hash  uint64 `json:"hash"` // cumulative: equal hashes mean an equal prefix up to this position
	Bytes int32  `json:"bytes"`
	// Media is the part of Bytes that is a base64 image or document block. NewBody finds it. The
	// token ratio leaves it out (§4.2 rule 7). It is not in the hash.
	Media int32 `json:"media,omitempty"`
	// Opaque is the part of Bytes that is an opaque string the client sends back and the provider
	// bills as few tokens: a thinking signature. NewBody finds it. The token ratio leaves it out, and it
	// has a fixed price of 1 token for each 250 bytes (§4.2 rule 7). It is not in the hash.
	Opaque int32 `json:"opaque,omitempty"`
	// OpaqueCounted is the part of Opaque whose tokens the host knows, and OpaqueTokens is those tokens:
	// the thinking tokens of the response that made each block (design D16). NewBodyCounted sets both.
	// The library prices the counted bytes at OpaqueTokens and the rest of Opaque at the fixed price.
	// OpaqueCounted 0 means no count, whatever OpaqueTokens says. Neither is in the hash.
	OpaqueCounted int32 `json:"opaqueCounted,omitempty"`
	OpaqueTokens  int32 `json:"opaqueTokens,omitempty"`
	// Unseen counts the media blocks of the position whose tokens the bytes do not show: an image or a
	// document given by url or by file id (no bytes at all), and a PDF (billed by page, not by byte).
	// NewBody finds them. They change no price. Only the check of the token ratio reads them, to name its
	// failure (media_unseen, §6.5 check 9). It is not in the hash, and Snapshot does not keep it: check 9
	// reads only the forwarded body of the current request, so a restored body with Unseen 0 is enough.
	Unseen int32 `json:"unseen,omitempty"`
}

PosHash holds hashes and sizes only (R2).

type Position

type Position struct {
	Section Section `json:"section"`
	Index   int     `json:"index"` // block or message index in that section
}

Position is a place in the prompt. The provider hashes tools, then system, then messages.

func SharedWarmFrom added in v0.1.1

func SharedWarmFrom(fwd Body, siblings []Sibling) *Position

SharedWarmFrom returns the value of EntryFacts.SharedWarm for a request that forwarded fwd: the last position of fwd that a sibling kept warm, or nil when none did (R54).

The host decides which siblings count (inside the TTL, another thread, not later than this request). This function decides only where the shared prefix ends. The provider caches at breakpoints, so a prefix counts as warm up to the last breakpoint the sibling sent inside the prefix both bodies share. A shared prefix with no breakpoint of the sibling in it was not kept warm. A sibling whose body has no breakpoint (automatic prefix caching, for example OpenAI) is the exception: with no breakpoint every position counts as one (design §5.1, §6.2), so the whole shared prefix was warm. With many siblings, the one that reaches furthest wins.

It is pure: it reads the bodies and changes nothing.

type PricedOp

type PricedOp struct {
	OpID     string
	Kind     Kind // copied from the operation: rewrite, spend or setting
	Operator string
	ChangeID string
	DryRun   bool
	Saved    TierTokens // tokens the provider did not bill, by tier; never negative
	Caused   TierTokens // tokens the provider billed because of this operation; never negative
	// SavedMessages and CausedMessages are the size of the spans in the messages section, counted at the
	// request's text ratio, as MessageTokens is, and opaque bytes at the body's own price. They use no host
	// count (Size.Tokens, Size.OpaqueTokens), so they can differ from the messages part of Saved and Caused.
	// The tier split of CausedMessages can differ from Caused too (Caused books CacheRead for content the
	// previous request cached). Only the sum is meaningful: the bound uses it. A removed tool declaration
	// is in neither.
	// [Withhold] compares them with MessageTokens, so a request that removes many tool declarations is not
	// withheld for their size, and dense content is not withheld for its density (§6.7).
	SavedMessages  TierTokens
	CausedMessages TierTokens
	Call           *ModelCall // spend only: copied from the operation, for the host to price
	Estimated      bool
}

PricedOp is one operation in tokens for each tier.

type Provider added in v0.1.1

type Provider struct {
	// ReadGranularity is the step in tokens of the cached count the provider reports (OpenAI before
	// GPT-5.6 rounds down to a multiple of 128). The extent search allows one step plus 2%. 0 = 128.
	// Use 1 for a provider that reports the exact count. A negative value counts as 0.
	ReadGranularity int `json:"readGranularity,omitempty"`
	// TTLs narrows the breakpoint TTL strings the model accepts, besides the empty one. It may list
	// "5m" and "1h" only: the engine prices no other lifetime, so a string outside them is refused by
	// check "breakpoints" even if listed. A breakpoint with an unlisted TTL fails that check.
	// Nil = "5m" and "1h". An empty non-nil list allows only the empty TTL.
	TTLs []string `json:"ttls,omitempty"`
	// StorageBilled says the provider bills the storage of a cache entry by token and hour (Gemini
	// explicit caching). Result.StorageTokens then holds the tokens the request wrote. The host
	// multiplies it by the hours it keeps the cache and by its rate: the library knows neither.
	StorageBilled bool `json:"storageBilled,omitempty"`
	// ReadSetsTTL says a read sets the TTL of the part it reads, to the TTL of the reading request (AWS Bedrock,
	// measured 2026-11-19). A read at 1h keeps the entry for 1 hour, and a later read at 5m sets it back to 5
	// minutes. The reading request is a keep-alive ping: its TTL is EntryFacts.PingTTL. A real request already
	// sets the TTL of its parts through its own breakpoints. False = a part keeps the TTL of the breakpoint
	// that wrote it, and EntryFacts.PingTTL is ignored. Anthropic first-party is not measured: keep it false there.
	ReadSetsTTL bool `json:"readSetsTTL,omitempty"`
}

Provider is the provider profile of a request. Every field has a zero value that keeps today's behaviour.

type Ratio added in v0.12.0

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

Ratio is the request ratio that [Compute] used: the provider's billed tokens of the forwarded text, against its bytes (§5.3). A host that prices bytes of text outside a Result, such as a removed tool declaration, converts them with it. It wraps the one engine ratio: there is no second copy of the rule. The zero value converts every byte to 0 tokens.

func NewRatio added in v0.12.0

func NewRatio(billed int, forwarded Body) Ratio

NewRatio builds the ratio of a body that the provider billed for billed prompt tokens (fresh input plus cache read plus cache write). It is the ratio Compute builds for the request.

func RatioFromText added in v0.12.0

func RatioFromText(tokens, bytes int, capped bool) Ratio

RatioFromText rebuilds a text ratio from the two counts that Ratio.Text returned and the flag that Ratio.Capped returned, for example from a stored row. Only the text conversion is rebuilt: media and opaque bytes are not priced by it.

A count that is negative or above maxRatioCount (2^31-1, far above any request) is not a ratio: the result converts every byte to 0 tokens and is marked capped, so a figure that uses it is an estimate. This keeps the integer math of Ratio.Tokens inside int64.

func (Ratio) Capped added in v0.12.0

func (x Ratio) Capped() bool

Capped says that the media price was above the bill and was cut to fit it (§5.3). The text ratio is then at its floor, so a figure that uses it is the lowest it can be.

func (Ratio) InRange added in v0.12.0

func (x Ratio) InRange() bool

InRange says whether the text ratio is inside the limits of check 9 (§6.5): from 0.05 to 2.0 tokens a byte. A host that builds a Ratio before Compute (with NewRatio) uses it to keep only a ratio that Compute would accept. Compute sets Result.Ratio only for such a ratio, so a Result's ratio is always in range.

func (Ratio) Text added in v0.12.0

func (x Ratio) Text() (tokens, bytes int)

Text returns the tokens and the bytes of the text of the forwarded body, after the media and the opaque bytes were priced apart.

func (Ratio) Tokens added in v0.12.0

func (x Ratio) Tokens(textBytes int) int

Tokens converts bytes of text to tokens with the request ratio, with the same integer math as Compute. It is 0 when the request had no text bytes.

type RemovalFigure added in v0.11.0

type RemovalFigure struct {
	// SavedUSD is the Removed tokens at the size without the change: Prompt plus the net tokens removed.
	SavedUSD float64
	// AddedUSD is the Added tokens at the billed size (the size of the request sent).
	AddedUSD float64
	// NetUSD is SavedUSD minus AddedUSD.
	NetUSD float64
	// PerTokenUSD is the price of one removed token at the size without the
	// change. With a nil Ratio it is the host's token with the factor included. With a Ratio it is the provider's
	// token and the factor is 1. A host that splits a removal between names uses it. It does not depend on Removed, except
	// through the size.
	PerTokenUSD float64
	// Tier is the tier the tokens were priced at.
	Tier Tier
	// Estimated is true when a rate the pricer gave is an estimate, or the Ratio is capped.
	Estimated bool
	// Version is RulesVersion, the version of the rules that made the figure (R46). A host that records the
	// figure stores it as OpsVersion.
	Version int
}

RemovalFigure is RemovalSaving in money.

func RemovalSaving added in v0.11.0

func RemovalSaving(in RemovalInput, p SizedPricer) RemovalFigure

RemovalSaving prices a change that took tokens out of the head of a request. It is the one formula for a tool declaration filter and for tool deferral, so a host never prices such a saving itself.

The tokens are Removed times Factor. With a Ratio, they are the Ratio's tokens of RemovedBytes, and the factor is 1. They are priced at the tier the head was billed at. The size that picks the rate is the billed size plus the net tokens removed, rounded up: the request without the change. Rounding up errs to the larger size, so a token at a price line is never put in the cheaper side. Added tokens price at the billed size, because the request sent carried them.

It is deterministic and does no I/O. A model the pricer does not know gives rate 0 and Estimated.

type RemovalInput added in v0.11.0

type RemovalInput struct {
	Model string
	At    time.Time
	// Tier is the tier the head was billed at: [HeadTier] of the usage of the request sent.
	Tier Tier
	// Prompt is the billed size of the request sent: input plus cache read plus cache write. 0 means
	// the host does not know it.
	Prompt int64
	// Removed is the tokens the change took out, in the host's own tokenizer units.
	Removed int
	// Added is the tokens the change put back at the same tier. 0 for a plain removal.
	Added int
	// Factor is the host's tokenizer correction: the ratio of the provider's token count to the
	// host's. The figure applies it once, to Removed and to Added, in size and in dollars. 0 or less
	// means 1. The library knows no tokenizer, so the host gives it.
	Factor float64
	// RemovedBytes and AddedBytes are the bytes of text the change took out and put back. They are used
	// only when Ratio is set.
	RemovedBytes, AddedBytes int
	// Ratio is the request ratio of the request sent: [Result.Ratio], or one rebuilt with
	// [RatioFromText]. When it is set, Removed and Added are Ratio.Tokens of the two byte counts, in the
	// provider's own tokens, the same conversion as [Compute]. Removed, Added and Factor are then
	// ignored: the factor is 1. A rebuilt ratio ([RatioFromText]) prices TEXT bytes only: it holds no media or opaque state, so pass the bytes of text. A capped ratio makes the figure Estimated. When it is nil, nothing changes: Removed, Added and Factor apply.
	Ratio *Ratio
	// Unsized says that the host has no prompt size. The pricer then gets size 0, the rate of a small
	// request, for both sides.
	Unsized bool
	// Endpoint is the upstream endpoint the request was billed on, for a host whose rates are keyed by
	// endpoint. It is passed to the pricer in [RequestContext].Endpoint, unchanged. "" (the default)
	// means the model alone decides the rate, as before.
	Endpoint string
}

RemovalInput is one change that took tokens out of the head of a request, and maybe put some back (a list of names that stands for the removed definitions).

type Request

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

Request is the record of one request. It is private to that request: two requests of one thread in flight each have their own (R53).

func (*Request) Add

func (r *Request) Add(op Operation)

Add records one reported operation. The framework sets Operator and DryRun first.

func (*Request) Compute

func (r *Request) Compute(usage Usage) Result

Compute prices the request and then replaces the thread's ThreadState (§6.1). It is deterministic and does no I/O (R26). If it panics, the ThreadState is unchanged, because the replace is its last step. If another request replaced the ThreadState after EndRequest, Compute calculates again from the current one and sets Result.Recomputed (R53).

Call it once for each request. A second call prices the request against the ThreadState the first call stored, so the active changes count again (the second result is usually phase hot). Do not call Compute again to retry after a transient error in the host: the first call already advanced the state. Use Preview to price a request again, because it stores nothing. Compute does not recover from a panic: the host wraps the call so that a failure leaves the request unpriced.

func (*Request) EndRequest

func (r *Request) EndRequest(thread Thread, forwarded Body, breakpoints []Breakpoint, facts EntryFacts)

EndRequest names the thread, records the forwarded body, its breakpoints and the facts only the host knows, and takes a copy of the thread's ThreadState. Call it after the last plugin.

It also stores the reported rewrite and setting operations in the ThreadState as active, with a Version bump (§4.6). A request can fail before the response, and then Compute never runs; the operator reports a change once, so the change would be lost. The fingerprint and the cache state change only in Compute, because they need the usage. Compute does not store the operations a second time: a reported operation replaces the active one with its ChangeID. When the stored list would not change (a retry that reports the same change), nothing is written and Version stays.

func (*Request) LowerTTL added in v0.1.1

func (r *Request) LowerTTL(ttl time.Duration)

LowerTTL tells the library that the response billed a shorter cache lifetime than the request asked for, when the host learns it after EndRequest: a gateway that bills a 1h ask as 5m. Call it before Compute. It lowers EntryFacts.TTL to ttl and, for a ttl below one hour, sets every 1h breakpoint to 5m, in the forwarded body and in the client body alike: the library judges each part of an entry by the TTL of the breakpoint that wrote it, and the client body is billed through the same gateway (accountant#56). A ttl between 5m and 1h counts as 5m for the breakpoints, because the engine knows only 5m and 1h. A lower TTL can move a saving in either direction (design §4.4), so the host calls it only for a downgrade it has proved. The host's own breakpoint slices are not changed. It does nothing before EndRequest, for a ttl that is not shorter than the TTL in EntryFacts, or for a ttl of 0 or less: it only lowers. It leaves EntryFacts.Lifetime alone, so the host passes LifetimeExact for a lifetime it read from the bill.

func (*Request) Preview

func (r *Request) Preview(usage Usage) Result

Preview does the same calculation as Compute and stores nothing (§6.1).

type RequestContext added in v0.18.0

type RequestContext struct {
	PromptTokens int64
	Endpoint     string
}

RequestContext is the context of the request a priced token belongs to. The library builds it and passes it to SizedPricer.PriceAt, so the interface can grow a new field later without another breaking signature change. A host reads only the fields it needs.

PromptTokens is the prompt size of the request the token belongs to: fresh input plus cache read plus cache write, as the provider counts it. PromptTokens 0 means the size is unknown: the host then gives the rate of a small request. The library never passes a negative size. A zero-value RequestContext is the size-unknown case with no endpoint, so a host that reads only PromptTokens behaves as before.

Endpoint is the upstream endpoint, route or host the request was billed on, as the host names it. It is for a host whose rate table is keyed by endpoint as well as model (the same model served by two routes can bill at two rates). "" means the host does not give it, or does not key rates by endpoint: the pricer then uses the model alone, exactly as before. The library sets it from the host's input struct (FigureInput.Endpoint and the like); it carries no meaning to the library.

type RequestCostInput added in v0.11.0

type RequestCostInput struct {
	Model string
	At    time.Time
	// Billed is the usage the provider billed, as in [FigureInput]: CacheWrite counts every lifetime, and
	// CacheWrite1h is the part of it billed at the 1-hour tier.
	Billed Usage
	// Output is the output tokens the provider billed.
	Output int
	// PromptTokens is the prompt size that picks the price tier. 0 or less means Input + CacheRead +
	// CacheWrite, the size the provider counts.
	PromptTokens int64
	// Endpoint is the upstream endpoint the request was billed on, for a host whose rates are keyed by
	// endpoint. It is passed to the pricer in [RequestContext].Endpoint, unchanged. "" (the default)
	// means the model alone decides the rate, as before.
	Endpoint string
}

RequestCostInput is the billed usage of one request, for RequestCost.

type RequestMeta

type RequestMeta struct {
	RequestID string `json:"requestId"`
	Session   string `json:"session"`
	Model     string `json:"model,omitempty"`
	// ModelKey names the model apart from the spelling of its id. Two ids with the same ModelKey are one
	// model: a dated id (claude-sonnet-4-5-20250929), an alias (claude-sonnet-4-5) and a vendor prefix
	// (aws/..., anthropic/...) of one model share a key. The library compares ModelKey, so a change of
	// spelling is not reported as a model change. Empty = compare Model as written.
	ModelKey string            `json:"modelKey,omitempty"`
	Params   map[string]string `json:"params,omitempty"`
	At       time.Time         `json:"at"`
	Billing  Billing           `json:"billing"`
	// Compaction is the host's verdict that this request is the first one after a client compaction.
	// The library cannot tell a compaction from another client edit: both end the changes at or after
	// the first difference (§4.3). Empty means the host says nothing. The library records the verdict
	// in Result.Compaction and never reads it for pricing.
	Compaction CompactionTrigger `json:"compaction,omitempty"`
	// Window is the model's context window in tokens: the most that a prompt can hold. The client cannot
	// send a body above it, so the baseline compacts when it reaches it (R58). 0 means the host does not
	// say: the library then uses its default window for the model, and none for a model it does not list.
	Window int `json:"window,omitempty"`
	// CompactionPoint is the token count at which the client compacts its own body, when the host knows it
	// and it is not the window (for example, 95% of the window). It is used instead of Window. When both are
	// set, the lower one applies. 0 means the host does not say. A value of the host replaces the default
	// window of the model. With no value and no default, the baseline never compacts (R58).
	CompactionPoint int `json:"compactionPoint,omitempty"`
}

RequestMeta is what the host knows about the request before the pass: the fields of RequestOps that are not operations.

type RequestOps

type RequestOps struct {
	Version   int               `json:"version"`
	RequestID string            `json:"requestId"`
	Session   string            `json:"session"`
	Thread    Thread            `json:"thread"`
	Model     string            `json:"model,omitempty"`  // the model the request was sent for
	Params    map[string]string `json:"params,omitempty"` // other settings that change the cost: effort, thinking, max_output, ...
	At        time.Time         `json:"at"`
	// Billing prices every operation of the request, a spend included (R41, R42).
	Billing Billing `json:"billing"`
	// Ops is in-process only: input to Compute for this request, never recorded (R20).
	Ops []Operation `json:"ops"` // in pipeline order
}

RequestOps is the operations of one request, or of one call made outside a request.

type Result

type Result struct {
	Version int
	Ops     []PricedOp // one for each input operation, same order: the reported ones, then the active ones applied again
	// CacheEffects are the breaks, rescues and breakpoint changes the library found. The library
	// writes them and a host never reports one, so they have no input form (§4.2 rule 4).
	CacheEffects []CacheEffect
	Interaction  TierTokens // §6.2: on a rescued request; attributed to nobody
	Unpriced     []Unpriced // with a machine-stable reason
	Checks       []CheckFailure
	Boundary     *Position  // the B* used; nil when unknown
	Recomputed   bool       // another request replaced the ThreadState first (R53, §6.1)
	Phase        CachePhase // the cache phase it used (§5.2); for the host's own checks, never an input
	// InteractionCaused is the other side of Interaction, as Caused is for Saved. Interaction is the
	// tokens the client body would have billed cold (write). InteractionCaused is what the ops
	// already book for them (read). The host prices Interaction minus InteractionCaused.
	InteractionCaused TierTokens
	// Compaction is set when the host reported a client compaction on this request
	// (RequestMeta.Compaction). It is a record for the host, which closes its own epoch on it. It
	// changes no figure.
	Compaction *CompactionRecord
	// BaselineCompaction says how the compaction point of the baseline applied to this request (R58). nil
	// when no point applies: the host gave no RequestMeta.Window and no CompactionPoint, and the model has no
	// default window. It is set on a request that is not priced too, with the stored cut, Fired false and
	// NotBooked 0.
	BaselineCompaction *BaselineCompaction
	// StorageTokens is the tokens this request wrote into a cache that the provider bills by storage
	// (Provider.StorageBilled). 0 when storage is not billed or nothing was priced. The host prices
	// the hours; the library does not know how long the cache is kept.
	StorageTokens int
	// ActiveOps is the count of rewrite and setting operations still active in the thread's state
	// after this request (§4.6). It includes an observe-mode (DryRun) change. A count that keeps rising while the thread adds no new changes shows
	// a change that did not end (accountant#70).
	ActiveOps int
	// OldestActiveTurns is the count of requests since the oldest active operation entered the state:
	// 0 when it entered on this request, and 0 when nothing is active. It counts requests that Compute
	// stored. A DryRun change ages from the request on which it entered, and a switch to enforce does
	// not start the age again. When another request of the thread stored its Compute first
	// (Recomputed), the request that reported the change can get 1. After a Restore of a snapshot that
	// has no record (older than this field), the count starts again at the Restore. Results that do
	// not read the thread state (end_request_missing, ComputeStandalone) give 0 for both fields. A change that stays for the whole session is normal, so this value
	// alone is not a sign of an error: read it with ActiveOps.
	OldestActiveTurns int
	// MessageTokens is the size of the messages section of the client body, in tokens, by the library's
	// own measure (the byte ratio of this request). It is the size that [Withhold] tests the saved
	// message tokens against (§6.7). The tool declarations and the system are not in it. 0 when nothing
	// was priced (no usage, or a usage that failed a check).
	MessageTokens int
	// Ratio is the request ratio that priced this result (§5.3). A host converts the bytes of a text it
	// removed with it, and stores [Ratio.Text] and [Ratio.Capped]. nil in two cases: nothing was priced (no usage, or
	// a usage that failed a check), or the request was priced but its ratio is not in range ([Ratio.InRange]): no text
	// bytes, or a count above the bound of a Ratio. MessageTokens can be above 0 while Ratio is nil.
	//
	// Not marshaled: a Ratio holds only unexported fields, so JSON would show an empty object and change the digest
	// of every stored Result. A host stores [Ratio.Text] and [Ratio.Capped], and rebuilds it with [RatioFromText].
	Ratio *Ratio `json:"-"`
}

Result is the output of Compute (§6.3).

func ComputeStandalone

func ComputeStandalone(ops RequestOps) Result

ComputeStandalone prices a RequestOps that holds only spend operations (a keep-alive ping or a detached call). It reads and changes no ThreadState (§6.1). A spend is not priced in tokens: its Call is returned for the host to price (D4). Any other kind is unpriced.

func (Result) Reliable added in v0.1.1

func (r Result) Reliable() bool

Reliable reports whether no check of the Result is Fatal. An unreliable Result still has figures, but they come from a wrong list of operations.

type Section

type Section string // tools | system | messages

The enums are strings, not integers, so an unknown value from a newer operator survives a decode and can be reported as unpriced (R19).

type SettingChange

type SettingChange struct {
	From *string   `json:"from,omitempty"`
	To   *string   `json:"to,omitempty"`
	At   *Position `json:"at,omitempty"`
}

SettingChange is one setting going from one value to another. A nil pointer means "not set".

At is the first position of the prefix that the provider renders this setting into, so the first position whose cache entry the change can invalidate (cached-prefix.md). A model change starts at tools[0]; an effort change on a model that renders it into the messages starts at messages[0]. The body does not differ where a setting differs, so the library cannot find this position by comparing hashes (§5.2). Nil means the reporter does not know: the library then falls back to the read the usage shows.

type Sibling added in v0.1.1

type Sibling struct {
	Body        Body
	Breakpoints []Breakpoint
}

Sibling is another thread of the same session: the body it last forwarded and the breakpoints it sent with it. The host keeps one for each thread it has seen inside the TTL (R54). It holds hashes and sizes only (R2).

type Size

type Size struct {
	Bytes int `json:"bytes,omitempty"` // required on rewrite; the sum check compares it with the Body sizes (§6.5)
	// Tokens is the token count the host measured for the range. 0 means not measured: the library
	// then converts Bytes and marks the result Estimated.
	Tokens int `json:"tokens,omitempty"`
	// MediaBytes is the part of Bytes that is base64 media (an image or a document block). The
	// library prices it apart from the text ratio. 0 means the range has no media, or the host did
	// not mark it.
	MediaBytes int `json:"mediaBytes,omitempty"`
	// OpaqueBytes is the part of Bytes that is opaque (a thinking signature, PosHash.Opaque). The
	// library prices it apart from the text ratio. 0 means the range has none, or the host did not
	// mark it.
	OpaqueBytes int `json:"opaqueBytes,omitempty"`
	// OpaqueTokens is the host's token count for the opaque bytes of the range (design D16). 0 means no
	// count: the library takes the counts of the body that holds the range, and prices the rest of the
	// opaque bytes at the fixed price.
	OpaqueTokens int `json:"opaqueTokens,omitempty"`
}

Size is the bytes of a range, and optionally its tokens. Bytes are required. When the host knows the tokens (a tokenizer, or a count_tokens call), it sets Tokens, and the library uses them as they are. Without Tokens the library converts the bytes (§4.2 rule 7).

type SizedPricer added in v0.9.0

type SizedPricer interface {
	PriceAt(model string, at time.Time, tier Tier, req RequestContext) (usdPerToken float64, estimated bool)
}

SizedPricer gives the host's rate for one token. The host owns the rate table. The library knows no price (D3).

Some providers bill a large request at a higher rate for ALL its tokens, so the rate depends on the prompt size. The rate may also depend on the endpoint the request was billed on. RequestContext carries both: req.PromptTokens is the prompt size (0 means unknown: give the rate of a small request), and req.Endpoint is the host's endpoint key ("" means the model alone decides the rate). Figure never passes a negative size.

estimated is true when the rate is a fallback or a guess. A rate of 0 with estimated false is a real free rate. An unknown model must return estimated true.

type Span

type Span struct {
	Section    Section `json:"section"`
	From       int     `json:"from"`
	To         int     `json:"to"`
	SizeBefore Size    `json:"sizeBefore"`
	SizeAfter  Size    `json:"sizeAfter"`
}

Span is a range of positions in one section: [From, To], both in the operator's output.

type Thread

type Thread struct {
	ID     string `json:"id"`               // "main" for the primary thread
	Parent string `json:"parent,omitempty"` // the thread this one was forked from; "" if none
}

Thread identifies one conversation inside a session: the main thread, a subagent, or a fork. Each thread has its own provider cache entry.

type ThreadState

type ThreadState struct {
	Active    []Operation  // rewrite and setting operations still applied (§4.6)
	PrevPrint *Fingerprint // this thread's previous request; nil = none (§5.2)
	Cache     CacheState   // what the previous request left cached; zero value = unknown
	Version   uint64       // +1 at each replace; the optimistic lock (R53)
	// Requests is the count of this thread's requests that Compute stored. It is not Version: a
	// request that reports a change replaces the state twice (EndRequest and Compute).
	Requests uint64
	// FirstApplied maps the ChangeID of each operation in Active to the request (a value of Requests)
	// on which it entered Active. A reported operation that replaces an active one with its ChangeID
	// keeps the first value, so a change that the host reports again does not look new. Code makes a
	// new map for each new state and never changes a stored one.
	FirstApplied map[string]uint64
	// contains filtered or unexported fields
}

ThreadState is kept between requests and replaced after each one (§6.1).

type Tier added in v0.9.0

type Tier string

Tier is a price class of tokens. A host prices each tier with its own rate table.

const (
	TierInput        Tier = "input"
	TierCacheRead    Tier = "cache_read"
	TierCacheWrite5m Tier = "cache_write_5m"
	TierCacheWrite1h Tier = "cache_write_1h"
	TierOutput       Tier = "output"
)

func HeadTier added in v0.11.0

func HeadTier(u Usage) Tier

HeadTier is the tier the head of a request's prefix was billed at. Any cache read means the head was read. Else any cache write means the request created it, at the one-hour rate when CacheWrite1h is above 0 (CacheWrite1h is part of CacheWrite, never an addition to it). Else the head was fresh input.

Why 1h on a mixed write: the provider's constraint is that longer lifetimes come before shorter ones in prompt order (tools, system, messages; docs/cached-prefix.md). So when any 1h tokens were written, the first breakpoint, which ends the head, is 1h. See docs/design.md §6.6. HeadLifetimeOneHour answers the same question about a write (CacheWrite1h > 0), for a host deciding what to pass Request.LowerTTL; if this rule ever needs to change, change that one with it.

A change that takes tokens out of the head, such as a tool declaration, saves them at this tier.

type TierTokens

type TierTokens struct {
	Input        int `json:"input,omitempty"`
	CacheWrite5m int `json:"cacheWrite5m,omitempty"`
	CacheWrite1h int `json:"cacheWrite1h,omitempty"`
	CacheRead    int `json:"cacheRead,omitempty"`
}

TierTokens is a token count for each billing tier.

func (TierTokens) Add added in v0.1.1

func (t TierTokens) Add(o TierTokens) TierTokens

Add returns t plus o, tier by tier. Use it, not a copy of the four fields, so a new tier is counted by every host that adds tokens.

func (TierTokens) IsZero added in v0.1.1

func (t TierTokens) IsZero() bool

IsZero reports whether every tier is 0.

func (TierTokens) Sub added in v0.1.1

func (t TierTokens) Sub(o TierTokens) TierTokens

Sub returns t minus o, tier by tier. The result can be negative.

type Tracker

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

Tracker keeps the state of one thread between requests.

type Trackers

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

Trackers holds one Tracker for each thread. It is safe for concurrent use. It bounds its own memory: when more than maxThreads are held, BeginRequest drops the threads seen longest ago. A dropped thread loses its active changes (design §11, Q13).

func NewTrackers

func NewTrackers() *Trackers

NewTrackers returns an empty set: every thread starts with no history.

func (*Trackers) BeginRequest

func (ts *Trackers) BeginRequest(meta RequestMeta, client Body, clientBreakpoints []Breakpoint) *Request

BeginRequest opens a record that belongs to no thread yet: the thread is known only at the end of the pass (§6.1). Call it before the plugins, with the client body before any plugin.

func (*Trackers) Restore added in v0.1.1

func (ts *Trackers) Restore(data []byte) error

Restore replaces the state of every thread with the one in data, made by Trackers.Snapshot. On an error it changes nothing. It refuses a snapshot with no threads field, an empty thread key, a key twice, or a change recorded after the thread's next request (a firstApplied value above requests + 1). An EndRequest that runs during Restore can be lost: stop the traffic first. The count of Trackers.Trimmed is not part of the snapshot.

func (*Trackers) Snapshot added in v0.1.1

func (ts *Trackers) Snapshot() ([]byte, error)

Snapshot returns the state of every thread as JSON. It holds no content (R2): no message text. It holds hashes, sizes, positions, and the IDs and names the state needs (session and thread keys, operator names, ChangeIDs, model names, setting values, times and TTL strings). A host saves it before a restart and passes it to Trackers.Restore after. It does no I/O. The same state gives the same bytes. It returns an error when the state cannot be encoded, for example a request time outside the years 0 to 9999 (Compute prices such a request without error).

func (*Trackers) Trimmed added in v0.1.1

func (ts *Trackers) Trimmed() uint64

Trimmed returns how many threads the trim has dropped since the set was made. A host can export it as a metric. A dropped thread loses its active changes (design §6.1, Q13).

type USDEffect added in v0.9.0

type USDEffect struct {
	Effect    CacheEffect
	SavedUSD  float64
	CausedUSD float64
	// Counted says that the effect is part of the bill difference. An InBaseline effect, an effect of an
	// unknown kind, and a break owned by a change no counted operation made are not counted.
	Counted bool
	// Owner is the Operator of the counted operation that owns the effect, or "".
	Owner string
}

USDEffect is one cache effect, priced. SavedUSD is its Saved tokens at the size without the operations. CausedUSD is its Caused tokens at the billed size. Both are never negative. The value of the effect is SavedUSD minus CausedUSD: a break, a markPremium and a ttlPremium come out negative. An effect that no figure books is not priced, so both are 0: an InBaseline effect that is not a break, and an effect of an unknown kind.

type USDFigure added in v0.9.0

type USDFigure struct {
	// Lines is every priced amount of the counted operations: moved tokens (saved at the size without
	// the operations, caused at the billed size), the call usage of each spend, and the re-rate shares.
	Lines []USDLine
	// Effects is every cache effect of the Result, in order.
	Effects []USDEffect

	// ByComponent is the net dollars of each operation: saved minus caused, plus the breaks and the mark
	// effects it owns, plus its share of the re-rate.
	ByComponent map[string]float64
	// ByComponentFirst and ByComponentReplay split the SAVED tokens of each operation by tier: the write
	// and input tiers (content the provider had not cached: a first removal, with the re-rate share of a
	// net saver) and the read tier (a replay of content in the cached prefix). An adder's re-rate share is
	// in ByComponent only: it saved nothing.
	ByComponentFirst, ByComponentReplay map[string]float64
	// ByComponentSaved is the dollars of the Saved tokens of each operation, at the size without the
	// operations. ByComponentSavedAsRead is the same tokens priced at the read tier. A host that wants a
	// lower bound of a figure it cannot trust uses the two.
	ByComponentSaved, ByComponentSavedAsRead map[string]float64

	// KeepAliveSavedUSD is the rescue effects. TTLUSD is the premium
	// (negative) and the rescue of the head TTL.
	KeepAliveSavedUSD, TTLUSD float64
	// EndedBreakUSD is the break that an ended change left behind. No operation owns it, but the client
	// body would have read that prefix, so it is part of the bill difference. Negative: a cost.
	EndedBreakUSD float64
	// UnattributedBreakUSD is the breaks the client body has too (InBaseline), and the breaks of a change
	// no counted operation made. It is shown and never counted. A positive number is a cost.
	UnattributedBreakUSD float64
	// UnownedMarkUSD is the value of the markPremium and markPayback effects that no counted operation
	// owns. Counted in DeltaUSD. The host chooses its row.
	UnownedMarkUSD float64
	// UnownedReRateUSD is the re-rate when no operation moved the size to own it. Counted in DeltaUSD. It is
	// a guard: a re-rate always has an owner today (see Figure), so it is 0.
	UnownedReRateUSD float64
	// InteractionUSD is the net value of Result.Interaction minus Result.InteractionCaused, at the size
	// without the operations. Signed. Counted in TotalUSD, not in DeltaUSD.
	InteractionUSD float64
	// CallUSD is the cost of the spend calls (the usage of each model call, output included). It is a
	// separate bill, so it is in neither DeltaUSD nor TotalUSD.
	CallUSD float64

	// DeltaUSD is the sum of ByComponent, EndedBreakUSD, UnownedMarkUSD and UnownedReRateUSD. It leaves
	// out KeepAliveSavedUSD, TTLUSD, InteractionUSD and UnattributedBreakUSD.
	DeltaUSD float64

	// Unpriced lists "opID:reason" for each operation the library did not price. Every entry has this
	// one form, so a host splits it at the first colon. A reason with no operation has an empty opID:
	// ":effect_<kind>_unknown_kind" for an effect of an unknown kind. A call on an operation that is not
	// a spend gives "opID:not_spend". An unpriced operation is not a zero saving.
	Unpriced []string
	// Estimated is true when a counted operation or counted effect is an estimate, or a rate the pricer used is.
	Estimated bool
}

USDFigure is the savings of one request in money. Figure makes it. It is the only place in which the savings of a request with a Result are turned into dollars. A head removal that has no Result is priced by RemovalSaving. A host maps its fields to its own rows and columns, and does not price a saving itself.

Keys of the maps are the Operator of the operation, as the host gave it.

func Figure added in v0.9.0

func Figure(in FigureInput, p SizedPricer) USDFigure

Figure turns a Result into dollars. It is deterministic and does no I/O.

Two prompt sizes matter. The request sent has the billed size. The request without the operations has the billed size plus the tokens the counted operations saved, minus the tokens they caused. A counted operation is a non-DryRun operation that is not a spend. A cache effect and the interaction move tokens between tiers, so they do not change the size. Saved tokens (of an operation or an effect) are priced at the size without the operations. Caused tokens are priced at the billed size.

The tokens that stay in both requests change rate when the two sizes sit on different sides of a price line (the re-rate). Per tier the amount is stay x (rate without - rate billed). Stay is the billed tokens of the tier, minus the tokens the counted operations caused, minus the tokens the counted effects caused (an effect prices its own whole difference). The output tier counts too, with FigureInput.Output: all of it stays. The re-rate can be negative. The operations that moved the size own it. If the operations made the prompt smaller, each operation with net saved tokens (saved minus caused, above 0) takes a share in proportion to them. If they made it larger, each operation with net added tokens takes a share in proportion to those. So the components add up to the request total, and an operation that pushes a prompt over a price line pays the premium of the tokens that stay. With no such operation the re-rate is UnownedReRateUSD. That is a guard: the sum of the nets is the size difference, so a re-rate always has an owner, and UnownedReRateUSD is 0 with a pricer whose rate depends only on the model, the tier and the size.

A spend call is priced at its own model, and at the size of its own usage.

func (USDFigure) CountedUSD added in v0.11.0

func (f USDFigure) CountedUSD() float64

CountedUSD is DeltaUSD plus InteractionUSD. A host that shows the keep-alive and TTL effects on their own rows counts this figure as the savings of the operations. TotalUSD adds those effects.

func (USDFigure) TotalUSD added in v0.9.0

func (f USDFigure) TotalUSD() float64

TotalUSD is the whole bill difference of the request: the bill without the operations minus the bill as sent. It is DeltaUSD plus the effects and the interaction.

type USDLine added in v0.9.0

type USDLine struct {
	Kind      Kind
	Operator  string
	Tier      Tier
	Direction string
	USD       float64
	// ReRate marks a line that is the operation's share of the re-rate, not the price of tokens that moved.
	ReRate bool
}

USDLine is one priced amount of one operation in one tier. USD is never negative: Direction gives the sign. A line with Direction "added" is a cost.

type Unpriced

type Unpriced struct {
	OpID   string
	Reason string // "unknown_kind", "negative_size", "operator_not_allowed", "penalty_unknown", ...
}

Unpriced names an operation the library did not price and why.

type Usage

type Usage struct {
	Input        int `json:"input"`
	CacheRead    int `json:"cacheRead"`
	CacheWrite   int `json:"cacheWrite"`
	CacheWrite1h int `json:"cacheWrite1h"`
}

Usage is the provider's billed prompt usage. CacheWrite1h is the part of CacheWrite billed at the one-hour rate, never an addition to it.

Jump to

Keyboard shortcuts

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