keepalive

package
v0.7.4-beta.1 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 28 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 (
	ManualHoldMaxPerTenant      = 16
	ManualHoldMaxBytesPerTenant = 32 << 20
)

The caps on manual-only holds PER TENANT. The global caps (MaxSessions, MaxBytes) are shared, and a header any client can send must not let one tenant fill them with many session ids and starve everyone else's keep-alive. Past either cap, that tenant's OLDEST manual-only hold goes first. 16 threads covers a busy session and its sub-agents; 32 MiB is a few large contexts.

View Source
const (
	ReasonNotOptedIn  = "not opted in" // no automatic keep-alive and the request did not ask to be held
	ReasonTooLarge    = "too large"    // the body is over the per-body limit (Policy.BodyLimit)
	ReasonExpired     = "expired"      // it was held, and the hold ran out
	ReasonOverBudget  = "over budget"  // one ping would cost more than the per-ping ceiling
	ReasonUnsupported = "unsupported"  // a shape that cannot be pinged cheaply (thinking enabled, an unsupported route)
	// The reasons on an account whose automatic keep-alive is ON (issue #662). None of these is
	// "not opted in": that stays for a request that carried no opt-in and met no automatic policy.
	ReasonPingsUsed   = "pings used"   // the planned pings ran out and the keeper let go of the thread
	ReasonStopped     = "stopped"      // the keeper stopped the thread after a miss, a refused ping or a failure
	ReasonBelowLimits = "below limits" // the automatic gates refused it: first request, under the minimum prefix, no tool call yet on the thread (#858), or the predictor
	ReasonDone        = "done"         // the thread's last response ended with a terminal tool (#857): the agent is finished, so nothing is pinged
	ReasonNoEntry     = "no entry"     // nothing is known about the thread: a restart, or no request since
	ReasonUnavailable = "unavailable"  // the route is failing in a row, or the provider refused this credential
)

Why a thread cannot be pinged, for the button to say. Pingable is the other half of the answer.

View Source
const (
	EvictReasonBytes = "bytes" // the tenant's held bytes passed ManualHoldMaxBytesPerTenant
	EvictReasonCount = "count" // the tenant's held entries passed ManualHoldMaxPerTenant
)

Why a manual hold was evicted.

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 12 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 (4 bodies at the per-body limit): 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 is the default limit on one held body: a memory guard, not a cost guard. Bytes
	// are a poor proxy for tokens (base64 images and escaped text are big in bytes and cheap in
	// tokens), so the per-ping cost cap (Policy.Ceiling) decides whether a ping is worth it. The cap
	// can judge only a priced model: for an unpriced one the keeper keeps LegacyMaxBodyBytes. This
	// limit only stops one thread from taking more than a quarter of MaxBytes. When the total goes
	// over MaxBytes, evictLocked drops entries. Policy.MaxBodyBytes overrides it per policy.
	MaxBodyBytes = 32 << 20
	// LegacyMaxBodyBytes is the limit before #1100. Set Policy.MaxBodyBytes to it to restore the old behavior.
	LegacyMaxBodyBytes = 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 (
	// DefaultToolWaitMaxPings is the most pings a tool wait gets. A tool almost never runs longer
	// than 13 minutes (0 of 805 main waits locally, 5 of 5,202 on the hosted proxy), so in practice
	// the count stays near the base. Mirrored by config.DefaultKeepAliveToolWaitMaxPings.
	DefaultToolWaitMaxPings = 8
	// DefaultBackgroundExtraPings and DefaultHumanExtraPings are added to the base. Mirrored by
	// config.DefaultKeepAliveBackgroundExtraPings and DefaultKeepAliveHumanExtraPings.
	DefaultBackgroundExtraPings = 3
	DefaultHumanExtraPings      = 1
	// DefaultToolWaitMinPrefix is the prefix floor of a tool wait, background work, a teammate and any subagent wait. Mirrored by
	// config.DefaultKeepAliveToolWaitMinPrefix.
	DefaultToolWaitMinPrefix = 20000
	// MaxWaitPings bounds any plan result unless the base itself is higher. It equals the highest
	// strategy ping count, so the credential hold stays at (11+1) x 299 s = 60 min or less.
	MaxWaitPings = 11
)

