keepalive

package
v0.7.10 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 31 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 (
	ManualBlockAtOneHour = "at one hour"
	ManualBlockCold      = "cold"
)

Why a manual ping is refused before the keeper is asked, from the host's view of the thread's cache.

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 operator's own per-ping cap (keepalive_max_usd_per_ping)
	ReasonNotWorth    = "not worth it" // the planned pings cost at least as much as the one cache miss they protect (the value rule)
	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 (
	// MaxOverrideUntil caps how far ahead an override may reach.
	MaxOverrideUntil = 12 * time.Hour
	// DefaultOverrideUntil is what the dialog offers.
	DefaultOverrideUntil = time.Hour
	// The idle interval's band. Below 60 s a ping lands inside the previous one's own refresh.
	// Above MaxOverrideIdle the first ping arrives after the 5-minute lifetime has lapsed and pays
	// a 1.25x WRITE, the charge the mechanism exists to avoid.
	MinOverrideIdle = 60 * time.Second
	MaxOverrideIdle = modelinfo.AnthropicCacheLifetime5m - 10*time.Second
	// OneHourIdleFloor is the Idle at or above which a policy is an EXPLICIT 1-hour schedule (a
	// strategy with HeadTTL1h): no 5-minute Idle can reach it, because MaxOverrideIdle refuses it.
	// Such a policy does not take the per-wait plan.
	OneHourIdleFloor = modelinfo.AnthropicCacheTTL5m
	// The ping-count band. The upper end is bounded again, and more tightly, by MaxOverrideHold.
	MinOverridePings = 1
	MaxOverridePings = 11
	// MaxOverrideHold is the operator's ceiling on the CREDENTIAL HOLD an override may buy. The hard
	// deadline is (K+1) x X. It is currently unreachable: the two caps above bound (K+1) x X at
	// 12 x 290 s = 58 minutes. It stays as the bound that keeps holding if either is widened.
	MaxOverrideHold = time.Hour
	// MaxOverridesPerTenant and MaxOverridesTotal bound the host's map: many accounts with a few,
	// or one account with many.
	MaxOverridesPerTenant = 64
	MaxOverridesTotal     = 512
	// MaxSessionIDBytes refuses an implausible session id before it is used as a map key.
	MaxSessionIDBytes = 200
	// OverrideArmsPerHour is the arm rate per account. Arming is a spend authorization, so it is
	// rate-limited like one.
	OverrideArmsPerHour = 30
)

Override bounds. Every one is a refusal with a reason, not a silent clamp: a clamp on a spend authorization tells the person they got what they asked for when they did not.

View Source
const (
	MaxOverrideIdle1h  = modelinfo.AnthropicCacheLifetime1h - 10*time.Second
	MaxOverridePings1h = 3
)

The 1-hour tier's idle and ping band, parallel to the 5-minute band (MinOverrideIdle .. MaxOverrideIdle, MinOverridePings .. MaxOverridePings) but scaled to the hour-long lifetime a HeadTTL1h strategy holds.

MaxOverrideIdle1h keeps the same 10-second margin MaxOverrideIdle leaves against the 5-minute lifetime, applied to the 1-hour one. Past it the first ping arrives after the lifetime has lapsed. MaxOverridePings1h is far tighter than MaxOverridePings: a caller-pays credential is held in memory for up to (MaxPings+1) x Idle. At the 1-hour tier the 5-minute count would hold it for up to half a day. 3 keeps the worst case at (3+1) x 3590 s, about 4 hours, and the 1-hour tier needs far fewer refreshes to hold the same span.

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 CompactRaceMargin = 2 * time.Second

CompactRaceMargin bounds how late a SessionStart compact event may arrive after the request that follows the compaction started. Measured hook-to-proxy delivery is 0.2-0.8 s; the old prefix's last request (the compaction call itself) started tens of seconds earlier. Known limitation: a ping also moves startedAt, so an old-prefix entry pinged within the margin is not retired by the event and is pinged at most once more before its next idle check stops it.

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 DefaultOneHourRebuildTokens = 150000

DefaultOneHourRebuildTokens is D's default threshold.

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 ManualPingMinGap = 30 * time.Second

ManualPingMinGap is the least time between two manual pings of the same thread.

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")
	// ErrAtOneHour means the thread's entry is at 1 hour after a free 1-hour ping. A press sends 5-minute
	// markers, and a read at 5 minutes moves the entry back to 5 minutes, so the press would shorten it (#1259).
	ErrAtOneHour = errors.New("keepalive: this thread's entry is at 1 hour from a free 1-hour ping; a manual ping would shorten it to 5 minutes")
)
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 BestStrategy added in v0.7.8

func BestStrategy(strategies []tenant.Strategy, tenantID string, now time.Time, ignoreWindows bool) *tenant.Strategy

