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 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 EnforcedSessionIDFor(pipe *components.Pipeline, tenant, explicitSess, api string, ...) string
- func InBandBreakpointStats() (moved, noMark, notFound, tooFar int64)
- 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 SessionIDFor(tenant, explicitSess string, provider bschemas.ModelProvider, body []byte) string
- func TailBreakpointStats() (added, noSlot, atEnd, shortTail, noMark, notFound int64)
- type Breakpoints
- 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 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 keeper uses this, with the billed tier, to pick a session's keep-alive schedule.
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 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 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 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 a req.Input that no longer lines up with wire, so those changes are 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 aliasSeen 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.
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 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.
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 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
// internal/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.
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
// internal/compactionpoint for the definition and why it is not the window.
CompactionPoint int
// CompactionPointSource is "measured" | "assumed" | "configured" | "client_default" | "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
// 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
// CanKeepAlive, when set, tells a component whether the host's keep-alive can ping the thread of
// the session this request belongs to. See components.Ctx.CanKeepAlive. nil => it cannot.
CanKeepAlive func(session, thread string) 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
// 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
// SplitTailHash identifies the VOLATILE half the split moved the breakpoint off. Compared
// against the same session's previous request to decide whether the snapshot moved, which
// is the turn on which the split is worth anything: with the block unsplit, a moved
// snapshot re-creates the whole thing. 0 when nothing split.
SplitTailHash uint64
// SplitStableTokens is the token count of the half the volatile-tail split moved the
// breakpoint onto — the tokens it moved out of the cache-creation tier. 0 when nothing
// split. It is the honest numerator for the prefix-cache saving: the alternative,
// crediting the request's whole cache_read, over-credits by whatever the agent's OTHER
// breakpoints were already matching — 7.5x in dollars on a measured session.
SplitStableTokens int
// 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
// 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
// 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.