The per-wait ping plan (#858). The ping count is chosen when a turn ends, from what the thread waits for. Metadata only: stop reason, tool names, the open-task counts and the shape of the thread id. "Base" is Policy.MaxPings.

own tool (main or subagent)               keep pinging until the result comes, at most 8
main, background work                     base + 3
main, a person                            base + 1
main, a teammate                          base
subagent, its main agent                  base
done, or no tool call yet on the thread   0

The prefix floor follows the same cause (WaitMinPrefix): a tool wait and any subagent wait use the lower tool-wait floor (20k); so do a main thread's waits for background work and for a teammate. A main thread that waits for a person, or for an unknown cause, uses MinPrefixTokens (80k).

The plan applies to the 5-minute tier only. A 1-hour thread keeps its own schedule (Policy.ForOneHour), whose credential hold is already bounded at (K+1) x 59 min.

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 LargeManualHoldBytes = 8 << 20

LargeManualHoldBytes is the size from which a held body counts as "large" for the log line.

View Source
const ManualHoldMax = 300 * time.Second

ManualHoldMax is how long a manual-only hold lives, from the start of the last REAL request on the thread. Nothing else extends it: not a press (a press every 30 s would otherwise hold a caller's credential for as long as they keep pressing), not a ping. So the most a credential is held for the button is ManualHoldMax after the last real request.

ManualHoldMax1h is the manual-only hold of a thread billed at the one-hour tier: the same 59 minutes the schedule pings at. At 300 s the button would never work on a one-hour thread: its cache is still warm then and a press is pointless, and by the time a press matters (near the hour) the hold would be long gone. It is still measured from the last REAL request, and a press does not extend it.

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.

MaxHold1h is the longest a one-hour thread can hold the caller's credential and conversation: (cap + 1) x 59 min = 236 min. The default (1 ping) holds 118 min.

Variables

View Source
var (
	// ErrNotHeld means the keeper holds nothing to ping this thread with: an unknown thread,
	// another tenant's, 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")
)
View Source
var ManualHoldBucketsMiB = [...]int64{1, 4, 8, 16, 32}

ManualHoldBucketsMiB are the upper bounds of the body-size histogram, in MiB.

View Source
var ToolStopReasons = []string{"tool_use", "tool_calls", "function_call"}

ToolStopReasons are the stop reasons that mean "the response called a tool". The dashboard reads the same list when it looks for the first tool call of a thread in its stored rows.

Functions

func BilledOneHour added in v0.7.4

func BilledOneHour(cacheWrite, cacheWrite1h int64, prev bool) bool

BilledOneHour is the response half of ResolveTier: whether the tier the response billed is the one-hour one, once the request asked for it on every breakpoint. A response that wrote tokens bills its tier on them: one hour needs every written token at the one-hour tier. A response that only read the cache bills no tier, so it inherits prev, the thread's last billed one. The proxy's accountant path calls this with its own record of prev, so the two decide a read-only turn alike.

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 IsSubagentThread added in v0.6.6

func IsSubagentThread(threadID string) bool

IsSubagentThread reports whether a thread id names a subagent. The main thread is "".

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).

func ResolveTier added in v0.6.0

func ResolveTier(body []byte, u Usage, usageOK, prev bool) bool

ResolveTier decides whether a thread's cache is a one-hour cache, from the traffic.

The BILLED tier is the source of truth, not the request: a gateway can downgrade a requested 1h to 5m (#330) and still answer 200. One-hour needs both halves:

  • the request asks 1h on EVERY breakpoint. A mixed ask (the proxy's own 1h head over a 5m tail) leaves a tail that expires in five minutes, and a 59-minute ping would refresh only the head.
  • the response billed the one-hour tier for everything it wrote. A turn that only READS the cache (cache_write 0) bills no tier, so it inherits the thread's last billed one (prev).

Anything else is five minutes, which is the schedule the keeper always ran. Pure, and false on any doubt.

func WindowsApply added in v0.6.6

func WindowsApply(cause string, subagent bool) bool

WindowsApply reports whether a manager strategy's time windows apply to a thread that waits for cause. Only a wait for a person follows working hours. A tool, a background task, a teammate and a main agent answer at night as fast as in the day. A subagent's "human" wait (end_turn, or the SubagentHandback tool) is a wait for its main agent, not for a person.

Types

type EntryView

type EntryView struct {
	Pings, Turn    int
	Prefix         int64
	PingUSD, Spent float64
	Refreshed      int64
	Stopped        bool
	TTL1h          bool // the thread's cache was billed at the one-hour tier
	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 or WROTE 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) ManualHoldSnapshot added in v0.7.4

func (k *Keeper) ManualHoldSnapshot() ManualHoldSnapshot

ManualHoldSnapshot reads the manual-hold measures. A nil Keeper reads as zero.

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) PingStates added in v0.5.4

func (k *Keeper) PingStates(tenant string, all bool, session string) PingStateMap

PingStates says, per thread of one session, whether a manual ping can work now and, when not, why. all drops the tenant filter, as Plans does. It is PingNow's own "held" test, so a client that hides the button on Pingable=false never meets ErrNotHeld. nil means the keeper cannot say.

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.

func (*Keeper) ToolSeen added in v0.6.6

func (k *Keeper) ToolSeen(key Key) bool

ToolSeen reports whether a response of the thread has called a tool (#858). Cheap: one map read under the keeper lock. The host uses it to keep nothing for a thread that the plan will not ping.

func (*Keeper) WaitingFor added in v0.6.6

func (k *Keeper) WaitingFor(key Key, names []string, incomplete bool, stopReason string, usageOK bool) string

WaitingFor is the wait cause of a response, from its tool names and stop reason and the thread's open-task counts (Options.OpenTasks). The open counts are as of the last request the host's tracker observed, which can lag by one request: a stale count reads as "a person", the cheaper plan.

type Key

type Key struct{ Tenant, Session, Thread string }

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

type ManualHoldSnapshot added in v0.7.4

type ManualHoldSnapshot struct {
	EvictedBytes, EvictedCount int64
	TooLarge                   int64
	Buckets                    [len(ManualHoldBucketsMiB) + 1]int64
	SizeSum, SizeCount         int64
	Tenants                    []ManualHoldTenant // sorted by tenant id; only tenants holding now
}

ManualHoldSnapshot is one scrape's reading. Buckets are NOT cumulative.

type ManualHoldTenant added in v0.7.4

type ManualHoldTenant struct {
	Tenant string
	Bytes  int64
	Count  int
}

ManualHoldTenant is one tenant's current manual holds.

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
	// OpenTasks reports a thread's open background-task and teammate-wait counts, for the wait cause
	// the sweep stores with a held answer (#404, #453). nil: 0, 0.
	OpenTasks func(tenant, session, thread string) (background, teammate int)
	// TerminalTools names the tools whose call ends an agent (#857). A thread whose last response
	// ends with one is done: it is never pinged. nil: the shipped list. A non-nil
	// empty list turns the rule off, which is the behavior before #857.
	TerminalTools []string
}

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

type PingState added in v0.5.4

type PingState struct {
	Pingable bool
	Reason   string
}

PingState says whether a thread can be pinged right now, and if not, why.

type PingStateMap added in v0.5.4

type PingStateMap map[string]PingState

PingStateMap is one session's threads ("" = main). A thread with no entry was never held.

func (PingStateMap) For added in v0.5.4

func (m PingStateMap) For(thread string) PingState

For is the thread's state; a thread nothing is known about has "no entry".

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
	// Idle1h and MaxPings1h are X and K for a thread whose cache the provider billed at the
	// one-hour tier. Idle and MaxPings above stay the five-minute schedule. Record swaps the pair
	// in per entry (see ForOneHour), so each thread follows the TTL it was actually granted.
	// Zero means the shipped default (modelinfo.AnthropicDefaultKeepAliveIdle1h and MaxPings1h).
	Idle1h     time.Duration
	MaxPings1h 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
	// MaxBodyBytes is the largest request body the keeper holds for one thread (a memory guard).
	// Zero means MaxBodyBytes (32 MiB). Set LegacyMaxBodyBytes (8 MiB) for the old limit. Read it through
	// BodyLimit().
	MaxBodyBytes int
	// 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; HeadTTLMinBytes gates
	// it on the request body size in bytes. Passed through to apply.Opts — see apply/headttl.go.
	HeadTTL1h       bool
	HeadTTLMinBytes int
	// HeadTTLMinTokens is DEPRECATED: the old name of HeadTTLMinBytes, kept so a host that still
	// sets it builds and behaves as before. Read the gate through HeadTTLGateBytes.
	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
	// WaitPlan turns on the per-wait ping plan (waitplan.go, #858): the ping count follows what the
	// thread waits for, time windows apply only to a wait for a person, the sweep question is not
	// asked during a tool wait, and a thread with no tool call yet is not pinged. False is the
	// behavior before #858: MaxPings for every wait. The zero Policy has it off, so a host that builds a
	// Policy by hand keeps the old behavior until it asks.
	WaitPlan bool
	// ToolWaitMaxPings, BackgroundExtraPings and HumanExtraPings tune the plan. Zero means the shipped
	// default (DefaultToolWaitMaxPings, DefaultBackgroundExtraPings, DefaultHumanExtraPings). Read only
	// while WaitPlan is on.
	ToolWaitMaxPings int
	// ToolWaitMinPrefix is the floor for a tool wait, background work, a teammate and for any wait of a subagent thread (see
	// WaitMinPrefix). Zero means DefaultToolWaitMinPrefix. Read only while WaitPlan is on.
	ToolWaitMinPrefix    int
	BackgroundExtraPings int
	HumanExtraPings      int
	// ManualHold is the host's reading of an opt-in on THIS request (the proxy: the
	// x-context-guru-ping header): keep this thread for the Ping button even though no automatic
	// ping will be sent for it. It never turns the schedule on, and never widens what is held: the
	// entry lives ManualHoldMax (ManualHoldMax1h on a one-hour thread) and is released and zeroized then. See manualhold.go.
	ManualHold bool
}

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) BodyLimit added in v0.7.3

