keepalive

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 24 Imported by: 1 module, 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 keepalive is the idle keep-alive: the one cache mechanism that cannot be a component.

What it is for

An Anthropic prompt-cache entry has a five-minute default lifetime, and a session idle longer than that loses its entire cached prefix. The next turn then re-bills every token of it at the cache-CREATION rate. GPT-5.6+ OpenAI Responses entries instead have a documented 30-minute minimum after the latest write or reuse and use a separate 28-minute schedule. Measured Anthropic traffic on this service over 19,805 requests and $3,139.97 of spend: 742 requests (3.7% of traffic) missed for that reason and cost $741.07 — 23.6% of everything — at $0.9987 each against $0.1178 for a request that hit. Against each row's own counterfactual the penalty is 11.35x, of which 91.2% is pure re-write. $584.83 of it, 18.6% of ALL spend, sits in misses whose idle gap was under an hour, and 47% of the misses missed the window by less than five minutes.

The provider documents the two facts that make this fixable:

"By default, the cache has a 5-minute lifetime. The cache is refreshed for no
 additional cost each time the cached content is used."

"The lifetime is measured from the start of the request that writes or reads the cache
 entry, not from the end of its response."

So a cache READ refreshes the lifetime, and a read costs 0.1x base input where re-creating the prefix costs 1.25x. One ping buys back one re-creation at 11.5:1.

Replayed over the production window THROUGH THIS CODE (TestKeepAliveOnProductionSnapshot) at the defaults shipped when it was measured (X=280s, K=2): 912 pings costing $90.76 convert 148 of 357 addressable misses worth $215.84, net **+$125.08** — 3.98% of spend, and 12.9x everything the whole transformation pipeline delivered over the same window ($9.72). The defaults have changed since (the idle default is now config.DefaultKeepAliveIdle; see Policy and the config defaults), and this replay has not been rerun at them, so read these figures as that measurement, not as what today's defaults deliver.

Why it is host-level and not a component

A component runs while a request is in flight. The event this addresses happens when NO request is in flight: the agent is idle, and the entry lapses with nothing on the wire to hook. Nothing inside the pipeline can act at that moment, which is why this lives beside the request path rather than in it.

What it costs, and whose money it is

A ping is a real upstream request billed to the caller's own credential. That is the trade — a small certain spend against a much larger probable one — and it is not ours to make on someone's behalf, so it is opt-in per account, capped per session, capped in count, and recorded as its own dashboard row with its own cost. See Policy.

The two ways this can be WRONG, and the guards

  1. **A ping that writes instead of reads costs 12.5x rather than saving.** The prefix hash is cumulative up to and including the breakpoint, so the ping's body must be byte-identical over that prefix. Hence the ping resends the exact bytes that were sent upstream, and changes only `max_tokens` and `stream` — fields outside the hashed prefix. If a ping's usage nevertheless reports more written than read, the mechanism is wrong for that session: it is logged at ERROR, counted, and the session is dropped rather than pinged again.

  2. **Pinging a session that has ENDED is pure waste.** It is not detectable: only 290 of 3,891 session-final requests (7.5%) end with `end_turn`, the other 3,476 end mid-tool-loop and look exactly like an active session. K is therefore the control, and it is why the default is small: the marginal ping's yield falls while its cost does not, so the net flattens and then collapses — +$125.08 at K=2, +$130.80 at K=3, +$85.28 at K=1, +$58.35 at K=12.

    K=2 and K=3 are a TIE on money (the $5 between them is inside the run-to-run wobble), so the default is 2 for the request-volume reason and not a dollar reason: it sends 26% fewer pings on a gateway path that returned 180 HTTP 429s in the same window.

A note on what this deliberately does NOT do: it does not stop pinging a session whose last response ended with `end_turn`. That reads like a session-end signal and is the opposite. `end_turn` means the model finished and control returned to a HUMAN, which is precisely the state that produces a long gap: P(gap > 300s) is 37.15% after `end_turn` against 0.74% after `tool_use`, a 6.7x lift, and 83.7% of the recoverable dollars sit behind it. Stopping there would discard most of the value the mechanism exists to capture.

Index

Constants

