apply

package
v0.3.2-test-update Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: Apache-2.0 Imports: 25 Imported by: 2 modules, 1 package

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

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

View Source
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 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 RecordBilledInput added in v0.2.0

func RecordBilledInput(st store.Store, session string, tokens int64)

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

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.

Types

type Breakpoints added in v0.1.1

type Breakpoints struct {
	System   int // system.#.cache_control / .cachePoint
	Tools    int // tools.#.cache_control / .cachePoint
	Messages int // messages.#.cache_control (message level)
	Blocks   int // messages.#.content.#.cache_control / .cachePoint (content-block level)
}

Breakpoints is where a request's prompt-cache breakpoints actually sit, split by the location the provider hashes them at. The split is what makes the count diagnosable rather than merely a number: `tools` and `system` render AHEAD of `messages`, so a breakpoint's location decides how much of the prefix it protects, and a dashboard that reports only a total cannot tell a well-placed request from a badly-placed one with the same count.

func CountBreakpoints added in v0.1.1

func CountBreakpoints(body []byte) Breakpoints

CountBreakpoints counts every breakpoint the provider will see in this request, by location. Structural (a field, per gjson) for the same reason hasCacheBreakpoint is: a tool output whose text merely contains the string "cache_control" must not count.

A component cannot count these for itself. `system` and `tools` never reach it at all, and the `tool_result` blocks this package normalizes into synthetic role=tool messages lose their mark on the way in (see toolMessage) — so on real Claude Code traffic all three of the agent's own breakpoints were invisible to it (2 in `system`, 1 on a `tool_result` block), and it computed 3 free slots when 1 was free: 6 on the wire, and a 400 (issue #32).

ONE pass over the top-level object, not one gjson `#.field` query per location. The path form re-scanned the whole body seven times and squashed every matched array on the way, which made this ~22% of the rewrite path's CPU on real 600 KB Claude Code requests — and it runs twice per request (inbound count + the cap check). Walking the object once also means the location a mark was found AT is known for free, which is what the split below reports; the path form had to derive it from the query string.

func (Breakpoints) Total added in v0.1.1

func (b Breakpoints) Total() int

Total is the figure the provider's cap of four applies to.

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
	// Session is the host-supplied session id ("" => content hash).
	Session string
	// 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" | "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
	// HeadTTLMinTokens is the size gate on HeadTTL1h, in estimated tokens. 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.
	HeadTTLMinTokens 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
	// 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

func BodyOpts(ctx context.Context, pipe *components.Pipeline, st store.Store, o Opts) (res Result)

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
	Bypassed     bool
	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
	// Run is the pipeline's aggregate report (nil when the pipeline never ran).
	Run *components.RunReport
	// 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.

Jump to

Keyboard shortcuts

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