func (p Policy) BodyLimit() int

BodyLimit is the per-body byte limit in force: MaxBodyBytes when unset, never above MaxBytes.

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) ForOneHour added in v0.6.0

func (p Policy) ForOneHour() Policy

ForOneHour swaps in the one-hour schedule for a thread billed at the one-hour tier. Zero values resolve to the shipped defaults, the same way config.CacheConfig.Resolved does for the config path (strategies and overrides build a Policy without going through it).

MaxPings is capped at modelinfo.AnthropicMaxKeepAliveMaxPings1h whatever the source, so the credential hold of a one-hour thread never exceeds MaxHold1h.

A policy whose Idle is already past the five-minute lifetime is an EXPLICIT one-hour schedule (a manager strategy with HeadTTL1h, whose band allows up to 3590 s) and is left alone: no 5-minute Idle can be that long, because config and the override band refuse it.

func (Policy) HeadTTLGateBytes added in v0.6.5

func (p Policy) HeadTTLGateBytes() int

HeadTTLGateBytes is the head-TTL size gate in bytes of the request body: HeadTTLMinBytes, or the deprecated HeadTTLMinTokens x 4 when only that is set. 0 means the upgrade is off.

func (Policy) LowestMinPrefix added in v0.7.2

func (p Policy) LowestMinPrefix() int