View Source
const (
	// MaxSessions bounds the tracked ENTRIES, which since #423 are threads, not sessions:
	// one session holds one entry per thread that passed the gates (main agent, each subagent).
	// The name is kept so the bound stays greppable from its history. 512 still holds: an entry
	// exists only for a thread past its first request with a prefix over the floor, a finished
	// thread's entry ends at the hard deadline ((K+1) x Idle, about 14 min at the defaults), and
	// the body bound below binds first. evictLocked has no per-session fairness on purpose: it
	// drops the entry whose ping is least imminent, whichever session it belongs to.
	MaxSessions = 512
	// MaxBytes bounds the total request bodies held for replay.
	//
	// THIS is the binding ceiling, not MaxSessions — tune this one. A gated session
	// carries at least a 20k-token prefix, so ~100 KB to 1 MiB of body, and 128 MiB therefore
	// binds around 130 large sessions: well before the 512-session count. The replay reports a
	// peak of 11 live sessions, but it drives ~350-byte synthetic bodies, so it exercises the
	// count bound and says nothing about this one.
	MaxBytes = 128 << 20
	// MaxTurnKeys bounds the per-thread turn counter (per session before #423).
	// Larger than the entry bound because it holds one int rather than a body, and it has to
	// outlive the entry.
	MaxTurnKeys = 20000
	// MaxBodyBytes refuses to hold a single body larger than this. A body this big
	// is a multi-million-token request whose ping would itself cost real money, and holding
	// one would spend a fifth of the whole budget on one session.
	MaxBodyBytes = 8 << 20
)

Keeper bounds. Both are memory bounds and both are needed: a few enormous sessions and a great many small ones are different ways to exhaust the same 8 GiB.

View Source
const DefaultMaxUSDPerPing = 0.50

DefaultMaxUSDPerPing mirrors config.DefaultKeepAliveMaxUSDPerPing, which this package may not import (proxy does not depend on the configuration loader). They are pinned equal by TestTheProxysPingCeilingDefaultMatchesTheConfigLoaders.

View Source
const ManualStrategyID = "manual"

ManualStrategyID is the keepalive_strategy_id a manual ping's row carries. It names no real strategy, so no strategy ledger matches it.

Variables

View Source
var (
	// ErrNotHeld means the keeper holds nothing to ping this thread with: an unknown thread,
	// another tenant's, one the keeper has stopped, or a thread of an account whose keep-alive is
	// off (no body and no credential are kept then, and pinging needs both).
	ErrNotHeld = errors.New("keepalive: nothing held for this thread")
	// ErrBusy means a real request is open on the thread. It refreshes the entry itself, and a
	// second request beside it would only crowd the tenant's budget.
	ErrBusy = errors.New("keepalive: a request is in flight on this thread")
	// ErrLimited means the tenant has no spare rate or concurrency for a ping right now.
	ErrLimited = errors.New("keepalive: no spare capacity for a ping")
	// ErrTooCostly means one ping on this thread would cost more than the policy's per-ping
	// ceiling, the same guard the scheduled path applies (Policy.Ceiling).
	ErrTooCostly = errors.New("keepalive: a ping on this thread costs more than the per-ping ceiling")
)

Functions

func Disabled

func Disabled() bool

Disabled is the operator's kill switch, read once at construction. A single environment variable rather than a control-plane route: the thing an operator needs at 3am is one that works when the control plane is what is broken.

func PingHeaders

func PingHeaders(src http.Header) http.Header

PingHeaders copies the non-secret headers a ping needs from the recorded request.

func PredictorFor

func PredictorFor(id string) (func(stopReason string) float64, bool)

