Documentation
¶
Overview ¶
Package apply is the one place the pipeline meets a raw wire request, shared by every host adapter (the bifrost proxy and an in-process sidecar plugin). It extracts the messages array, runs the pipeline on it, and splices the result back into the original body — byte-lossless for every other field (headroom invariant I1). This is what makes "one implementation behind both integrations" concrete: hosts differ only in how they obtain the body, provider, and session id.
Provider normalization. Components operate on OpenAI-shaped tool outputs (role=="tool" messages with string content). The Anthropic Messages API instead carries tool outputs as `tool_result` content blocks INSIDE user messages — a shape bifrost's ChatContentBlock cannot even represent (it drops the payload on unmarshal). So for Anthropic requests we expand each tool_result block into a synthetic role=tool message the existing components already know how to shrink, run the pipeline, then splice each rewritten tool output back into its exact source block via sjson. Everything the pipeline did not touch stays byte-identical.
Index ¶
- Constants
- func AllBreakpointsAskExtendedTTL(body []byte) bool
- func BilledLifetimeMs(provider bschemas.ModelProvider, model string, ...) int64
- func Body(ctx context.Context, pipe *components.Pipeline, st store.Store, ...) ([]byte, bool)
- func BodyFull(ctx context.Context, pipe *components.Pipeline, st store.Store, ...) ([]byte, bool)
- func BodyWithModel(ctx context.Context, pipe *components.Pipeline, st store.Store, ...) ([]byte, bool)
- func BodyWithModelWindow(ctx context.Context, pipe *components.Pipeline, st store.Store, ...) ([]byte, bool)
- func CacheAnchorStats() (written, noSlot, notFound int64)
- func ConfirmRealTouch(st store.Store, alias string, atMs, seq int64)
- func EndTouchTier(st store.Store, alias, tag string)
- func EnforcedSessionIDFor(pipe *components.Pipeline, tenant, explicitSess, api string, ...) string
- func EntryAgeMs(sinceMs, tsMs int64, refreshedAt time.Time) int64
- func EntryLifetime(f CacheFacts) time.Duration
- func ExplicitSession(header string, body []byte, host ...string) string
- func ExplicitSessionFor(h http.Header, route agent.Agent, cl agent.Client, body []byte) string
- func InBandBreakpointStats() (moved, noMark, notFound, tooFar int64)
- func IsCold(f CacheFacts, prevAtMs, nowMs int64) bool
- func LiveOneHourPing(st store.Store, alias string, provider bschemas.ModelProvider, model string, ...) (atMs int64, live bool)
- func MarkInBandFollowUp(wire string, body []byte) []byte
- func NormalizeMessages(provider bschemas.ModelProvider, body []byte) []bschemas.ChatMessage
- func OpsFromRun(rr components.RunReport, wire []int, applied bool) (ops []accountant.Operation, dropped int)
- func ProjectFor(provider bschemas.ModelProvider, body []byte) string
- func RecordBilledInput(st store.Store, session string, tokens int64)
- func RecordBilledInputThread(st store.Store, session, threadID string, tokens int64)
- func RecordCacheTouch(st store.Store, tenant string, body []byte, provider bschemas.ModelProvider, ...)
- func RecordCacheTouchAlias(st store.Store, alias string, nowMs int64)
- func RecordCacheTouchAliasRoute(st store.Store, alias string, nowMs int64, oneHour bool, tag string)
- func RecordCacheTouchAliasTier(st store.Store, alias string, nowMs int64, oneHour bool)
- func RecordCacheTouchTier(st store.Store, tenant string, body []byte, provider bschemas.ModelProvider, ...)
- func RecordRatioThread(st store.Store, session, threadID string, tokens, bytes int)
- func RelabelAllTTL1h(body []byte, provider bschemas.ModelProvider) (out []byte, upgraded bool)
- func RelabelPrefixBodyForAsk(ctx context.Context, body []byte, provider bschemas.ModelProvider) []byte
- func RouteTag(route string) string
- func SessionIDFor(tenant, explicitSess string, provider bschemas.ModelProvider, body []byte) string
- func StandingOneHourPing(st store.Store, alias string) (atMs int64, ok bool)
- func TailBreakpointStats() (added, noSlot, atEnd, shortTail, noMark, notFound int64)
- func TouchAliasFor(tenant string, body []byte, provider bschemas.ModelProvider) string
- type Breakpoints
- type CacheFacts
- type CacheLifetimeKind
- type Change
- type Opts
- type Result
- type Trace
Constants ¶
const ( TTLEphemeral5m = "ephemeral_5m" TTLEphemeral1h = "ephemeral_1h" )
TTL tier names, as the provider names them. These are the strings the dashboard stores and groups by, so they are the provider's own vocabulary rather than ours.
const ( AnthropicDefaultCacheTTL = modelinfo.AnthropicCacheTTL5m OpenAIMinimumCacheTTL = modelinfo.OpenAIMinimumCacheTTL )
const SessionHeader = "x-context-guru-session"
SessionHeader is the header a client or its plugin names the session with. It wins over every other id.
const TraceTextCap = 4000
TraceTextCap bounds Change.Before/After — the copy of the text that goes into a trace or a dashboard row. It is NOT a cap on the message: the pipeline rewrote the whole thing, and BeforeTokens/AfterTokens are counted on the FULL string, so a Change can legitimately report 2,658 tokens next to 4,000 bytes of text. clip() appends a visible "…[+N bytes]" so a reader is told, and the original is recoverable through the expand tool when the after-text carries a <<cg:HASH>> marker.
It is exported because it is the cap that actually binds. apply is an importable library — the bifrost plugin embeds it and has its own reason to bound trace size — so an embedder that stores these rows must be able to report the EFFECTIVE limit rather than assert its own, larger one. dash does exactly that for content_cap_bytes.
Variables ¶
This section is empty.
Functions ¶
func AllBreakpointsAskExtendedTTL ¶ added in v0.6.0
AllBreakpointsAskExtendedTTL reports whether the body has cache breakpoints and every one of them asks for the 1h tier. A single 5m breakpoint (the default when `ttl` is absent) makes it false: that segment expires in five minutes whatever the others ask. The top-level cache_control of automatic caching is one of the breakpoints. The keeper uses this, with the billed tier, to pick a session's keep-alive schedule.
func BilledLifetimeMs ¶ added in v0.7.8
func BilledLifetimeMs(provider bschemas.ModelProvider, model string, billedOneHour, refreshedOneHour bool) int64
BilledLifetimeMs is the lifetime of the entry a request tried to read, in ms; 0 when the lifetime is not exact. billedOneHour is the tier the provider BILLED that entry at, not the tier a request asked for: a one-hour ask billed at five minutes stays five minutes. billedOneHour false (also "unknown") keeps the base lifetime. refreshedOneHour says the last touch was a live free 1-hour ping; it is a second, separate reason for the 1-hour lifetime. The result is the 1-hour lifetime when either boolean is true.
func Body ¶
func Body(ctx context.Context, pipe *components.Pipeline, st store.Store, provider bschemas.ModelProvider, body []byte, explicitSession string, bypass bool) ([]byte, bool)
Body runs the pipeline with no LLM clients available (deterministic components only). See BodyWithModel to supply model clients for LLM-based components.
func BodyFull ¶
func BodyFull(ctx context.Context, pipe *components.Pipeline, st store.Store, provider bschemas.ModelProvider, body []byte, explicitSession string, bypass bool, models components.ModelSpec, window int, cacheMode string) ([]byte, bool)
BodyFull is BodyWithModelWindow plus the cache mode ("auto"|"on"|"off", default "auto") controlling cache-aware compaction. "auto" turns on cache-awareness when the backend is a prompt-caching provider or the request already carries cache_control breakpoints; "on" forces it; "off" restores the legacy compact-everything behavior (correct for confirmed non-caching backends).
func BodyWithModel ¶
func BodyWithModel(ctx context.Context, pipe *components.Pipeline, st store.Store, provider bschemas.ModelProvider, body []byte, explicitSession string, bypass bool, models components.ModelSpec) ([]byte, bool)
BodyWithModel runs the pipeline over the request body's messages and returns the rewritten body. changed=false means "forward the original unchanged" (no messages array, unparseable, or a re-serialization problem) — always fail open. explicitSession is the host-supplied session id ("" -> content hash). models carries the LLM clients that NeedsModel components may call.
func BodyWithModelWindow ¶
func BodyWithModelWindow(ctx context.Context, pipe *components.Pipeline, st store.Store, provider bschemas.ModelProvider, body []byte, explicitSession string, bypass bool, models components.ModelSpec, window int) ([]byte, bool)
BodyWithModelWindow is BodyWithModel plus the model's resolved context window (max input tokens, 0 = unknown) so fraction-based Trigger thresholds can scale with the model. Hosts that resolve the window (the proxy, via internal/modelinfo) call this; window=0 reproduces the pre-D3 behavior exactly.
func CacheAnchorStats ¶ added in v0.6.0
func CacheAnchorStats() (written, noSlot, notFound int64)
CacheAnchorStats reports the cache-anchor counters: written, no free slot, block not found.
func ConfirmRealTouch ¶ added in v0.7.8
ConfirmRealTouch ends the carried 1-hour ping under the alias's clock: the host learned that the real request that wrote the clock at atMs was accepted, so the entry's tier is now that request's own. The time stays.
It ends only the carry that request wrote (the value's own time is atMs). Another request on the same alias may have written its clock since, over a ping that came after this request's clock: that carry is not this request's to end, and if that request then fails, the ping's hour must stand (#1365). The value's request number (seq) makes the match exact: two requests that wrote in one millisecond cannot end each other's carry. atMs 0 (this request wrote no clock) ends nothing. The keeper calls it where it ends its own index entry.
func EndTouchTier ¶ added in v0.7.8
EndTouchTier ends the free 1-hour ping that stands under the alias's clock, keeping the clock's time: the plain value stays. It ends a plain `:1h` and a carried ping alike, and only one stamped with tag, the route that made it (RouteTag). A later ping of another route, a ping with no tag and a plain value stay. The keeper calls it when the route that gave the tier is switched off, so the cold check never keeps an hour for a tier no route granted, and never loses one a different route granted. It is the only way the keeper ends a tier: the store record is the one record of the fact.
func EnforcedSessionIDFor ¶ added in v0.6.3
func EnforcedSessionIDFor(pipe *components.Pipeline, tenant, explicitSess, api string, provider bschemas.ModelProvider, bypass bool, body []byte) string
EnforcedSessionIDFor derives the session id BodyOpts will use for this request on an ENFORCED path: it runs the same envelope transform first (toolfilter's skills half rewrites the head message that the session hash reads), then derives the id exactly as BodyOpts does. A host that must write state under the pipeline's session BEFORE the pipeline runs (the proxy's expand repair, #175) calls this, so the two cannot disagree. It costs a transform and a re-parse, so call it only when there is state to write.
func EntryAgeMs ¶ added in v0.7.8
EntryAgeMs is how old the provider's cache entry was when a request arrived: the gap since the last real request, cut short by a ping that refreshed the entry later than that request.
func EntryLifetime ¶ added in v0.7.8
func EntryLifetime(f CacheFacts) time.Duration
EntryLifetime is how long the provider keeps the entry after its last touch. A provider with a fixed lifetime (OpenAI GPT-5.6+, 30 minutes) ignores the tiers.
func ExplicitSession ¶ added in v0.7.1
ExplicitSession resolves the explicit session id for one request: the header wins, then the metadata fields, then the host ids, then "" (Scoped's derived-hash fallback). The rule lives in session.Explicit; this only reads the fields off the raw body. The proxy's Bob route calls it with the X-Task-Id header as a host id. It passes the result back as Opts.Session.
gjson scans, so this costs no second unmarshal of the body on the request path. A `metadata` that is absent, null, a scalar or an array yields a non-existent result, and a value that is not gjson.String is skipped, so both fall back to the derived hash.
`metadata` is fetched ONCE and the fields read off it, rather than a full-body query per field: on a real 600 KB request `metadata` sits behind `messages`, so each query walked the whole transcript to reach it.
func ExplicitSessionFor ¶ added in v0.7.9
ExplicitSessionFor is the explicit session id for one request, for a host that has the request headers. The order is fixed here, so every host gets the same answer:
- the SessionHeader header;
- the body's own ids (session.Explicit), when the header is empty;
- the id of the agent that owns the route (route.SessionID(h), for example Bob's X-Task-Id);
- the client's own id from its headers (cl.SessionID: Codex session-id, OpenCode x-opencode-session-id).
3 and 4 come after every other id. A route with no agent id and a client with no id give the header unchanged. cl is agent.Identify(h), computed once per request by the host.
route may be nil (a host that has no route agent). A panic in route.SessionID gives no id for it: the request keeps the session it has without one (fail open). In Cortex there is no route agent: pass nil, and pass the host's own session id (pctx.SessionID) as the header value when it is set.
func InBandBreakpointStats ¶ added in v0.6.5
func InBandBreakpointStats() (moved, noMark, notFound, tooFar int64)
InBandBreakpointStats reports the in-band follow-up counters: moved, no client mark, no target, past the lookback.
func IsCold ¶ added in v0.7.8
func IsCold(f CacheFacts, prevAtMs, nowMs int64) bool
IsCold reports whether the entry is certainly gone: the last touch was prevAtMs, the question comes at nowMs, and the lifetime plus the margin has passed. An unknown last touch (0) is never cold.
func LiveOneHourPing ¶ added in v0.7.9
func LiveOneHourPing(st store.Store, alias string, provider bschemas.ModelProvider, model string, nowMs int64) (atMs int64, live bool)
LiveOneHourPing is StandingOneHourPing that also asks the one lifetime function: the ping counts until EntryLifetime of the 1-hour tier for this provider and model has passed since it started.
func MarkInBandFollowUp ¶ added in v0.6.5
MarkInBandFollowUp gives an in-band follow-up request the breakpoint the client would have given it (#784). An in-band follow-up is a request the HOST sends upstream inside one client request, after it answered a tool call itself: the expand continuation (expand.Continuation), and #485's tool-search stub when it lands. It ends with content the client never sent — the assistant's tool_use and the host's tool_result — and no breakpoint covers it, so the provider bills it as plain input and caches none of it.
WHEN IT PAYS. The mark makes the provider WRITE the new content (1.25x the input price, 2x for a 1h TTL) instead of billing it as plain input (1x). That pays only when a later request READS the entry, which needs that request to carry the same bytes up to the mark. The caller owns that:
- #485's search stub, a future caller, will splice the stored exchange back into the client's next request byte-identically, so the next turn reads it (probe: 474 tokens written without, 0 with).
- The expand continuation does NOT qualify, so the proxy calls this only when `expand.inband_breakpoint` is set. The client never sees the tool_use or the tool_result; its next request carries an assistant turn without the tool_use, and fixed_restore inserts a user text message, not the tool_result. Both diverge before the mark, so only a later round of the same loop could read the entry. Pinned by TestTheNextClientRequestDivergesBeforeTheMark.
THE LOOKBACK. The follow-up still reads the client's cached prefix only through the provider's lookback from the moved mark (lookbackBlocks). A follow-up that adds more blocks than that after the client's mark is left unmarked and counted as too far.
It MOVES the last cache_control in `messages`, whoever placed it (the client, or the pipeline before it), onto the last block of the last message, with the same cache_control value, so the TTL the client asked for ("1h" stays "1h") is kept. That is what Claude Code itself does on each new request. A move keeps the client's count, so the provider's cap of 4 is never at risk, and breakpoints in `tools` and `system` are not touched. A client that put no breakpoint in `messages` asked for no cache strategy there, and none is invented: the body is returned unchanged.
Call it on each follow-up as built. On a later round the mark found is the one the previous round moved, so it moves on again. Only the Anthropic messages wire carries cache_control; on every other wire this is a no-op. Fails open: any unexpected shape or error returns body unchanged.
func NormalizeMessages ¶ added in v0.5.0
func NormalizeMessages(provider bschemas.ModelProvider, body []byte) []bschemas.ChatMessage
NormalizeMessages is normalizeSessionMessages, exported for a caller outside this package that needs the SAME normalization BodyOpts itself uses on a raw wire body — proxy's sentStash is the first one, which has to derive a cheap identity for a previously-forwarded body in order to answer components.PrefixCoverage.CoversSpan with the same message boundaries a components/offload caller computed over its own, freshly-normalized request.
func OpsFromRun ¶ added in v0.7.0
func OpsFromRun(rr components.RunReport, wire []int, applied bool) (ops []accountant.Operation, dropped int)
OpsFromRun turns a run's per-message changes into accountant operations, in pipeline order. The sizes are the components' TEXT sizes; the caller must convert them to wire bytes (wireSizes) before the operations reach the library. wire maps a req.Input index to the wire message index (wireGroups). applied is false when the rewritten body was not the one forwarded; a report that ran in observe mode is DryRun too, whatever applied says: its operations are computed but never sent.
A reverted or skipped report changed nothing upstream and reports nothing. The first report that changed the message count carries one splice change, mapped to a MessageSplice operation when it covers whole wire messages (else dropped). Every report after it indexes the req.Input the splice left. A change on a message the splice kept is mapped back to the slot and wire message it came from and reported in the forwarded space, with the ChangeID of the pre-splice slot. A change on the inserted message, or after a splice that was itself dropped or a second splice, cannot be placed and is dropped, never guessed.
func ProjectFor ¶ added in v0.5.4
func ProjectFor(provider bschemas.ModelProvider, body []byte) string
ProjectFor returns the directory the agent was started in, as stated in the request's own prompt, or "" when the request does not state one.
Here rather than in the caller because the normalization it needs — one provider-agnostic message slice out of an Anthropic or OpenAI body — is this package's job and is unexported. SessionIDFor is the same shape for the same reason, and the two share normalizeSessionMessages so that a body shape one accepts is a body shape the other accepts.
It must be given the PRISTINE inbound body. A rewritten transcript may have had the environment block compacted out of it, and the project would then flip to unattributed on exactly the requests the pipeline acted on — the ones whose cost is most worth attributing.
func RecordBilledInput ¶ added in v0.2.0
RecordBilledInput stores the provider's own input-token count for a finished turn, so the NEXT turn of the same session can be compared against the model's context window in the units that window is stated in. Call it once per response, with fresh + cache-read + cache-write.
EXPORTED, and the only writer, because the read and the write must agree on the key or the figure is silently always zero — which reads as "not full" and disables every fraction gate that depends on it. The host has to hand back the session id the pipeline itself derived (Trace.Session): re-deriving it from the outgoing body would hash a transcript this pipeline had just rewritten, producing a different key on exactly the sessions where compaction is happening.
A ping must never come through here. Its usage describes a keep-alive touch of the cached prefix, not the agent's transcript, and it would understate the fill for a session that is merely idle. Only the real request path calls this.
func RecordBilledInputThread ¶ added in v0.6.3
RecordBilledInputThread stores the same figure per thread, for the billed-growth horizon. Call it next to RecordBilledInput, with the thread id the request was served under.
func RecordCacheTouch ¶ added in v0.2.0
func RecordCacheTouch(st store.Store, tenant string, body []byte, provider bschemas.ModelProvider, nowMs int64)
RecordCacheTouch records that something refreshed this prefix's provider cache entry at nowMs, against the SAME content-derived alias the request path reads. It is the seam a keep-alive ping uses.
Why a ping has to count ¶
A ping's whole job is to READ the cached prefix, and a read refreshes the entry's TTL. So after a successful ping the entry is warm again — and until this existed, nothing told the cache-liveness clock. `prevAt` came only from real requests, so on a kept-alive session the idle time grew without bound while the provider held the entry alive, and every reader of Ctx.IdleMs concluded the cache was long dead.
For summarize's gate that conclusion was expensive in the one direction that matters: a strict clock test returned "certainly cold", the then-shipped `cache_state: pre_expiry_or_cold` permitted a rewrite, and the component compacted a LIVE prefix — on exactly the sessions someone is paying pings to protect. The gate's own docstring existed to avoid that outcome via Ctx.ColdCache, and then reproduced it through the timestamp underneath. Issue #243.
THAT PARTICULAR CONSUMER IS GONE: the cold-gated cache states were withdrawn, and summarize's default no longer consults the cache at all. This clock is not therefore decorative — a component asking "is this prefix LIVE?" reads it, which is `cache_state: pre_expiry` today and cache_aware_summarizer's whole premise tomorrow, and it would be wrong in the same direction without the touch below.
And why this is NOT the dashboard's session-recency map ¶
keepalive.go deliberately does not touch that map, and its reason is right: re-dating the session would make the next real request's gap read as four minutes instead of the twenty it actually was, hiding the very thing the mechanism exists to demonstrate.
Those are two different questions and they want two different clocks:
"is the provider still holding this prefix?" -> counts pings -> THIS clock "how long was the USER away?" -> ignores pings -> the recency map, untouched
Sharing one clock forces a wrong answer to one of them. This writes only the first, so the dashboard's idle-gap statistics and any firing-rate measurement over them are unaffected.
Why the alias and not the session id ¶
Because the provider's entry is keyed on CONTENT, and this must land on the key apply's own aliasSeenState will read. Computing it here, from the same schema.SessionHead + session.Scoped pair, is what makes the two impossible to drift apart — a second derivation of a cache key is how the cold decision and the dashboard came to disagree once already.
nowMs must be the time the ping's request STARTED, not its completion: the provider's lifetime runs from request start, which is the same reasoning kaEntry.startedAt is anchored on.
This form derives the alias from body. That is right only when body is the transcript the request path hashed. A body the host changed after apply ran (tool deferral appends the names list to the head) gives another alias, so such a host passes the one apply derived to RecordCacheTouchAlias.
func RecordCacheTouchAlias ¶ added in v0.6.7
RecordCacheTouchAlias is RecordCacheTouch for a caller that holds the alias already: Trace.TouchAlias, derived from the request as it arrived. It writes the same clock under the given key, monotone. The touch carries no tier: it ends any 1-hour tier an earlier touch left.
func RecordCacheTouchAliasRoute ¶ added in v0.7.9
func RecordCacheTouchAliasRoute(st store.Store, alias string, nowMs int64, oneHour bool, tag string)
RecordCacheTouchAliasRoute is RecordCacheTouchAliasTier that also stamps a 1-hour touch with the tag of the route that made it (RouteTag), so a switch-off of that route can end it and no other. The tag is ignored for a 5-minute touch. tag must come from RouteTag (hex): a tag with "^", "#" or ":" would break the value's shape.
func RecordCacheTouchAliasTier ¶ added in v0.7.8
RecordCacheTouchAliasTier is RecordCacheTouchAlias with the tier of the touch.
oneHour says the touch left the provider's entry at the 1-hour tier: a free 1-hour keep-alive ping (1-hour-on-wait) read the prefix and moved the entry from 5 minutes to 1 hour. A request that carries 1-hour markers does not need it: it states its own tier, and sessionTTL keeps it. Until the next touch the cold decision then counts the entry's lifetime from this touch at the 1-hour lifetime (lastTouchOneHour), not at the 5 minutes the thread's own requests ask for.
A touch with oneHour false is the new LAST touch and ends the tier: a manual 5-minute ping moves a 1-hour entry back to 5 minutes (#1258). The clock stays monotone: an older touch changes nothing.
func RecordCacheTouchTier ¶ added in v0.7.8
func RecordCacheTouchTier(st store.Store, tenant string, body []byte, provider bschemas.ModelProvider, nowMs int64, oneHour bool)
RecordCacheTouchTier is RecordCacheTouch that also says the tier the touch left the entry at.
func RecordRatioThread ¶ added in v0.7.11
RecordRatioThread stores the request ratio of a finished turn for its thread (#1533): the provider's billed tokens of the forwarded text and its bytes (accountant.Ratio.Text). Call it next to RecordBilledInputThread. A turn with no ratio writes nothing, and the previous one stays.
func RelabelAllTTL1h ¶ added in v0.7.5
func RelabelAllTTL1h(body []byte, provider bschemas.ModelProvider) (out []byte, upgraded bool)
RelabelAllTTL1h re-labels EVERY existing cache breakpoint of a body as a one-hour entry: tools, system and messages. BodyOpts uses it on a REAL main-thread request in the 1-hour modes D (1-hour-on-wait) and C (1-hour-always) (#1261): such a request writes at 1 hour, so nothing is switched. The keeper no longer uses it on a keep-alive ping (v0.7.12): a 5-minute to 1-hour READ keeps the entry on Haiku 5.5 but not on Opus 5.5 (direct to the gateway, 2026-11-30), so the result depends on the model.
The same three constraints as upgradeHeadTTL hold, and each is why this is safe:
- It adds no breakpoint. It only sets `ttl` on a mark the client already sent, so the cap of four is not touched.
- The order rule (1h entries before 5m ones) holds because NO breakpoint is left at 5m: all of them are 1h.
- It never strips an existing ttl and sets "1h" on every mark, so a second call changes nothing (idempotent).
A request with no breakpoint is returned untouched. It fails open: any edit error returns the input body whole, never half-labelled.
func RelabelPrefixBodyForAsk ¶ added in v0.7.11
func RelabelPrefixBodyForAsk(ctx context.Context, body []byte, provider bschemas.ModelProvider) []byte
RelabelPrefixBodyForAsk is the host's half of the 1-hour sweep question (#1561). A host PrefixAsker calls it on the stashed body before it appends the ask. When the caller asked for 1-hour markers (components.WithOneHourMarkers) it relabels every marker, as the 1-hour ping does, and reports what it did (components.NoteOneHour). The ask the host appends then copies a marker that is already at 1 hour. Without a request, or on a provider with no explicit marker, it returns body as it is. It never changes body in place. Deprecated: since v0.7.12 the keeper never asks for 1-hour markers on a prefix call, so this is inert. It stays so that a host (Cortex) that calls it still builds. Removed in the release after v0.7.12 (N+1).
It stays as it is (not a pass-through): it relabels only for a context made by components.WithOneHourMarkers, and the keeper makes none, so it already returns its input unchanged. A host that still sets one keeps a working relabel until N+1.
func RouteTag ¶ added in v0.7.9
RouteTag is the short name of a route a 1-hour ping is stamped with. It is a hash, so the store value holds no provider, endpoint or model text.
func SessionIDFor ¶ added in v0.2.0
func SessionIDFor(tenant, explicitSess string, provider bschemas.ModelProvider, body []byte) string
SessionIDFor derives the session id apply WOULD use for a request, without running a pipeline.
It exists for the response path in OBSERVE mode. There the enforced path never calls BodyOpts at all — that is what makes observe's byte-identity guarantee structural — so it has no Trace and no session id, and RecordBilledInput had nothing to key on. The consequence was that Ctx.PrevBilledInput stayed 0 forever on an observe tenant, FracResolvable read false, and summarize's shipped 0.9 default reported window_not_exact on every turn: a permanent zero in the one mode whose entire purpose is showing an operator what enforcing WOULD have saved.
It shares BOTH halves with BodyOpts — messagesArray for the gate and sessionIDFrom for the derivation — rather than reproducing them. An earlier version claimed that agreement in a comment while actually holding a second copy, and the two had already drifted apart on which body shape they accepted.
It re-parses the body, so it is for callers with no Trace. A caller holding one uses Trace.Session.
func StandingOneHourPing ¶ added in v0.7.9
StandingOneHourPing reads the one record of the fact "the last touch of this entry was a free 1-hour ping": the time that ping started, and whether one stands. It is the `:1h` value (the ping is the last touch) or the carry under a real request nobody has confirmed (the request touched nothing yet). A plain value, a value it cannot read and a missing value all say no: an unreadable record never reads as a tier. It does not slide the store's TTL (store.PeekValue): asking is not a touch.
Every reader asks this, not a copy of the fact: the dashboard's cache clock, the manual-ping refusal and the probe. The cold check reads the same value through aliasSeenState, where it also writes its own clock.
func TailBreakpointStats ¶ added in v0.6.5
func TailBreakpointStats() (added, noSlot, atEnd, shortTail, noMark, notFound int64)
TailBreakpointStats reports the tail-breakpoint counters: added, no free slot, mark at the end, short tail, no client mark, no target.
func TouchAliasFor ¶ added in v0.7.8
func TouchAliasFor(tenant string, body []byte, provider bschemas.ModelProvider) string
TouchAliasFor is the alias (the cold clock's key) a request body derives, "" when it derives none. It is the same derivation RecordCacheTouch uses, so a caller that must find the clock again later (the keeper ending a 1-hour tier) cannot drift from it.
Types ¶
type Breakpoints ¶ added in v0.1.1
type Breakpoints = schema.Breakpoints
Breakpoints is where a request's breakpoints sit, by location. See schema.Breakpoints.
func CountBreakpoints ¶ added in v0.1.1
func CountBreakpoints(body []byte) Breakpoints
CountBreakpoints counts the breakpoints the provider will see in this request, by location, except a mark whose key is spelled with a \u escape: this is the hot-path count (the cap check runs it twice per request) and its prefilter is "cache" only. schema.CountBreakpointsEscaped counts those too; hasCacheBreakpoint uses it. See schema.CountBreakpoints.
type CacheFacts ¶ added in v0.7.8
type CacheFacts struct {
Provider bschemas.ModelProvider
Model string
// LastOneHour is the tier the LAST touch of the entry left it at, whoever made that touch: a real
// request that asked 1 hour, or a keep-alive request that did (a free 1-hour ping). The last touch
// counts, not the longest: a 5-minute touch after a 1-hour ping moves the entry back (#1258).
LastOneHour bool
// BilledOneHour is the tier the provider billed the entry's last write at, when the caller has only
// that (the dashboard rows). It widens like LastOneHour: either one says 1 hour.
BilledOneHour bool
// Floor is the longest lifetime a safety guard has seen for this prefix (the monotone sessionTTL, the
// parent's record). The lifetime is never shorter than it: the guards only ever err toward WARM.
Floor time.Duration
}
CacheFacts are the metadata facts that say how long the provider keeps one thread's cache entry NOW (#1350). Nothing here is content: a provider, a model, two tiers and a floor.
EntryLifetime and IsCold are the ONE place that turns them into a lifetime and a verdict. Every reader asks them: the cold check (apply), the keeper (cacheTTL, the substitute windows, the 1-hour probe, the 1-hour touch), the dashboard's cache clock and its miss attribution. No other code writes "5 minutes", "30 minutes" or "1 hour" for a cache lifetime. The table underneath is modelinfo.CacheLifetime.
Why in apply: apply, keepalive, dash and the proxy already import it, and it imports none of them, so all can call it without a cycle. The tier tables stay in internal/modelinfo.
type CacheLifetimeKind ¶ added in v0.4.0
type CacheLifetimeKind uint8
CacheLifetimeKind distinguishes a known expiry from a minimum guarantee. A minimum may prove an entry is still eligible, but cannot prove it has expired.
const ( CacheLifetimeUnknown CacheLifetimeKind = iota CacheLifetimeExact CacheLifetimeMinimum )
func CacheLifetime ¶ added in v0.4.0
func CacheLifetime(provider bschemas.ModelProvider, model string, body []byte) (time.Duration, CacheLifetimeKind)
CacheLifetime returns the only lifetime facts the cache gate may act on. GPT-5.6+ defaults to a 30-minute MINIMUM after the latest write or reuse; OpenAI may retain the prefix longer, with no documented maximum. Therefore even a very old OpenAI entry cannot safely set ColdCache or lift TailOnlyCold. Earlier OpenAI models have variable retention, so their lifetime is unknown without a reliable per-request fact.
type Change ¶ added in v0.1.1
type Change struct {
Path string `json:"path"`
BeforeTokens int `json:"before_tokens"`
AfterTokens int `json:"after_tokens"`
Before string `json:"before"`
After string `json:"after"`
// Components names which components rewrote this message, IN THE ORDER THEY
// TOUCHED IT. A LIST, not a single id, and that is not a hedge: several components
// routinely rewrite the same message in sequence (a reformatter then an offloader),
// and the before/after pair here is their cumulative result — a single field would
// have to name a winner and would be wrong for every other toucher.
//
// A REVERTED component is absent. The pipeline only records indices for a run that
// survived its guards (see components.runOne), so a component rolled back by an
// error, a panic, or the never-worse rule is never credited with the change.
Components []string `json:"components,omitempty"`
}
Change is one rewritten message, captured for the CONTEXT_GURU_DUMP trace and for the dashboard's before/after diff view, so a human can see exactly what context-guru did to the wire.
type Opts ¶ added in v0.1.1
type Opts struct {
Provider bschemas.ModelProvider
Body []byte
// API identifies the wire envelope. Empty means Chat Completions / Messages;
// "responses" (or the upstream path "/v1/responses") selects OpenAI's native Responses
// instructions+input shape. schema.WireFor reads it.
API string
// Session is the host-supplied session id ("" => content hash).
Session string
// ThreadOf, when set, finds the thread of the session this request belongs to (see
// package thread). It is called once, as soon as the session id is resolved and BEFORE the
// pipeline runs, so components see the thread on Ctx.Thread; the result rides on
// Trace.Thread. nil leaves every request on the primary thread.
//
// A host builds it with thread.ResolveSession, the rule the proxy uses too (proxy/thread.go
// threadFor). ResolveSession gives the primary thread for an empty session and recovers a
// panic. Keep one thread.Tracker per process, because it holds per-session state:
//
// orig := body // the request as the agent sent it, saved before the pipeline runs
// agentID, _ := thread.HeaderAgentID(agent.Identify(req.Header).SubagentID())
// opts.ThreadOf = func(session string) thread.Result {
// // agentall is github.com/rossoctl/context-guru/agent/all. With no headers, pass nil.
// res, _ := tracker.ResolveSession(tenant, session, agentID, orig, agentall.IsClientCompaction(req.Header, orig))
// return res
// }
//
// Call ThreadOf (and so Resolve) once per request: each call records the request as its
// thread's newest turn. If Trace.ThreadResolved is false after the call, apply returned
// before it called ThreadOf (no message list, or no message it can use). Then call the same
// function yourself with Trace.Session, so the finish side below still has a thread.
// Trace.Session is "" in that case, so the result is the primary thread.
//
// lifecycle.Prepare runs the request-side steps in their order, lifecycle.Request.Opts builds the
// shared options, and lifecycle.Finish runs the finish-side steps below.
//
// Host contract. Once ThreadOf is set, components key their state by
// thread.Key(session, threadID). Make the finish-side calls with the same thread
// (threadID = Trace.Thread.ID, session = Trace.Session), or state is written under one key
// and read under another:
//
// - lifecycle.Prepare calls offload.ClearStaleKeepAliveCandidate(thread.Key(session, threadID),
// startedAt) for the host, after the pipeline and after the keep-alive arrival.
// - lifecycle.Finish calls, for the host, RecordBilledInput and RecordBilledInputThread (only when
// usage is OK, and in observe mode for the shadow store too), offload.ResolveDeferredCacheAwareSummary
// and offload.ResolveWarmQuestion, all with the same session and threadID.
// - The host keeps every keepalive.Keeper call (ArriveAt, Depart, WaitingFor, RaiseWaitPlan and the
// others) with keepalive.Key{Tenant: tenant, Session: session, Thread: threadID}. It passes them
// to Prepare (Arrive) and Finish (Touch) as function values, so they run in the right order.
ThreadOf func(session string) thread.Result
// Tenant namespaces the session id in a hosted, multi-tenant deployment. Empty
// in single-tenant use, which leaves session keys byte-identical to before this
// field existed.
//
// It has to exist because the fallback session id is a content hash of the system
// prompt plus the first user message. Two people running the same agent on the
// same repository produce the SAME hash — so without a namespace they would share
// one session key, and therefore one sticky offload set and one cached-prefix
// boundary. That is a cross-tenant state collision arrived at by nobody doing
// anything wrong.
Tenant string
Bypass bool
Models components.ModelSpec
// Window is the model's resolved context window (max input tokens; 0 = unknown).
Window int
// WindowExact says Window is a figure published for THIS model rather than a family
// guess. False when unknown, and false when it came from the substring table of last
// resort — which answers 200,000 for every Opus, five times low. A component deciding
// "how full is the context" must not act on a guess; one setting a per-output floor may.
// See modelinfo.ExactResolver.
WindowExact bool
// CompactionPoint is C in provider-billed tokens: where the conversation's own compaction
// mechanism acts. 0 = unknown, and components fall back to Window. See
// compactionpoint for the definition and why it is not the window.
CompactionPoint int
// CompactionPointSource is "measured" | "assumed" | "configured" | "client_default" | "operator" | "window_fallback".
CompactionPointSource string
// CacheMode is "auto" (default) | "on" | "off" — see resolveCacheAware.
CacheMode string
// Now is the clock, injected so idle-time reasoning is testable. Zero means time.Now().
Now time.Time
// SelfRates are the per-token rates of the model a NeedsModel component would call via
// `model.source: incoming` — i.e. the request's own model. Supplied by the host, which is
// the only layer with a Pricer. Zero means unknown and the component falls back.
SelfRates components.TokenRates
// RatesFor resolves the operator's rate card for a NAMED model, so a component that
// compacts with a model other than the request's own can price its own calls from the
// same card the bill is computed from. nil means unavailable; the component falls back.
RatesFor func(model string) components.TokenRates
// Mode is the operating mode. Empty means components.ModeSync, so a caller that does
// not know about modes gets exactly today's behavior.
Mode components.Mode
// HeadTTL1h asks for the provider's one-hour cache tier on the HEAD breakpoints
// (`tools`, `system`) while the trailing message breakpoint stays at five minutes —
// the documented mixed-TTL shape. Off by default; see headttl.go for the measured reason,
// which is that Bedrock grants the tier for the Claude 4.5 family and silently downgrades
// it for the Opus 5 / Sonnet 5 models this service actually runs.
//
// NOTE for anyone reading the cold-cache logic: setting this makes bodyAsksExtendedTTL
// true, so cacheTTL returns 1h and cacheIsCold becomes correspondingly permissive. That is
// the right behaviour when the tier is granted and a deliberate over-estimate when it is
// not (the safe direction — believing a cache is warm only forgoes an optimisation). It
// cannot affect anything today because this is off, but it is the one way this field
// touches shared behaviour.
HeadTTL1h bool
// OneHourFirst asks the host whether THIS request must carry the 1-hour tier on EVERY existing cache
// breakpoint (tools, system and messages): 1-hour-always (from the first request) or 1-hour-on-wait (from the
// first cold rebuild of a big prefix), so the main thread writes at 1 hour (#1261). It is
// asked at the end of apply, once the thread and the session are known, with the model of the FINAL
// body (the one the keeper keys its route state by) and whether the body declares tools. It adds no breakpoint and changes no other request. nil never relabels.
OneHourFirst func(session, threadID, model string, toolsDeclared bool) bool
// HeadTTLMinBytes is the size gate on HeadTTL1h, in bytes of the request body. 0 disables the
// upgrade entirely rather than defaulting, so a host that forgets to resolve its
// configuration asks for nothing instead of asking on every request.
HeadTTLMinBytes int
// PrefixAsk, when set, lets a component put a question to the request's own model with the
// previous turn's SENT body as the cached prefix. See components.PrefixAsker. nil => a component
// that wants one gets none and decides for itself; today's behaviour for every caller that does
// not set it.
PrefixAsk components.PrefixAsker
// CanSweepAtPing, when set, tells a component whether the sweep can ask its question at a keep-alive
// ping of the thread of the session this request belongs to. It is NOT "the keeper pings this
// thread": the sweep's question is Anthropic only, so it is false for every OpenAI thread, which the
// keeper does ping. See components.Ctx.CanSweepAtPing. nil => it cannot.
CanSweepAtPing func(session, thread string) bool
// CanKeepAlive is the old name of CanSweepAtPing, with the same meaning. It is used only when
// CanSweepAtPing is nil.
//
// Deprecated: use CanSweepAtPing.
CanKeepAlive func(session, thread string) bool
// FreePing asks the host for the free 1-hour ping that was the last touch of a conversation: its start time in
// milliseconds, and whether one stands. It is the host's fact for ONE case: the store keeps nothing
// (store.Keeps is false: storage off, or no store), so the ping's clock was never written and the cold check
// has nothing to read (#1350). apply asks it ONLY then. With a real store the stored clock stays the one record
// and this is never called. It can only make a cold verdict warm, and only inside the entry lifetime of the
// ping (EntryLifetime). nil asks for nothing, and so does a panic (fail open, as CanSweepAtPing).
//
// It is asked by the cold clock's ALIAS (Trace.TouchAlias, from the body), not by session id and thread: the
// stored clock is keyed by the alias, and the same conversation may arrive under two session ids (with and
// without the client's session header). Asking by alias makes the store-off answer as id-independent as the
// stored one.
FreePing func(alias string) (atMs int64, ok bool)
// Tracker, when set, owns the per-session cached-prefix boundary. Supplying it also
// removes the concurrent-turn race in the legacy read-then-deferred-write of prevLen.
// nil => the legacy store-backed path, unchanged for library callers and /compact.
Tracker *modes.Tracker
}
Opts is BodyOpts' input: everything the positional BodyFull takes, plus the operating mode (#31) and the per-session boundary tracker.
A struct rather than more positional arguments: the parameter list was already at the limit of readability, and these fields are set by one host only.
type Result ¶ added in v0.1.1
type Result struct {
// Body is the body to forward. Always valid: on any trouble it is the input.
Body []byte
// Changed is false when Body is the untouched input.
Changed bool
Trace
}
Result is BodyOpts' output.
The embedded Trace carries everything observational: the resolved Session, the pipeline's Run report (which observe mode reads as its ONLY output, since the body is thrown away), the cache-awareness facts, and each rewritten message's before/after text for the dashboard. It is embedded rather than duplicated so there is exactly one Session and one Run in the codebase — two copies of the same value is how one of them goes stale.
func BodyOpts ¶ added in v0.1.1
BodyOpts is the full entry point: everything BodyFull takes plus the operating mode (#31), the per-session boundary tracker, and the observational Trace the dashboard's capture path reads. Hosts that support modes call this; BodyFull is the positional shim every other caller keeps using.
The rewrite is byte-identical whether or not anyone reads the trace: every trace field is filled from a value the rewrite already computed, and nothing branches on it.
type Trace ¶ added in v0.1.1
type Trace struct {
Session string
// TouchAlias is the key of the cold decision's liveness clock (cg:seen:<alias>), derived from the
// transcript as it arrived, before the host changes it. A host that records a keep-alive passes
// it on, and the ping touches this key through RecordCacheTouchAlias. Re-deriving it from the
// body that goes upstream gives another key when the host edits the head (tool deferral).
// "" when apply derived none.
TouchAlias string
// TouchAtMs is the time this request wrote under TouchAlias (the cold clock, before the forward). The host
// hands it back to ConfirmRealTouch, so a confirm ends only the carry its OWN request wrote. 0 when this
// request wrote no clock (a bypassed one).
TouchAtMs int64
// TouchSeq numbers that write (the carry it makes holds it). The host hands it back with TouchAtMs.
TouchSeq int64
// Thread is the request's thread, from Opts.ThreadOf; ThreadResolved says ThreadOf ran.
Thread thread.Result
ThreadResolved bool
Bypassed bool
// BypassCount, set only on a bypassed request, returns the token figures the pipeline would
// have reported for it: the message tokens before (and, nothing having run, after) and
// AttemptedTokens. It tokenizes the whole transcript, so it must never be called on the
// request path; the dashboard's count worker calls it.
BypassCount func() (before, attempted int)
CacheAware bool
MaxCachedIdx int
// Messages is the normalized message count this request carried.
Messages int
// AttemptedTokens is the token count of the messages age/supersession
// offloaders were ALLOWED to touch (the uncached tail when cache-aware, the
// whole request otherwise). It is the honest denominator for
// "saved / attempted-to-compress"; TokensBefore−AttemptedTokens is the
// compaction our own cache-safety mechanism deliberately gave up.
AttemptedTokens int
// FrozenTokens is TokensBefore−AttemptedTokens: the cost of cache safety.
FrozenTokens int
// Breakpoints is where this request's prompt-cache breakpoints sat ON ARRIVAL,
// split by location. Observational, and free: the pipeline already counts them to
// respect the provider's cap of four.
Breakpoints Breakpoints
// CacheTTL is the prompt-cache lifetime tier this request asked for: "ephemeral_5m",
// "ephemeral_1h", or "" when the body carried no cache_control at all. See ttlTier.
CacheTTL string
// FilteredDeclTokens is what the declaration filter stopped carrying on this request:
// the token weight of the `tools` elements it removed under the account's opt-in list.
// 0 when nothing was configured, nothing matched, or the prose gate refused.
//
// It is the ONLY honest numerator for this feature's saving, and it is written from the
// filter itself rather than derived from the inventory: the inventory records what the
// CLIENT declared (it reads the pristine body), so a figure computed from it would keep
// reporting a saving for a request the filter had declined to touch.
FilteredDeclTokens int
// FilteredDeclBytes is the bytes the filter took out of the body: the same removal in the unit the accountant's
// request ratio converts (#1533). A count. 0 when nothing went.
FilteredDeclBytes int
// FilteredDecls is how many declarations went, for the component's own report.
FilteredDecls int
// HeadTTL1h says this request asked for the provider's ONE-HOUR cache tier on its head
// breakpoints (`tools`, `system`) while leaving the trailing message breakpoint at five
// minutes. False on every request unless the account opted in.
HeadTTL1h bool
// HeadTTLTokens is the size of the prefix that 1h entry covers — the numerator of the
// head share f, on which the whole mixed-TTL economics is linear. Measured rather than
// assumed, because f was the one input R4's simulation could not read off the database
// and had to parameterise.
HeadTTLTokens int
// Restored is how many expanded originals this request restored as their own message at a
// fixed anchor (`expand.fixed_restore`, #407), and RestoredTokens what those copies added on
// the wire. The pipeline's own token counts do not include them: the copies are inserted after
// it runs, so that no component can ever compact one.
Restored, RestoredTokens int
// Run is the pipeline's aggregate report (nil when the pipeline never ran).
Run *components.RunReport
// Ops are the rewrite operations of this request for the savings computation, in pipeline
// order, with wire positions. OpsDropped counts changes that could not be placed.
Ops []accountant.Operation
OpsDropped int
// Declined says a component changed the message count, the rebuild of the shortened messages
// failed, and the proxy forwards the ORIGINAL body. The run report still shows what the
// components did, but none of it reached the provider, so no saving may be booked (#1179).
Declined bool
// Changes lists each rewritten message's before/after text (clipped).
Changes []Change
}
Trace is the per-request record of what BodyFull actually did: the resolved session, the pipeline's own run report (per-component accounting), the before/after text of every rewritten message, and the cache-awareness facts that decided which messages were even eligible. It is the dashboard's capture input — the same material CONTEXT_GURU_DUMP writes to a file, handed to a caller instead. Purely observational: nothing on it affects the rewrite.