LowestMinPrefix is the lowest floor any wait can have. A replay gates on it in SQL and then applies SpanPrefixOK to each span.

func (Policy) On

func (p Policy) On() bool

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

func (Policy) SpanPings added in v0.6.6

func (p Policy) SpanPings(s SpanFacts) (pings int, idle time.Duration)

SpanPings is the schedule the plan gives the idle span after a response, from the facts a stored row holds: the ping count and the spacing between pings. It is the keeper's decision in one place, for a replay. p.Idle is the 5-minute spacing; p.KeepAlive must be on.

  • 5-minute tier: the count WaitPings gives for the wait cause, at p.Idle. Only when p.Idle is under 300 s, as in the keeper; at 300 s or more the base count stays.
  • 1-hour tier: the schedule of ForOneHour (MaxPings1h pings, Idle1h apart; 1 ping at 59 minutes by default).
  • 0 pings for a thread with no tool call yet (the no-tool rule) and for a finished thread (done). The no-tool rule holds on both tiers.
  • A stored "retry" wait (a non-2xx response) gets 0 pings: the keeper does not track a response whose status is not 2xx (Record returns first), so it holds nothing for the span.
  • MaxPings with WaitPlan off, for OpenAI, and for a row that stored neither a wait cause nor a stop reason (an old row: nothing to replay from).

TestDashboardReplayMatchesTheKeeper (package dash) runs the keeper and this function on the same cases.

func (Policy) SpanPrefixOK added in v0.7.2

func (p Policy) SpanPrefixOK(s SpanFacts, prefix int64) bool