PredictorFor is predictorFor, exported for a host that needs to replay the same gate outside the keeper (the adapt-cache report's currentPlan).

Types

type EntryView

type EntryView struct {
	Pings, Turn    int
	Prefix         int64
	PingUSD, Spent float64
	Refreshed      int64
	Stopped        bool
	Policy         Policy
	Tag            string
	MaskedBody     []byte // a copy, still masked; for tests and replay tooling
}

EntryView is a read-only snapshot of one tracked entry. Exported for tests and replay tooling; hosts do not need it.

type Keeper

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

Keeper runs the keep-alive. One goroutine per host, one map, one lock.

func New

func New(o Options) *Keeper

New builds a Keeper. o.Dispatcher is required. o.Now defaults to time.Now; o.Go defaults to running each ping on its own goroutine, because a round trip must not be made while the map lock is held — the snapshot replay passes an inline runner instead, so a five-day simulation is deterministic and needs no synchronisation.

func (*Keeper) Arrive

func (k *Keeper) Arrive(key Key) (pings int, refreshed int64, tag string)

arrive tells the keeper a real request just started on this session, and reports what the keep-alive did during the span that request just ended.

Called at the START of the request, before it goes upstream: an entry left in the map while a real request is in flight could be pinged concurrently with it, which is both pointless (the real request refreshes the entry itself) and a second request against the tenant's concurrency budget.

tag is e.tag (Record.Tag) — in the proxy, which manager-controlled strategy resolved this idle span's policy, "" when none did. It is in scope right here and nowhere else once the entry is cleared, so this is the one place a real request's credit can be attributed to the strategy that earned it, rather than only the tenant's whole lifetime credit.

Only THIS thread's entry is cleared: a subagent's request says nothing about whether the main thread is still idle.

Every Arrive must be paired with a Record or a Depart for the same Key, once that request ends. An unpaired Arrive — a request that opens here and then neither calls Record nor Depart — leaks that thread's open count and stops its pings for good; nothing but Forget clears it.

func (*Keeper) ArriveAt

func (k *Keeper) ArriveAt(key Key) (pings int, refreshed int64, tag string, refreshedAt time.Time)

ArriveAt is Arrive plus the instant the entry's provider-side cache was last known refreshed (see kaEntry.refreshedAt) — the real request that started the idle span, or the start of the last ping that READ the cache. Zero when there was no entry.

func (*Keeper) Depart

func (k *Keeper) Depart(key Key)

Depart ends one open request on key's thread. Record calls it for its own key, so a host calls it only for a request that ends without a Record (e.g. an error path that never reaches it). On a thread with nothing open it does nothing. Nil-safe and a no-op on an empty session, like Arrive. Port of main's `departed`.

func (*Keeper) EndedAfter

func (k *Keeper) EndedAfter(tenant, session string, startedAt time.Time) bool

EndedAfter reports whether session (or a client alias) was marked ended at or after startedAt, i.e. the request that started at startedAt was in flight when the user left. Port of main's keeper.endedAfter (proxy/clientsignal.go, #527).

func (*Keeper) Entry

func (k *Keeper) Entry(key Key) (EntryView, bool)

Entry snapshots one tracked entry. Exported for tests and replay tooling; hosts do not need it. MaskedBody is a copy and stays masked, so a caller can measure it without being handed a readable transcript.

func (*Keeper) Forget

func (k *Keeper) Forget(tenantID string)

forget releases everything held for one tenant, for the paths that end an account's authority rather than change its mind: deletion, token revocation, disablement. Consent withdrawal is handled in record, and the hard deadline bounds anything that goes quiet — but this repo holds the stronger invariant explicitly (tenant.TestDeleteCascadesEveryCredential), and the keeper is a credential store that cascade did not know about.

ponytail: called from the four control-plane paths that end a hold's authority or its consent; a fifth would have to remember. Delete, revoke-token and disable end AUTHORITY — the credential stops working. PUT /api/me ends CONSENT — the credential still works and the hold is still authorized, but permission to use it is gone; that distinction is why ctlRevokeSession is deliberately not in the set (a browser cookie is neither). Move this inside TenantSource.Forget if revoke and disable ever start invalidating the cached tenancy too, which would make one hook cover all of them.

func (*Keeper) LiveSessionKeys

func (k *Keeper) LiveSessionKeys() []string

LiveSessionKeys returns the session ids the keeper currently considers live — a copy, so mutating the result never touches k.live. k.live is keyed by tenant:session:thread, but each entry carries its own raw session id (kaEntry.session), which is what dash.Filter.Session expects. Each session appears once, however many of its threads are live.

func (*Keeper) MarkEnded

func (k *Keeper) MarkEnded(tenant, session string, at time.Time)

MarkEnded records that session ended at `at`. Record then refuses any entry of that session (matched on Key.Session or Record.Client) whose request started before `at`.

func (*Keeper) Now

func (k *Keeper) Now() time.Time

Now is the keeper's clock, so a host resolving policy reads the same instant the keeper schedules by. Nil-safe: a nil keeper reads time.Now.

func (*Keeper) PendingPings

func (k *Keeper) PendingPings() int

PendingPings counts entries with a ping still ahead of them. Nil-safe: a keeper whose sweep never launched (the CONTEXT_GURU_KEEPALIVE kill switch) has nothing pending, which correctly lets an idle proxy exit.

func (*Keeper) PingNow

func (k *Keeper) PingNow(r ManualRequest) (ManualResult, error)

PingNow sends one ping on r.Key's thread now. It fails open in the sense that matters here: any refusal sends nothing and changes nothing, and the scheduled pings are unaffected.

func (*Keeper) Pingable

func (k *Keeper) Pingable(tenant string, all bool, session string) map[string]bool

Pingable reports, per thread ("" = main) of one session, whether PingNow would find something held to ping with: an entry exists and the keeper has not stopped it. It is PingNow's ErrNotHeld test and nothing else, so a client can hide a Ping button that would only answer 409. all drops the tenant filter, as Plans does.

func (*Keeper) Plans

func (k *Keeper) Plans(tenant string, all bool, session string) map[string]Plan

Plans returns the plan of every thread of ONE session still to be pinged, keyed by thread ("" = main). session must always match — this never lists "every session" — and all only drops the TENANT filter, matching main's allTenants: a single-tenant deployment calls this with all=true and its one real session id, never with session="". Only an entry that will still be pinged has a plan: the same conditions as PendingPings, plus pingable. Port of main's Handler.KeepAlivePlans (git show 67c5f758:proxy/keepalive.go L2102: `e.session != session || (!allTenants && e.tenant != tenantID)`, keyed by e.thread unconditionally), for the status line's "held warm until".

Keyed by thread even under all=true, same as main: if two different tenants' entries for this session land on the same thread (e.g. both "", the main thread — ordinarily impossible, since a session id is scoped to its tenant, but all=true deliberately steps outside that scope), one overwrites the other in the result map. Map iteration order is unspecified, so which tenant's entry survives is nondeterministic — exactly main's own behavior, which keys the identical way with no tie-break either.

func (*Keeper) Record

func (k *Keeper) Record(r Record)

Record hands the keeper what it needs to ping this thread, once the request that established the cache entry has finished.

startedAt is the instant the upstream request STARTED, per the provider's lifetime rule. The body is the exact bytes that went upstream. The entry, the deadline and the turn count are per thread; a session override still applies to every thread of its session.

func (*Keeper) RetireSession

func (k *Keeper) RetireSession(tenantID, session string)

RetireSession releases every thread of one session: the primary thread's key and every key under it, matched on Key.Session or a client alias (see RetireSessionStartedBefore). The separator is NUL, which no session id contains, so a prefix can never reach into another session.

func (*Keeper) RetireSessionStartedBefore

func (k *Keeper) RetireSessionStartedBefore(tenant, session string, cutoff time.Time) int

RetireSessionStartedBefore retires the session's entries (matched on Key.Session or Record.Client). A zero cutoff retires every thread, as RetireSession. A non-zero cutoff retires only the MAIN thread's entries ("" thread) that started before it — only the main agent compacts (its compaction call stays on the main thread), so a subagent's or teammate's held cache keeps its keep-alive. Returns how many entries were retired. Port of main's keeper.retireSessionStartedBefore (proxy/keepalive.go, #527).

func (*Keeper) Shutdown

func (k *Keeper) Shutdown()

Shutdown ends the sweep and drops every held body and credential.

It does not wait for pings already in flight. A ping's goroutine may still finish briefly after Shutdown returns, and its record1 and the entry's Emitter may run then. A host that closes its event sink after Shutdown must tolerate one late report.

func (*Keeper) Start

func (k *Keeper) Start()

Start launches the sweep goroutine. Nil-safe, and a no-op when the kill switch is set.

func (*Keeper) Stats

func (k *Keeper) Stats() Stats

Stats snapshots the keeper's counters.

func (*Keeper) Sweep

func (k *Keeper) Sweep(now time.Time) int

Sweep fires every due ping. Returns how many it started. Exported for tests and replay tooling (Start runs it on a ticker); hosts do not need it.

The map lock is held only to select and to stamp: a ping is an HTTP round trip and holding the lock across it would block every arriving request on this map.

type Key

type Key struct{ Tenant, Session, Thread string }

Key names one tracked THREAD of one session (#423). Thread "" is the primary thread.

type ManualRequest

type ManualRequest struct {
	Key Key
	// MinGap is the least time between two manual pings of this thread; zero is no limit.
	MinGap time.Duration
	// RewriteUSD is what writing the thread's current context into a cold cache would cost: the
	// credit when this ping keeps it warm. The host prices it (it knows the TTL tier the cache
	// was written at); the keeper only carries it onto the report, and zeroes it when the ping
	// read nothing, because then it avoided nothing.
	RewriteUSD float64
}

ManualRequest asks for one ping on Key's thread.

type ManualResult

type ManualResult struct {
	Status    int
	Usage     Usage
	StartedAt time.Time
	// CostUSD is the ping's own cost; Priced is false when the model has no rate.
	CostUSD float64
	Priced  bool
	// AvoidedUSD is the rewrite the ping saved: ManualRequest.RewriteUSD if it read the cache, else 0.
	AvoidedUSD float64
}

ManualResult is what one manual ping did.

type Options

type Options struct {
	// Dispatcher sends pings and prices them. Its Price answering ok=false leaves a ping unpriced,
	// as with no price table.
	Dispatcher dispatch.Dispatcher // required
	// Spare reserves the tenant's spare rate/concurrency headroom for one ping; nil = no limiter.
	Spare func(tenant string, reserveFrac float64) (release func(), err error)
	Now   func() time.Time // nil: time.Now
	// Go runs one ping; nil: `go f()`. Exported for tests and replay tooling (an inline runner
	// makes a replay deterministic); hosts do not need it.
	Go     func(f func())
	OnTick func(now time.Time) // start of every sweep, outside the keeper lock; nil: none
}

Options configures a Keeper. Dispatcher is required; every other field has a default.

type Plan

type Plan struct {
	RefreshedAt time.Time // the last moment the provider's entry is known refreshed
	NextPing    time.Time // startedAt + Idle
	PingsLeft   int
	Idle        time.Duration
}

Plan is one thread's keep-alive plan, for a status line. Times are absolute; the host converts.

type Policy

type Policy struct {
	// KeepAlive turns the mechanism on for this tenant. Off by default.
	KeepAlive bool
	// Idle is X: how long a session must be idle before the first ping, measured from the
	// previous request's START per the provider's documented lifetime rule. Zero disables.
	Idle time.Duration
	// OpenAIIdle is the Responses interval for GPT-5.6+ implicit caches. Zero
	// uses the 28-minute default; it is separate from Anthropic's five-minute
	// schedule so enabling OpenAI does not send wasteful four-minute pings.
	OpenAIIdle time.Duration
	// MaxPings is K: the most pings one idle span may send. Zero disables.
	MaxPings int
	// MaxUSDPerPing refuses a ping whose projected cost exceeds this. PER PING, because ping
	// cost is bimodal (p50 $0.0004, p99 $0.2275, max $0.3780) while a per-SESSION budget
	// truncates exactly the long large-prefix sessions holding the value — capping the
	// window's pings per session at 20 drops the net from +$164 to $92.34.
	//
	// Read it through Ceiling(), never directly: zero here means UNCONFIGURED, and for a spend
	// guard that has to resolve to the default rather than to infinity.
	MaxUSDPerPing float64
	// MinPrefixTokens is the billed-prefix floor (the previous request's cache_read +
	// cache_write) a session must reach before it is pinged. With the first-request skip this
	// sends 8.7x fewer pings for 3.3% less money.
	MinPrefixTokens int
	// HeadTTL1h asks for the one-hour tier on the head breakpoints; HeadTTLMinTokens gates
	// it on request size. Passed through to apply.Opts — see apply/headttl.go.
	HeadTTL1h        bool
	HeadTTLMinTokens int
	// PredictorID optionally names a registered predictor (see predictorFor, and the proxy
	// host's knownPredictorIDs in proxy/keepalivestrategy.go) that pingable() must also clear before a
	// ping fires. "" (every account today, and every strategy created before this field
	// existed) means no predictor gate at all — unchanged behaviour.
	PredictorID string
	// PredictorThreshold is the minimum probability PredictorID must return. Ignored
	// while PredictorID is "".
	PredictorThreshold float64
}

Policy is one tenant's resolved cache policy — the host-level half of the cache story, which no component can reach.

A plain struct in this package rather than config.CacheConfig, for the reason ConfigBuilder exists: proxy does not depend on the configuration loader, so a library host or the bifrost adapter can set this directly.

func (Policy) Ceiling

func (p Policy) Ceiling() float64

Ceiling is the per-ping cost guard that is actually ENFORCED.

The whole of this method is the sentinel. `MaxUSDPerPing == 0` means "nobody configured one", and the shipped code read that as "no cap": `MaxUSDPerPing <= 0 || cost <= cap`. On an account whose keep-alive is OFF the config builder hands the request path a zero Policy, and enabling one session by hand is precisely the use case a per-session override exists for — so the one path where the guard was written to matter was the one path that ran without it, while the arm response cheerfully reported a ceiling of $0.00.

Zero in a money guard resolves to the DEFAULT. A caller that genuinely wants no ceiling has to say so with a negative value, which is a thing somebody has to type on purpose.

func (Policy) On

func (p Policy) On() bool

On reports whether this policy can ping at all. The exported form of on(), for hosts.

type Price

type Price = dispatch.Price

Price is one model's per-token rates in USD — dispatch.Price, so every host's Dispatcher.Price and the keeper price with one formula (Price.CostWithCacheWrite1h).

type Record

type Record struct {
	Key       Key
	StartedAt time.Time // when the upstream request STARTED
	Body      []byte    // exact bytes sent upstream; the keeper copies and masks it
	Provider  bschemas.ModelProvider
	Endpoint  string // upstream host, passed to Dispatcher.Price
	Route     string // upstream path
	Status    int
	Usage     Usage
	// Cred is an opaque credential id the host computes for the request's provider key; ""
	// means a server-held key (never subject to the dead-credential mark, only ever the route
	// breaker). The package scopes it by Key.Tenant itself, so the host passes the bare id with
	// no tenant prefix: the proxy host passes its per-process HMAC of the masked auth headers
	// (proxy/credmask.go credKey).
	Cred string
	// Client is the id the client itself names the session by, when the host keys it
	// differently (Codex's session-id header). "" when there is none. MarkEnded and
	// RetireSessionStartedBefore match on either Key.Session or Client.
	Client  string
	UsageOK bool
	Policy  Policy // resolved by the host
	Tag     string // host label returned by Arrive (proxy: the applied strategy id)
	Agent   string
	Preset  string
	Header  http.Header // the request's headers; only PingHeaders' allow-list is read
	Store   store.Store
	Emitter components.Emitter // nil: components.NopEmitter{}
	// Hold is called once, under the keeper lock, only if the entry is tracked. The host captures
	// the request's credential and returns the Ref it issued for it; the keeper releases it exactly
	// once.
	Hold func() dispatch.Ref
}

Record is one finished upstream request, handed to Keeper.Record by the host.

type Stats

type Stats struct {
	Live    int   `json:"live_sessions"`
	Pings   int64 `json:"pings"`
	Skipped int64 `json:"skipped"`
	Failed  int64 `json:"failed"`
	Wrote   int64 `json:"wrote_instead_of_read"`
	// Missed counts pings that read nothing — a real cache miss, not a failure. A FIRST miss
	// in a row keeps pinging; a SECOND stops it (see noteOutcome), which is why Missed and
	// Wrote can both be 1 for the same session (TestASecondMissInARowStops).
	Missed   int64   `json:"missed"`
	SpentUSD float64 `json:"spend_usd"`
	// RouteTrips counts how many times the route breaker has tripped (main #527, see
	// breaker.go) — a route failing routeFailLimit times in a row. Climbing here, unlike
	// Failed, says the SAME route keeps failing rather than scattered one-off failures.
	RouteTrips int64 `json:"route_trips"`
	// SummarySubstituted, SummarySubstituteFailed and SummarySubstituteOverBudget are
	// cache_aware_summarizer's share of Pings — see fireSummarySubstitute. A deployment running
	// that component should see SummarySubstituted climb instead of a flat Pings/Wrote pair; a
	// SummarySubstituteFailed or SummarySubstituteOverBudget that climbs just as fast says the
	// substitution is being attempted and declining, not that it is dead.
	SummarySubstituted          int64 `json:"keepalive_summary_substituted"`
	SummarySubstituteFailed     int64 `json:"keepalive_summary_substitute_failed"`
	SummarySubstituteOverBudget int64 `json:"keepalive_summary_substitute_over_budget"`
	// SummarySubstitutePhaseMismatch counts a routine `pre_expiry` candidate declined because
	// this particular ping did not land inside the component's own pre-expiry window.
	SummarySubstitutePhaseMismatch int64 `json:"keepalive_summary_substitute_phase_mismatch"`
	// SummarySubstituteNoCandidate/CheckpointExists/InFlight/ConcurrencyFull split what used to
	// be one silent "no substitute" outcome — see fireSummarySubstitute. NoCandidate is the
	// ordinary case for most sessions; the other three, climbing on a session that SHOULD have a
	// registered candidate, are what makes a registration gap diagnosable instead of looking
	// identical to the component simply not being in that tenant's pipeline.
	SummarySubstituteNoCandidate      int64 `json:"keepalive_summary_substitute_no_candidate"`
	SummarySubstituteCheckpointExists int64 `json:"keepalive_summary_substitute_checkpoint_exists"`
	SummarySubstituteInFlight         int64 `json:"keepalive_summary_substitute_in_flight"`
	SummarySubstituteConcurrencyFull  int64 `json:"keepalive_summary_substitute_concurrency_full"`
	// SummarySubstituteRefreshPaid/RefreshNotWorthIt are the money gate's own ledger (#415) for a
	// `pre_expiry` reserve that already exists: Paid when a refresh's expected saving on the
	// eventual cold return covered its own projected cost, NotWorthIt when it did not. Climbing
	// NotWorthIt on a deployment with a lot of idle time between turns is expected and healthy —
	// it is the gate doing its job, not a failure.
	SummarySubstituteRefreshPaid       int64 `json:"keepalive_summary_substitute_refresh_paid"`
	SummarySubstituteRefreshNotWorthIt int64 `json:"keepalive_summary_substitute_refresh_not_worth_it"`
}

Stats is the keeper's own ledger, for /stats. Every field is a way the mechanism can be worthless, which is the point of publishing them together: pings with no conversions is a policy that spends and gains nothing, and `wrote` above zero is a bug.

type TooSoonError

type TooSoonError struct{ RetryAfter time.Duration }

TooSoonError is the per-thread rate limit: the thread was manually pinged less than MinGap ago.

func (*TooSoonError) Error

func (e *TooSoonError) Error() string

type UpstreamError

type UpstreamError struct{ Status int }

UpstreamError is a ping the provider answered with a failure, or answered with nothing usable.

func (*UpstreamError) Error

func (e *UpstreamError) Error() string

type Usage

type Usage struct {
	FreshInput, CacheRead, CacheWrite, Output int64
	// CacheWrite1h is the part of CacheWrite billed at the one-hour tier.
	CacheWrite1h int64
	// StopReason is the response's own terminal stop reason; read only by a policy predictor.
	StopReason string
}

Usage is what one upstream response billed, in the provider's own units. A host fills it in Record for the real request, from whatever it already parses; for a ping the keeper reads it itself from the response body the Dispatcher hands back (PingUsage).

func PingUsage

func PingUsage(raw []byte) Usage

PingUsage reads what a ping's response billed. Pings always send stream:false, so this is one JSON document, never a stream. Anthropic's input_tokens excludes the cached tiers; OpenAI Responses' input_tokens includes cached_tokens, so fresh is the difference — the rule the proxy's own response parser applies (TestPingUsageMatchesResponseUsage in proxy pins the two equal).

Reading the response is wire format, not I/O, which is why it lives in the core: every host hands back the raw body and the keeper decides what it billed.

Jump to

Keyboard shortcuts

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