BestStrategy returns the highest-priority ACTIVE strategy of the list that matches tenantID at now, or nil. With ignoreWindows the time windows are ignored (#858): the strategy that targets the tenant applies as if its window were open. BetterStrategy picks among several.

func BetterStrategy added in v0.7.8

func BetterStrategy(candidate, current *tenant.Strategy) bool

BetterStrategy reports whether candidate beats current under the fixed precedence: a list-target strategy beats an all-target one (more specific wins); among equally specific matches, the most recently updated wins. Not configurable: one less knob a manager can get wrong.

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 CanKeepAlive added in v0.7.8

func CanKeepAlive(pol Policy, toolSeen func() bool) bool

CanKeepAlive is the record-time gate on a resolved policy: the policy is on, and a thread with no tool call yet is not pinged (#858) when the per-wait plan is on, so it keeps no copy either. toolSeen is read only when the plan is on. The host checks the kill switch, the audit sink, the provider and the session first.

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 "". It is thread.IsAgentThread, so the keeper and the resolver share one rule.

func KnownPredictorIDs added in v0.7.8

func KnownPredictorIDs() map[string]bool

KnownPredictorIDs returns a copy of the registered predictor names, so no caller shares the package's own map.

func LongWait added in v0.7.5

func LongWait(cause string, subagent bool) bool

LongWait reports whether a thread that waits for cause waits long enough for the 1-hour-on-wait ping (#1243): the MAIN agent, waiting for a person, a teammate, background work, or a cause the proxy cannot name. MAIN AGENT ONLY: a subagent thread is never a long wait here, whatever its cause, and keeps auto's 5-minute pings. A tool wait, a retry and a finished thread are short or over. The classification is waitcause's. This only groups its values.

func ManualPingBlock added in v0.7.8

func ManualPingBlock(oneHourLive bool, lastTouch time.Time, ttl time.Duration, now time.Time) string

ManualPingBlock is the cold gate of the Ping button. It reports why a press must not be sent, or "" when it may be.

A live free 1-hour ping comes first: the billed tier is 5 minutes, so the cold gate would give a press 5 to 60 minutes after the ping the wrong reason ("cold") for an entry that is still warm (#1259), and a press would move the entry back to 5 minutes. Then the cold gate: the entry is cold when its last touch (lastTouch) plus the TTL it was written at has passed. oneHourLive is Keeper.OneHourTouchLive.

func ManualSavedUSD deprecated added in v0.7.8

func ManualSavedUSD(rewriteUSD float64, res ManualResult) float64

ManualSavedUSD is the money one manual ping kept by an estimate: the rewrite it avoided less its own cost.

Deprecated: nothing books or shows it any more (#1460). The accountant credits the rescue on the thread's next real request. It stays so that importers still build.

func MayHoldCredentials added in v0.7.10

func MayHoldCredentials(hosted func() bool, hasAuditSink bool) (ok bool)

MayHoldCredentials answers who may keep a caller's credential in memory for pings.

The "no audit sink, no retention" rule applies only to a hosted, multi-tenant host, where the process holds other people's credentials: there, a deployment with no audit sink holds nothing. A single-tenant host holds only its own user's credential, in the user's own process, and needs no sink. A library host (Cortex, bifrost) never asks: its dispatcher resolves the credential.

A credential held this way lives in process memory only. No caller of this function may write it to a store, a file, a log or a metric.

hosted is a function so that a failure while reading the signal can be caught here. The rule fails closed to the old behavior: when hosted panics, the answer is hasAuditSink, which is what every host answered before this rule was narrowed.

func MissUSD added in v0.7.10

func MissUSD(price Price, model string, prefix int64, oneHour bool) float64

MissUSD is the extra cost of one cache miss on a prefix: the write rate minus the read rate, on every prefix token. oneHour picks the 1-hour write rate. Zero when the price is unknown.

func NormalizeSignal added in v0.7.8

func NormalizeSignal(event, kind string) (string, bool)

NormalizeSignal checks a client lifecycle event against the closed sets and returns the kind to use. A SessionEnd reason a newer client adds still means the session ended, so it reads as "other" instead of being refused and silently losing the feature. ok is false for an event or a kind outside the sets.

func PingHeaders

func PingHeaders(src http.Header) http.Header

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

func PingPrompt added in v0.7.10

func PingPrompt(prefix int64) int64

PingPrompt is the prompt size of a ping on a cached prefix. A host that prices a ping outside the keeper (the proxy's keep-alive control, the dashboard) calls it, so every price is read at the same tier.

func PingUSD added in v0.7.8

func PingUSD(prefixTokens int64, cacheReadUSDPerToken, outputUSD float64) float64

PingUSD is the worst-case cost of one ping on a prefix of prefixTokens tokens: a cache read of the prefix plus the output of the ping. Per-ping cost is bimodal, so it is priced from the session's own last billed prefix and its own model's rates, never a service-wide average.

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 ResolveHeadTTL added in v0.7.8

func ResolveHeadTTL(strategies []tenant.Strategy, tenantID string, now time.Time,
	accountHeadTTL1h bool, accountHeadTTLMinBytes int) (bool, int)

ResolveHeadTTL is the write-tier half of the strategy: it resolves the strategy that matches at now (windows respected) and returns the account's own head-TTL fallback unchanged when none matches or the matching one does not ask for the 1-hour head. A strategy can only turn HeadTTL1h ON, never off. The ping half (Resolve) and this half resolve the same strategy, except that Resolve ignores the windows for a wait that is not for a person (#858) and this half never does: the head-TTL write tier is a cost decision taken at write time, before the response.

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 ResolveWithWindows added in v0.7.8

func ResolveWithWindows(in WindowsInput) (Policy, string, *TaskCounts)

ResolveWithWindows resolves the policy of one finished response with the wait cause in hand.

Time windows gate only a wait for a person (#858), so the strategy is resolved with the wait cause of the response that ended this turn. The body reading joins only where the per-wait plan changes the count (the 5-minute tier, not OpenAI, Idle under 300 s: Record's own guard), for the windows as for the plan (#1227). Elsewhere the tracker-only cause decides.

Ignoring the windows must never refuse a hold today's decision makes, nor plan fewer pings. Today's policy is the one the windows give; the wide one is the policy with them ignored. When the two readings differ, the one that holds the wait, or plans more pings, wins.

It returns the policy, the applied strategy tag, and the open counts Record must use (nil when the reading did not apply).

func StrategyTZ added in v0.7.8

func StrategyTZ(strategies []tenant.Strategy, tenantID string) string

StrategyTZ is the timezone an account's keep-alive windows are written in: the first window of the highest-priority active strategy that targets it (at any time of day), else tenant.DefaultStrategyTZ. Reports that show time of day use it, so a cell matches a window the user sets.

func ValidPredictorRef added in v0.7.8

func ValidPredictorRef(predictorID string, threshold float64) error

ValidPredictorRef checks predictorID against the registered names (empty is always valid: no predictor gate) and the threshold's own shape.

A named predictor with a threshold <= 0 is refused: the probability functions only return values in [0,1], so `p >= threshold` is true for every prediction at 0, and the gate would still ping on the arm's own schedule without gating anything.

func ValidPredictorRefIn added in v0.7.8

func ValidPredictorRefIn(known map[string]bool, predictorID string, threshold float64) error

ValidPredictorRefIn is ValidPredictorRef against a caller-supplied set of registered names.

func ValidStrategyBounds added in v0.7.8

func ValidStrategyBounds(idle time.Duration, pings, minPrefix int, maxUSDPerPing float64,
	headTTL1h bool, headTTLMinTokens int) error

ValidStrategyBounds checks the numeric fields of a strategy against the same bounds an override uses (ValidIdleBand, ValidPingBand): a strategy is a broader-blast-radius version of the same spend authorization, so it gets at least as tight a check. With headTTL1h the band widens to MaxOverrideIdle1h / MaxOverridePings1h, since a 1-hour hold cannot fit in the 5-minute band.

MaxUSDPerPing is the one field an override does not expose; a strategy may set it because this is an audited manager action. It must be non-negative, and 0 means the package default (Policy.Ceiling).

headTTLMinTokens is the stored, token-named field, read as tokens x 4 bytes of request body (ResolveHeadTTL). Once headTTL1h is set, 0 is refused: the apply gate treats 0 as "never upgrade", so such a strategy would pay the 1-hour ping schedule for a benefit that never comes.

func ValidWindows added in v0.7.8

func ValidWindows(windows []tenant.Window) error

ValidWindows checks that a strategy has at least one window (one with no schedule can never fire) and that each one is valid.

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 CampaignDecision added in v0.7.8

type CampaignDecision struct {
	// Active is true when an ACTIVE-mode campaign scored this response (not shadow mode, not
	// opted out).
	Active bool
	// Tag names the campaign on the ping rows. Read only when Active.
	Tag string
	// Apply writes the campaign's ping count onto a policy. Read only when Active.
	Apply func(Policy) Policy
}

CampaignDecision is what a learned campaign tells the resolver about one finished response. The zero value means "no decision". The host scores the campaign and fills it in. The resolver only reads it.

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) ApplyClientSignal added in v0.7.8

func (k *Keeper) ApplyClientSignal(tenantID, scoped, event, kind string, now time.Time,
	afterRetire func(SignalResult)) SignalResult

ApplyClientSignal applies one client lifecycle event to the session and says what it did.

  • SessionEnd, any reason (even clear or resume): retires every entry of the id the event names, because that id will not send its next request from this process, then marks it ended. If it does (a resumed session), the request starts after the mark and is tracked normally (EndedAfter).
  • SessionStart with kind "compact": compaction replaced the conversation, so every entry held for the session caches the old prefix, which no later request will send. The session itself goes on, so there is no end mark. The hook sends in the background, so the event can arrive after the post-compaction request started: only entries whose last request started CompactRaceMargin before the arrival are the old prefix.
  • Everything else is accepted and never acted on. Notification: offline, the pings sent on tool-wait rows that outlast 60 s (the nearest proxy for "blocked on a human") net positive, so a rule that stops them would lose money.

afterRetire runs after the retirement and before the end mark, so a host can tell a campaign the session ended (nil is allowed).

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) OneHourFirst added in v0.7.5

func (k *Keeper) OneHourFirst(tenant, session, threadID string, provider bschemas.ModelProvider, endpoint, route, model string, toolsDeclared bool, mode OneHourMode) bool

OneHourFirst reports whether this request must carry 1-hour markers on every breakpoint. The host asks at the end of apply, once the thread is known. Nil-safe.

func (*Keeper) OneHourFirstFor added in v0.7.8

func (k *Keeper) OneHourFirstFor(resolve func() Policy, tenant, session, threadID string,
	provider bschemas.ModelProvider, endpoint, route, model string, toolsDeclared bool) bool

OneHourFirstFor is the apply hook of the 1-hour modes D and C (#1261), with the policy decision in the library. resolve returns the policy in force for the request: the account's with its stored strategy, so a manager's strategy that switches 1-hour-on-wait on counts, like for the pings. It is called only for a main-thread request that declares tools, so a host skips the policy chain for the rest. model is the model of the FINAL body apply hands over, the one Record keys the route state by too.

func (*Keeper) OneHourTier added in v0.7.5

func (k *Keeper) OneHourTier(key Key, body []byte, u Usage, usageOK bool, provider bschemas.ModelProvider) bool

OneHourTier reports whether Record would put this response on the 1-hour schedule: the thread was granted the 1-hour lifetime and the provider is not OpenAI. The host asks it before it decides how far to trust a body reading (#1227): the per-wait plan, and so the body reading, does not apply to that tier.

func (*Keeper) OneHourTouchLive added in v0.7.5

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

OneHourTouchLive reports whether key's thread is at 1 hour from a live free 1-hour ping. A host reads it to give a refused press the right reason before its own gates. Nil-safe.

func (*Keeper) OneHourTouches added in v0.7.5

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

OneHourTouches lists, by thread id, the threads of one session whose last touch was a free 1-hour ping that is under an hour old. A thread drops out at its next real request (Record), at the ping plus an hour, or when its route is switched off: a route that does not grant never shows an hour. Nil-safe.

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) ReadSetsTTL added in v0.7.5

func (k *Keeper) ReadSetsTTL(provider bschemas.ModelProvider, endpoint, route, model string, pinged bool) bool

ReadSetsTTL says whether the accountant may be told that a read sets the entry's TTL on this route and model (Provider.ReadSetsTTL, rossoctl/accountant#105). The proxy does not guess it from a model name or a provider: the route is Anthropic-shaped whatever it forwards to, and only evidence says what it did.

  • A route the probe PROVED: always.
  • A route not yet proven, for a request that follows a 1-hour ping (pinged): yes, unless the route is off. This is the return that decides the probe. It is priced in the same pass, before the keeper records the proof (the accounting runs first), so it must be priced as a return after a 1-hour ping to be credited at all. The library's rescue is itself evidence: it credits only tokens the return READ after the 5-minute lifetime. A cold return reads nothing and books none, and the keeper then switches the route off (resolveOneHourProbe).
  • Otherwise no. Nil-safe.

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) StoreOffPing added in v0.7.9

func (k *Keeper) StoreOffPing(alias string) (atMs int64, ok bool)

StoreOffPing is the keeper's record of the free 1-hour ping that was the last touch of a conversation, for a store that keeps nothing (storeOffAt), found by the cold clock's alias. It is what the cold check reads then, so a cold-only cut cannot fire inside the ping's hour at any storage level (#1350). It answers only for that case: with a real store the stored clock is the one record and this says no. A route that is switched off gave no tier, so it says no too; a costly route did rewrite the prefix at 1 hour, so it stands. It is the latest time a ping started: the caller decides how long it counts (EntryLifetime). Nil-safe.

By alias, not by session id and thread: the stored clock is keyed by the alias, and one conversation may arrive under two session ids (with and without the client's session header). It scans the index, which holds at most MaxTurnKeys entries, and only a request with no store asks.

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, cl agent.Client, names []string, incomplete bool, stopReason string, usageOK bool, open *TaskCounts) string

WaitingFor is the wait cause of a response, from its tool names and stop reason and the thread's open-task counts. cl is the client (agent.Identify; the zero Client names none): it decides what an end_turn with nothing open reads (waitcause.HumanFallback). The background count is the larger of two readings: the host's tracker (Options.OpenTasks), which is as of the request before and carries tasks whose start has left a compacted body, and the count the host read from this turn's own body (open; nil: the host had no result in time). A stale tracker count alone reads a turn that starts background work as "a person", the cheaper plan (#1225).

Only the background count is merged. The teammate count is the tracker's alone: a merged teammate count could turn "a person" (base+1 pings, the general floor) into "a teammate" (base pings), which is fewer. With the background count merged, the cause moves only from "a person" or "a teammate" to "background", which gets at least those pings and a floor no higher. Record also takes the larger count of the two causes, so no configuration of the extra pings can lower it.

func (*Keeper) WarmFacts added in v0.7.10

func (k *Keeper) WarmFacts(key Key) (lastTouch time.Time, ttl time.Duration, ok bool)

WarmFacts is what the keeper itself knows of one held thread's cache: the last moment its entry was known refreshed, and the lifetime it was written with. A host with no dashboard reads it for the cold gate of the Ping button (ManualPingBlock), where a host with a dashboard reads its thread table. ok is false when the thread is not held. It returns times only: no body and no credential. Nil-safe.

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 the host's estimate of the write a manual ping avoids.
	//
	// Deprecated: the keeper ignores it (#1460). The accountant credits the rescue on the thread's next real request.
	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 was the rewrite the ping saved.
	//
	// Deprecated: the keeper no longer sets it, so it is always 0 (#1460). The accountant credits the rescue on the thread's next real request.
	AvoidedUSD float64
}

ManualResult is what one manual ping did.

type OneHourMode added in v0.7.5

type OneHourMode struct {
	// Always is the C opt-in.
	Always bool
	// RebuildTokens is D's threshold. 0 = 150,000. NEGATIVE turns D off: a costly route then falls back to
	// plain auto. D applies only on a costly route.
	RebuildTokens int64
}

OneHourMode is what the host passes with each question: the account's resolved choices.

type OneHourTouch added in v0.7.5

type OneHourTouch struct {
	At time.Time
	// Proven is true when the route is proven to grant the 1-hour tier. While it is false the clock is a
	// belief the first return will test: the band shows "1h?".
	Proven bool
}

OneHourTouch is what the dashboard needs of it.

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 Override added in v0.7.8

type Override struct {
	// Pol carries Idle, MaxPings and MinPrefixTokens ONLY. MaxUSDPerPing is deliberately not here:
	// the per-ping cost guard exists because ping cost is bimodal (p50 $0.0004, p99 $0.2275, max
	// $0.3780), and an override may not widen it. KeepAlive is forced on: enabling the mechanism for
	// one session is the point, and the arming request is the consent act.
	Pol   Policy
	Until time.Time
	Armed time.Time
	// By is the tenant id of the principal that armed it, for the audit row. Always the
	// authenticated principal, never a value out of a request body.
	By string
}

Override is one armed session's policy and its expiry.

func ValidOverride added in v0.7.8

func ValidOverride(session string, idle time.Duration, pings, minPrefix int,
	until, now time.Time, by string) (Override, error)

ValidOverride checks a proposed override against every bound, naming the one it fails. It returns the resolved override, so the caller cannot apply a different one from the one checked. now is passed in, like the keeper's clock.

func (Override) Active added in v0.7.8

func (o Override) Active(now time.Time) bool

Active reports whether the override is still in force at now.

func (Override) Apply added in v0.7.8

func (o Override) Apply(pol Policy) Policy

Apply writes an armed override onto an Anthropic policy. Everything downstream (On, the pingable check, the hard deadline, the per-ping cost guard) reads the returned policy.

func (Override) ApplyOpenAI added in v0.7.8

func (o Override) ApplyOpenAI(pol Policy) Policy

ApplyOpenAI writes an armed override onto an OpenAI policy. It enables the session and sets its floor, but never imports the Anthropic-only 60-290 s cadence. The actual credential hold is bounded to one hour even when an account configured a longer OpenAI interval or many pings.

func (Override) Hold added in v0.7.8

func (o Override) Hold() time.Duration

Hold is the credential-hold ceiling this override buys: (K+1) x Idle, the arithmetic the entry's deadline uses. A person is shown it before they authorize.

func (Override) WorstCasePings added in v0.7.8

func (o Override) WorstCasePings(now time.Time) int64

WorstCasePings is the most pings one armed override can send before it expires: time until expiry over the idle interval, at least 1. It is a CEILING and not an estimate.

The count is `time until expiry / X`, one ping per idle interval, and NOT `K pings per (K+1)X span`. A span ends the instant a real request arrives, so the worst case is a session whose requests land just after each ping, restarting the clock every time and sending one ping per X for the whole hold. The span form under-states by (K+1)/K: 8 against a true 12 at the shipped defaults, and 2x at K=1. Under-stating a ceiling on a spend authorization is the one direction that cannot be defended. A zero idle gives 0 (nothing can be computed).

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 PlanInForce added in v0.7.4

type PlanInForce struct {
	// Built is true once Record filled the plan; false means no plan was built for the request.
	Built bool
	// MaxPings is the ping count after the per-wait plan (pol.MaxPings).
	MaxPings int
	// MinPrefixTokens is the prefix floor for this wait (Policy.WaitMinPrefix): 20k for a tool wait,
	// 80k for a person or an unknown cause, with the plan on.
	MinPrefixTokens int
	// IdleSeconds is the spacing between pings (pol.Idle), after the one-hour schedule is applied.
	IdleSeconds int
}

PlanInForce is the ping plan Record built for one wait: the count of pings, the billed-prefix floor the gate used and the spacing between pings. Numbers only.

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 is an opt-in flat dollar cap per ping. Pings read it through PingCap(): 0 means
	// the operator set none and the value rule alone decides (PingVerdict); a negative value also
	// means no cap. The summary and sweep substitutes read it the same way, through
	// PingCap() and SubstituteVerdict (#1439): 0 means no flat cap, and the value rule decides.
	//
	// It is PER PING and not per session, because ping cost is bimodal (p50 $0.0004, p99 $0.2275,
	// max $0.3780 before #1407). A manager strategy replaces it only with a value other than 0.
	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
	// OneHourOnWait turns on the 1-hour-on-wait ping (#1243), MAIN AGENT ONLY: for the main thread on the 5-minute tier whose
	// wait is long (LongWait), the first ping carries every cache marker at 1 hour and is the only ping
	// of that wait. Needs WaitPlan.
	OneHourOnWait bool
	// OneHourRebuildTokens is the D fallback's threshold: on a costly-switch route, a main thread runs as auto
	// until its first cold rebuild of a prefix of at least this many tokens, which is written at 1 hour (#1261).
	// 0 = 150,000. NEGATIVE turns D off (a costly route falls back to plain auto). Read only with OneHourOnWait.
	OneHourRebuildTokens int
	// OneHourAlways is the C opt-in: the main thread writes at 1 hour from its first request, with no pings.
	// Explicit only; ON MOST USERS IT DOES NOT PAY OFF (hosted +22% against auto, laptop -25%; #1261).
	OneHourAlways 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 ApplyStrategy added in v0.7.8

func ApplyStrategy(pol Policy, best *tenant.Strategy) (Policy, string)

ApplyStrategy writes a strategy onto a policy and returns the strategy's id. A nil strategy leaves the policy as it was and returns "".

A strategy forces KeepAlive on and replaces Idle, MaxPings, MinPrefixTokens and the predictor, and MaxUSDPerPing when it is not 0. It can only turn the 1-hour-on-wait ping ON, never off (#1243), and the same for 1-hour-always (#1261): like KeepAlive and HeadTTL1h there is no "deny" mode. The ping needs the wait plan, which the account policy carries (WaitPlan) and a strategy does not touch.

func EffectiveWaitPlan added in v0.7.8

func EffectiveWaitPlan(account Policy, strategies []tenant.Strategy, tenantID string, now time.Time,
	campaignOn bool) Policy

EffectiveWaitPlan is an account's EFFECTIVE per-wait ping plan (#868), the policy a calculator replays. It follows Resolve's order and reports the zero policy (the fixed-K model) when Resolve would turn the plan off:

  1. a covering manager strategy wins first, found as the request path finds it for a wait that is not for a person (windows ignored, unless an active campaign is on). Its Idle decides: 300 s or more (the 1-hour band) turns the plan off, less keeps the account's own setting. The campaign is then skipped;
  2. only when no strategy covers the account, an active campaign owns the count and turns the plan off.

Limits, stated because one read cannot see a single request: a campaign owns the count only on a request that passes its price gate; a per-session override turns the plan off for that session only; and the plan flag is one value for the account.

func FromConfig added in v0.7.8

func FromConfig(c config.CacheConfig) Policy

FromConfig maps the configuration document's `cache:` block onto a Policy. Every host that reads the document builds its account policy here, so they all resolve the same defaults.

func Resolve added in v0.7.8

func Resolve(pol Policy, in ResolveInput) (Policy, string)

Resolve layers the manager strategy, an active campaign and the session override over the account's own policy, and returns the policy plus the tag of the strategy or campaign that applied ("" when neither did).

Order, each layer reading the one below it:

  1. Account config (pol).
  2. The matching manager strategy. Anthropic only. With IgnoreWindows and no match today, a strategy that matches only because its window was ignored applies, unless an active campaign would own the count (with a campaign and a closed window, the campaign wins).
  3. An ACTIVE campaign decides the ping count unless a strategy matched. The campaign owns the count, so the per-wait plan is off for it (#858).
  4. The session override. An override may switch the mechanism ON for a session whose account leaves it off, since arming is the consent act. It may not widen MaxUSDPerPing, and it cannot reach around the kill switch or the no-audit-sink refusal, which the host checks first.

For OpenAI the strategy and campaign layers do not apply: the 60-290 s strategy band would buy 6-28 useless pings against a 30-minute cache. The idle is the OpenAI idle (or its default), and an override applies through ApplyOpenAI.

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 old flat guard, where zero means DefaultMaxUSDPerPing. No keeper path reads it any more: pings (#1428) and substitutes (#1439) use the value rule and PingCap. It stays as the pinned default the config loader mirrors.

It was the per-ping cost guard that was 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) FloorFor added in v0.7.9

func (p Policy) FloorFor(cause, stopReason string, subagent bool) int

FloorFor is the prefix floor of a stored row: the keeper's WaitMinPrefix, with the wait cause read from the row's stored cause and stop reason as storedWait reads it. A row with neither (an old row) gets the general floor, also on a subagent thread. It does not know OpenAI: the caller keeps the general floor for an OpenAI row.

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) PingCap added in v0.7.10

func (p Policy) PingCap() float64

PingCap is the operator's flat cap, or +Inf when the operator set none. Unlike Ceiling it does not map zero to a default: zero means "not set", and a negative value means "no cap" as before.

func (Policy) PingVerdict added in v0.7.10

func (p Policy) PingVerdict(pingUSD, missUSD float64, pings int) Verdict

PingVerdict decides one ping chain. pingUSD is the projected cost of one ping, missUSD the miss cost (MissUSD), pings the planned count K (below 1 counts as 1).

A zero pingUSD (unpriced) is always allowed. A zero missUSD is also allowed: it means the miss cost is unknown (no price) or degenerate (the write rate is not above the read rate, so a miss costs nothing extra to the price list), and the guard fails open for both, as it does for an unpriced model. The operator's flat cap still applies.

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) SubstituteVerdict added in v0.7.10

func (p Policy) SubstituteVerdict(costUSD, missUSD float64) Verdict

SubstituteVerdict decides a substitute call (summary or sweep question) that takes the place of a ping (#1439). It has the shape of PingVerdict with one call: the call is allowed when its projected cost is below the miss it protects.

The value is the miss of the entry the ping would renew (MissUSD). The call reads the same cached prefix and renews the same entry, as the keep-alive rule demands, so it protects at least the miss a ping protects. The payoff of a summary or a sweep answer (a shorter context, a cut) is not known from metadata at ping time, so it is not counted: the value is a floor.

An unset operator cap means no flat cap. An explicit one (MaxUSDPerPing > 0) still applies. A zero cost (unpriced) or a zero miss (unknown) is allowed, as for pings.

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.

func (Policy) WaitPlanOnly added in v0.7.8

func (p Policy) WaitPlanOnly() Policy

WaitPlanOnly is the part of an account's policy that rides on EVERY policy, a parked one too: the per-wait ping plan (#858) and its guards. A manager strategy can switch the keep-alive on for an account whose own block has it off, and the plan then still has to apply. These fields alone never turn the keep-alive on (Policy.On reads KeepAlive).

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 {
	// PrefixRewritten says the client rewrote the prefix this request sends (its own compaction, or a fork or
	// rewind of another thread). A cold read on such a request does not say the cache tier failed, so the
	// 1-hour-on-wait probe is not resolved on it (onehour.go).
	PrefixRewritten bool
	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
	// TouchAtMs is the time that request wrote under TouchAlias (apply.Trace.TouchAtMs). Record ends only the carry
	// written at that time (apply.ConfirmRealTouch). 0: the request wrote no clock, and nothing ends.
	// A request that took no clock step (a bypassed one) has TouchAtMs 0: it ends neither the stored carry nor, with
	// a store that keeps nothing, the keeper's own record of the ping (resolveOneHourProbe).
	// A host that runs apply MUST pass Trace.TouchAtMs and Trace.TouchSeq. Without them the confirm is a no-op, and
	// a free 1-hour ping stays under the clock until its hour ends, with no error.
	TouchAtMs int64
	// TouchSeq numbers that write (apply.Trace.TouchSeq), so the confirm is exact within one millisecond.
	TouchSeq int64
	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 (a client that sends an id but is keyed by another; Codex no longer, since its
	// session-id is the key). "" when there is none. MarkEnded and
	// RetireSessionStartedBefore match on either Key.Session or Client.
	Client string
	// Identity is the client agent.Identify named from the request headers. The zero value names no
	// client; a wait for a person then reads "human" for an end_turn with nothing open (waitcause.HumanFallback).
	Identity agent.Client
	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
	// OpenTasks, when non-nil, are the open-task counts the host read from this request's own body (see
	// WaitingFor). nil: the host had no result, and the tracker's counts decide, as before.
	OpenTasks *TaskCounts
	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
	// Plan, when non-nil, receives the ping plan built for the wait this response starts (#1198). It
	// is written only when the request passed every gate and got a schedule: a refused request leaves it
	// untouched, which the host reads as "no plan".
	Plan *PlanInForce
}

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

type ResolveInput added in v0.7.8

type ResolveInput struct {
	TenantID string
	// OpenAI is true for an OpenAI-family request. Strategies and campaigns are Anthropic only.
	OpenAI bool
	Now    time.Time
	// Strategies is the manager strategy list (a snapshot the host swaps wholesale under its lock).
	Strategies []tenant.Strategy
	// Campaign is the response's campaign decision, or the zero value when there is none (a
	// record-time gate such as canPing has no response yet).
	Campaign CampaignDecision
	// IgnoreWindows ignores a strategy's time windows (#858). Windows describe when a person
	// answers, so they gate only a wait for a person.
	IgnoreWindows bool
	// Override is the session's armed override that is still in force, or nil.
	Override *Override
}

ResolveInput is everything Resolve reads besides the account's own policy.

type SignalResult added in v0.7.8

type SignalResult struct {
	// Applied is true when the event is one the keeper acts on (SessionEnd, or SessionStart with
	// kind "compact"). It stays true when nothing was live to retire.
	Applied bool
	// Ended is true when the session was marked ended (SessionEnd only).
	Ended bool
	// Retired is how many live entries the retirement removed. It can be 0 when Applied is true.
	Retired int
	// Cutoff is zero for SessionEnd, which retires every thread of the session. For a compact it is
	// the arrival time less CompactRaceMargin: only the main thread's entries whose last request
	// started before it are retired.
	Cutoff time.Time
}

SignalResult reports what ApplyClientSignal changed for one client event.

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 TaskCounts added in v0.7.5

type TaskCounts struct{ Background, Teammate int }

TaskCounts are the open background-task and teammate-wait counts of a request body, read by the host while the request was upstream (#1225, #1227). Counts only. WaitingFor reads only Background; Teammate is carried for the host's own use and never changes a plan.

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

type Verdict added in v0.7.10

type Verdict int

Verdict is the answer of PingVerdict.

const (
	// VerdictOK means the ping is allowed.
	VerdictOK Verdict = iota
	// VerdictOverCap means the operator's own flat cap refuses it.
	VerdictOverCap
	// VerdictNotWorth means the planned chain costs at least the miss it protects.
	VerdictNotWorth
)

func (Verdict) Reason added in v0.7.10

func (v Verdict) Reason() string

Reason is the PingState reason for a refusal. Empty for VerdictOK.

type WindowsInput added in v0.7.8

type WindowsInput struct {
	// Account is the account's own policy.
	Account Policy
	// Tracked is true when the response is one the keeper would consider (2xx, a body, a start).
	Tracked bool
	// OpenAI is true for an OpenAI-family request.
	OpenAI bool
	// Subagent is true for a subagent thread.
	Subagent bool
	// Open is the thread's open background tasks and teammate waits, or nil.
	Open *TaskCounts
	// Prefix is the billed prefix of the response: cache read plus cache write.
	Prefix int64
	// CauseOf is the wait cause of the response, given the open counts (nil for the tracker-only
	// cause).
	CauseOf func(*TaskCounts) string
	// OneHourTier reports whether this response is on the 1-hour tier (Keeper.OneHourTier).
	OneHourTier func() bool
	// Resolve is the policy chain for one reading of the windows (Resolve with the host's
	// strategies, campaign and override). ignoreWindows ignores a strategy's time windows.
	Resolve func(pol Policy, ignoreWindows bool) (Policy, string)
}

WindowsInput is what ResolveWithWindows reads. The host fills the callbacks from its own state (the tracker, the request's usage and body), so each is called lazily and only where the resolver needs it.

Jump to

Keyboard shortcuts

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