SpanPrefixOK reports whether a stored span of the given prefix clears the floor of its wait. It is the replay's form of the keeper's gate, with the cause read as storedWait reads it. A row with no stored cause and no stop reason (an old row) gets the general floor, also on a subagent thread: the replay then under-counts those rows, the safe direction.

func (Policy) WaitMinPrefix added in v0.7.2

func (p Policy) WaitMinPrefix(cause string, subagent bool) int

WaitMinPrefix is the billed-prefix floor for a thread that waits for cause. With WaitPlan off, or when the cause is unknown ("": the plan did not apply), it is MinPrefixTokens. A tool wait, a wait for background work or a teammate, and any wait of a subagent thread, use the tool-wait floor, which never raises MinPrefixTokens. A main thread that waits for a person, or for an unknown cause, keeps MinPrefixTokens.

func (Policy) WaitPings added in v0.6.6

func (p Policy) WaitPings(cause string, subagent bool) int

WaitPings is the ping count for a thread that waits for cause. With WaitPlan off it is MaxPings.

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
	// TouchAlias is the key of the cold decision's liveness clock for this request (apply's
	// Trace.TouchAlias), derived from the request as it ARRIVED. A ping touches this key. "" means
	// the host has none, and the touch derives its key from Body, which is right only when the
	// host sent the transcript unchanged. Tool deferral changes the head, so the proxy sets it.
	TouchAlias string
	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
	// ToolUseNames is every tool_use name the response carried, in order. Read only to classify what
	// the thread is about to wait on (waitcause.ClassifyWaitingFor), which the sweep's held answer
	// stores (#404, #453). A field of Record, not of Usage, so Usage stays comparable.
	ToolUseNames []string
	// ToolUseIncomplete: ToolUseNames may miss the true last call (a spliced sniff window). The
	// terminal-tool rule is then off for this response, so the thread is pinged as before (#857).
	ToolUseIncomplete 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 SpanFacts added in v0.6.6

type SpanFacts struct {
	// Cause is the row's stored waiting_for ("" on an old row).
	Cause string
	// StopReason is the row's stored stop reason ("" on an old row).
	StopReason string
	// Subagent is true for a subagent thread (IsSubagentThread).
	Subagent bool
	// ToolSeen is true when this response or an earlier one of the thread called a tool.
	ToolSeen bool
	// OpenAI is true for an OpenAI request. The plan does not cover OpenAI: it keeps the base count.
	OpenAI bool
	// OneHour is true when the thread's BILLED tier is the 1-hour one. ResolveTier needs EVERY
	// breakpoint to ask 1 hour; a stored row keeps only "ANY breakpoint asked 1 hour" (cache_ttl), so a
	// replay can call a mixed request 1-hour when the keeper keeps it on 5 minutes. The billed write
	// (cache_write_1h >= cache_write) is the other half of the rule. The thread then keeps the schedule
	// of Policy.ForOneHour.
	OneHour bool
}

SpanFacts is what a stored request row says about the idle span that follows it: the facts the plan needs. The dashboard replays the plan from them (Policy.SpanPings).

type Stats

type Stats struct {
	Live    int   `json:"live_sessions"`
	Pings   int64 `json:"pings"`
	Skipped int64 `json:"skipped"`
	Failed  int64 `json:"failed"`
	// TimedOut is the part of Failed that ran to pingTimeout (#754). Unlike a fast failure, such a
	// ping was probably billed, so each one is booked in SpentUSD at its projected cost.
	TimedOut int64 `json:"timed_out"`
	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"`
	// Sweep* are extract_llm_sweep's share of Pings (#404): the question it sends in place of a ping.
	// SweepSubstituted climbing while SweepAsked/SweepHeld lag means the question reaches the
	// provider and its answers do not parse. SweepModelDeclined is sweep_model_declined (#422): pings
	// sent plain because the question would break the cache on that model. SweepExtraAsked and
	// SummaryExtraSent count the extra request after the last planned ping that follows a text turn
	// (#776), by kind. SweepExtraSkipped counts every extra slot that sent nothing at all: the thread
	// was busy, the summary declined (the sweep does not ask after it), or the question declined or
	// failed. Each of those also counts under its own substitute reason.
	SweepSubstituted   int64 `json:"keepalive_sweep_substituted"`
	SweepAskFailed     int64 `json:"keepalive_sweep_ask_failed"`
	SweepOverBudget    int64 `json:"keepalive_sweep_over_budget"`
	SweepExtraAsked    int64 `json:"keepalive_sweep_extra_asked"`
	SweepExtraSkipped  int64 `json:"keepalive_sweep_extra_skipped"`
	SummaryExtraSent   int64 `json:"keepalive_summary_extra_sent"`
	SweepAsked         int64 `json:"sweep_asked"`
	SweepHeld          int64 `json:"sweep_held"`
	SweepModelDeclined int64 `json:"sweep_model_declined"`
	// SweepSummaryOwnedPing is #404 point 10: pings where the summarizer had a candidate, so it owned the
	// ping and the sweep did not ask (also when the summary then declined). SweepSummaryInFlight: a
	// summary was already running. SweepThreadBusy: an earlier substitute still held the thread.
	SweepSummaryOwnedPing int64 `json:"sweep_summary_owned_ping"`
	SweepSummaryInFlight  int64 `json:"sweep_summary_in_flight"`
	SweepThreadBusy       int64 `json:"sweep_ping_thread_busy"`
	SweepNoInventory      int64 `json:"sweep_no_inventory"`
	SweepAlreadyAsked     int64 `json:"sweep_already_asked"`
	SweepNoCandidate      int64 `json:"sweep_no_candidate"`
	SweepHoldNoToolID     int64 `json:"sweep_hold_no_tool_id"`
	SweepPanics           int64 `json:"sweep_ping_panics"`
	SweepConcurrency      int64 `json:"sweep_concurrency_full"`
	SweepNotRegistered    int64 `json:"sweep_not_registered"`
	// SweepAskBatches counts the batches asked in all (#132): a sweep of 20 candidates is 2 batches.
	// SweepBatchFailed counts batches that failed open, SweepBatchFailedBy giving the reason. The answer
	// cost sums every batch.
	SweepAskBatches    int64            `json:"sweep_ask_batches"`
	SweepBatchFailed   int64            `json:"sweep_batch_failed"`
	SweepBatchFailedBy map[string]int64 `json:"sweep_batch_failed_by,omitempty"`
	// SweepBatchSkipped counts batches never started because the sweep's deadline passed (the per-request
	// event is sweep_batch_skipped_deadline). SweepBatchOverCap counts EVERY candidate left unasked by a
	// limit: max_ask_batches, or the cost ceiling lowering the count. SweepBatchesLowered counts sweeps
	// where the per-ping cost ceiling admitted fewer questions than planned.
	SweepBatchSkipped int64 `json:"sweep_batch_skipped"`
	// SweepBatchByIndex tells the batches apart by their position in a sweep: asked, items carried, verdicts
	// judged and fabricated quotes. A fabrication rate that differs between batch 0 and the later ones is a
	// batch effect; the same everywhere, it is the model.
	SweepBatchByIndex   []offload.SweepBatchIndexStats `json:"sweep_batch_by_index,omitempty"`
	SweepBatchOverCap   int64                          `json:"sweep_batch_over_cap"`
	SweepBatchesLowered int64                          `json:"sweep_batches_lowered"`
	// SweepDrops is what became of the drops the sweep applied (#404 point 7), overall and for the
	// busiest threads, under hashed labels. The false-drop rate is the number to pull the sweep from
	// xhigh on. Metadata only: counts, never content, never a session id.
	SweepDrops *SweepDropStats `json:"sweep_drops,omitempty"`
	// SweepGates counts the adjudication's own gate and event names across ping-time questions
	// (sweep_kept, sweep_unparseable, sweep_dropped, ...), the counters a request's Report carries
	// for an in-request question.
	SweepGates map[string]int64 `json:"sweep_gates,omitempty"`
	// SweepWarm is the warm path's ledger (#491). Absent unless the path ran.
	SweepWarm *SweepWarmStats `json:"sweep_warm,omitempty"`
}

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 SweepDropStats added in v0.6.0

type SweepDropStats struct {
	Applied              int64 `json:"applied"`
	AppliedCold          int64 `json:"applied_cold"`
	AppliedChangedPrefix int64 `json:"applied_changed_prefix"`
	// AppliedWarm is the warm path's share of Applied (#491). The warm false-drop rate is beside the
	// cold one so the two can be read apart.
	AppliedWarm       int64   `json:"applied_warm"`
	FalseDropsWarm    int64   `json:"false_drops_warm"`
	FalseDropRateWarm float64 `json:"false_drop_rate_warm"`
	FalseDropRateCold float64 `json:"false_drop_rate_cold"`
	ApplyDeclined     int64   `json:"apply_declined"`
	Referenced        int64   `json:"referenced_later"`
	Expanded          int64   `json:"expanded"`
	FalseDrops        int64   `json:"false_drops"`
	FalseDropRate     float64 `json:"false_drop_rate"`
	ExpandEvents      int64   `json:"expand_events"`
	ExpandTokens      int64   `json:"expand_tokens"`
	// ApplyPanics counts recovered cold-apply panics; HeldStaleWrites older answers refused.
	ApplyPanics int64 `json:"apply_panics"`
	// Threads are the busiest threads by drops applied, most first.
	Threads []SweepDropThread `json:"threads,omitempty"`
}

SweepDropStats is offload.SweepDropStats in /stats shape.

type SweepDropThread added in v0.6.0

type SweepDropThread struct {
	Thread        string  `json:"thread"`
	Applied       int64   `json:"applied"`
	FalseDrops    int64   `json:"false_drops"`
	FalseDropRate float64 `json:"false_drop_rate"`
}

SweepDropThread is one thread's share, under a hash label that is not the session id.

type SweepWarmStats added in v0.7.2

type SweepWarmStats struct {
	Fired             int64            `json:"fired"`
	Asked             int64            `json:"asked"`
	Held              int64            `json:"held"`
	Failed            int64            `json:"failed"`
	NotWorth          int64            `json:"not_worth"`
	NoBilledSize      int64            `json:"no_billed_size"`
	ThreadBusy        int64            `json:"thread_busy"`
	ModelDeclined     int64            `json:"model_declined"`
	ConcurrencyFull   int64            `json:"concurrency_full"`
	HeldExpired       int64            `json:"held_expired"`
	HeldShrunk        int64            `json:"held_shrunk"`
	CarriedMerged     int64            `json:"carried_merged"`
	CarriedOverridden int64            `json:"carried_overridden"`
	CarriedRefused    int64            `json:"carried_refused"`
	CarriedExpired    int64            `json:"carried_expired"`
	CarriedCapped     int64            `json:"carried_capped"`
	NotRegistered     int64            `json:"not_registered"`
	ThreadsFull       int64            `json:"threads_full"`
	AlreadyAsked      int64            `json:"already_asked"`
	NoInventory       int64            `json:"no_inventory"`
	Gates             map[string]int64 `json:"gates,omitempty"`
	// TriggerRefusals counts the refusals at the trigger, by reason. Recent is the last warm sweeps
	// applied, each with the gate's numbers, the conversation before and after, and the net it expected.
	TriggerRefusals map[string]int64 `json:"trigger_refusals,omitempty"`
	// GatePriceModel is set only when the DIAGNOSTIC warm_gate_price_model is on: the gate priced with that
	// model, not the request's. A run with it is not a normal run. PriceModelUnknown counts gate decisions
	// where that model was not on the rate card and the built-in rates were used.
	GatePriceModel    string              `json:"gate_price_model,omitempty"`
	PriceModelUnknown int64               `json:"price_model_unknown,omitempty"`
	Recent            []offload.WarmSweep `json:"recent_sweeps,omitempty"`
	// RecentDecisions is every trigger and apply-gate decision, accepted or refused (last 50), with D,
	// R, N, the weight, the ratios, deep or not and the reason: why a run refused reads as numbers.
	RecentDecisions []offload.WarmDecision `json:"recent_decisions,omitempty"`
	GateAccept      int64                  `json:"gate_accept"`
	GateRefuse      int64                  `json:"gate_refuse"`
	GateReasons     map[string]int64       `json:"gate_refuse_reasons,omitempty"`
	Panics          int64                  `json:"panics"`
	// V3 is sweep v3: why cut attempts were refused, the rule and judge drops, and each cut's D/P and P/C.
	V3 *offload.V3Stats `json:"v3,omitempty"`
}

SweepWarmStats is offload.SweepWarmStats in /stats shape: how often the trigger fired, what the questions and the held answers did, and the economic gate's accepts and refusals with the reasons.

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. Both rules live in internal/providerusage, which the proxy's own response parser uses too.

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