lifecycle

package
v0.7.11 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package lifecycle is the order of the steps around one request, for every host.

A host (the proxy, the bifrost adapter, the Cortex plugin) reads a request, calls the pipeline through apply, forwards the request and writes the answer. Several steps come before the pipeline, between it and the upstream call, and after the answer. Their ORDER matters: expand repair must run before the pipeline reads the transcript, the keep-alive arrival must run after the thread is known, tool deferral must see the final tools array. This package holds that order in code, so a host calls one function and cannot get it wrong.

The host keeps the HTTP read, the upstream call, the response write and the credentials. It gives this package function values for the steps that need its own state (the keeper, the dashboard capture, the observe pool, tool deferral).

It never imports proxy, proxyapp or dash. Every step fails open: Prepare recovers a panic and gives back the original body.

Index

Constants

View Source
const (
	GateDetected       = "detected"
	GateOversizeBypass = "oversize_bypass"
)

Gate values CompactionGate reports.

Variables

This section is empty.

Functions

func CompactionGate

func CompactionGate(headerBypass, agentCompaction bool, bodyLen int, limit int64) (bypassed bool, gate string)

CompactionGate decides what the agent's own compaction request does to the bypass flag.

Only the bypass header (headerBypass) bypasses. The agent's compaction request goes through the pipeline like any other request, so the provider cache stays warm. The one exception is size: a compaction body longer than limit bytes is bypassed.

gate is "" when the request is not a compaction, or when headerBypass already bypassed it. Otherwise it is GateDetected or GateOversizeBypass, and the host reports it.

func Enforcing

func Enforcing(mode components.Mode, bypassed bool) bool

Enforcing reports whether the host rewrites this request at all. It is the gate of expand repair, the fixed-restore anchor and every tool injection.

func Finish

func Finish(f Fin)

Finish runs the steps after the response, in their order:

  1. Touch (keep-alive), then Ledger (tool deferral);
  2. release a cache-aware summary the turn deferred because its cache was cold;
  3. run the warm sweep's question, if the trigger registered one;
  4. Counters (the host's SSE and usage counters);
  5. only when usage is OK: keep the billed input for the next turn, under the session and the thread, and, in observe mode, under the shadow store too.

A response without usage leaves the previous turn's figure in place: a zero would read as "unknown" and shut the fraction gate.

func Inject

func Inject(wire string, provider bschemas.ModelProvider, pipe *components.Pipeline, injectExpand string, storePersists bool, body []byte) []byte

Inject advertises the proxy's own tools on a request the host rewrites: the expand tool, then the adjudication tool. Both are sticky and appended last, so the provider's cached prefix stays warm. Under expand.InjectAuto the expand tool goes in only when the pipeline can mint a marker (Pipeline.HasOffload). The adjudication tool goes in only for a pipeline with extract_llm_sweep, on a wire whose prefixed ask has an adapter.

Hosts call it only for a request they rewrite. Observe mode and a bypassed request are forwarded byte for byte, so nothing is injected there. The agent's own compaction request is not bypassed, so it gets the tool like every earlier turn of its thread. That keeps the tools array, which the provider hashes ahead of messages, the same as on the previous turn.

Known gaps this leaves on a compaction turn (the prompt tells the model to call no tool, so both need a model that ignores it):

  • OpenAI dialect with stream:true: if the model calls context_guru_expand (or context_guru_adjudicate, declared on Chat since #1030), the client gets the raw tool call. The proxy does not inspect non-Anthropic SSE (see the isSSE case in serve). Claude Code uses the Anthropic dialect and is not hit.
  • Any dialect: if the model calls expand on every round, the client gets the raw tool call after maxExpandRounds, with no summary. That takes 4 calls in a row.

compactionexpand_test.go pins both, so a change shows.

Why `auto` asks Pipeline.HasOffload rather than a list of presets: a pipeline with no offload declared a tool whose every use is guaranteed to fail, and `off` is the A/B control arm, which must not carry an extra tool. The adjudication tool is gated on pipeline membership and the provider, both byte-stable under one config, so the tools array never flaps from turn to turn.

func Observing

func Observing(mode components.Mode, bypassed bool) bool

Observing reports whether this request is in observe mode: the pipeline runs off-path on a copy, and the forwarded body is the original. A bypassed request is never observed.

func RatesFor

RatesFor hands the pipeline the operator's rate card as a lookup by model name, so a component that compacts with a model other than the request's own prices its spend from the same card the bill uses. nil when there is no pricer.

func RatesOf added in v0.7.10

RatesOf is the rate card of a price: the four base rates and its tiers as absolute rates. The tiers come from modelinfo.Price.At, the one place that resolves a tier's rates.

func ResolveCompactionPoint

func ResolveCompactionPoint(ctx context.Context, r modelinfo.Resolver, model string, window int) compactionpoint.Point

ResolveCompactionPoint is C for a model: the compaction point the operator states for it, else the built-in table of compactionpoint. window is ResolveWindow's figure.

func ResolveWindow

func ResolveWindow(ctx context.Context, r modelinfo.Resolver, model string) (window int, exact bool)

ResolveWindow is a model's context window and whether the figure is published for that model rather than guessed from its family. exact is false for both "unknown" and "a guess": a caller that must not act on a guess must not act on an unknown either. A nil resolver gives (0, false). Every path of every host reads the window here, so they cannot disagree.

func SelfRates

func SelfRates(ctx context.Context, p modelinfo.Pricer, model string) components.TokenRates

SelfRates is the per-token rate card of one model, for a component that calls that model and prices its own spend. A nil pricer or an unnameable model gives the zero value, which a component must read as "unknown" and fall back on, never as free.

Types

type Fin

type Fin struct {
	// Store is the tenant's store. Shadow is the store the observe-mode off-path run reads. It may be nil.
	Store, Shadow store.Store
	Mode          components.Mode
	// Session and ThreadID are Trace.Session and the thread of the request. Every write below
	// uses this pair, or state is written under one key and read under another.
	Session, ThreadID string
	// UsageOK says the response reported usage. Billed is fresh + cache read + cache write input.
	UsageOK bool
	Billed  int64
	// RatioTokens and RatioBytes are the request ratio of this turn: the provider's billed tokens of the forwarded
	// text and its bytes (accountant.Ratio.Text), 0 when the host has none. Kept for the thread's next turn (#1533).
	RatioTokens, RatioBytes int
	// Forwarded says the upstream answered with a 2xx status. CacheRead is the cache-read tokens of the response.
	Forwarded bool
	CacheRead int
	// ObserveSession derives the session id the shadow pipeline uses, for an observe-mode request
	// (where Session is empty). nil or "" skips the shadow record. ObserveThread is the thread
	// resolver the off-path run uses; nil keeps ThreadID.
	ObserveSession func() string
	ObserveThread  func(session string) thread.Result

	// Touch hands the finished request to the keep-alive. It runs first.
	Touch func()
	// Ledger books the request in the tool-deferral ledger.
	Ledger func()
	// Counters runs after the warm sweep's question and before the billed-input writes. The host
	// books its SSE and usage counters here.
	Counters func()
}

Fin is the input of Finish: the facts of one finished request and the steps only the host can do.

type Pre

type Pre struct {
	Wire     string
	Provider bschemas.ModelProvider
	Mode     components.Mode
	// Bypassed is the request's final bypass flag (the header, or CompactionGate's size bypass).
	Bypassed bool
	Pipe     *components.Pipeline
	// Store is the tenant's store. Expand injection asks it whether it persists. It is read inside
	// Prepare, where a panic fails open.
	Store interface{ Persists() bool }
	// InjectExpand is the expand injection mode ("" means expand.InjectAuto).
	InjectExpand string
	// Orig is the request as the agent sent it. Prepare forwards it when a step panics.
	Orig []byte
	// MakeThreadOf builds the thread resolver of the request (thread.Tracker.ResolveSession bound to
	// it). Prepare calls it after the repair and anchor steps and just before the pipeline, and passes
	// the result to Apply. Prepare calls the resolver again when apply returned before it resolved
	// the thread. The result is in Prepared.ThreadOf.
	MakeThreadOf func() func(session string) thread.Result

	// RepairExpand puts back the content a client's own error answer to our expand tool replaced.
	// It runs first, only when the host rewrites the request. It returns the body and the number of
	// repairs.
	RepairExpand func(body []byte) ([]byte, int)
	// Apply runs the pipeline: the host's observe-versus-enforce choice. It gets the body and the
	// thread resolver, and gives back the body, the time to charge to the request and the trace.
	Apply func(body []byte, threadOf func(session string) thread.Result) ([]byte, time.Duration, apply.Trace)
	// Applied runs right after the pipeline, before the thread is resolved. The host notes the
	// latency and the trace here.
	Applied func(tr apply.Trace, added time.Duration)
	// Observed runs once the thread is known, and before the keep-alive arrival. The host notes the
	// thread and the savings record here.
	Observed func(th thread.Result, tr apply.Trace, added time.Duration)
	// Arrive tells the keep-alive and the predictor that a real request arrived on this thread.
	Arrive func(session, threadID string)
	// Settled runs after the stale keep-alive candidate is cleared.
	Settled func(tr apply.Trace, added time.Duration)
	// ToolDefer runs last, on the final tools array, only when the host rewrites the request. It
	// gives back the body to forward.
	ToolDefer func(tr *apply.Trace, th thread.Result, body []byte) []byte
	// Done runs at the end with the body that goes upstream. The host closes the savings record.
	Done func(th thread.Result, body []byte, tr apply.Trace)
	// OnRepair and OnStray report counts of repaired and answered calls, for the host's log.
	OnRepair func(n int)
	OnStray  func(n int)
}

Pre is the input of Prepare: the facts of one request and the steps only the host can do. Every hook may be nil; a nil hook is skipped.

type Prepared

type Prepared struct {
	// Body is the body to forward. On a panic it is Pre.Orig.
	Body []byte
	// PreBody is the body the pipeline received, before any component ran.
	PreBody []byte
	// Anchor is where in-band expands are restored from the next turn on. nil when fixed restore is off.
	Anchor *expand.Anchor
	Trace  apply.Trace
	Added  time.Duration
	// ThreadID is the thread of the request. "" when the thread was not resolved yet.
	ThreadID string
	// ThreadOf is the resolver MakeThreadOf built. nil when a step before it panicked.
	ThreadOf func(session string) thread.Result
	// Panic is the recovered value, nil when no step panicked.
	Panic any
}

Prepared is what Prepare gives back. It is filled in step by step: when a step panics, the fields set before it stay set, as the host's own hoisted variables did.

func Prepare

func Prepare(p Pre) *Prepared

Prepare runs every step before the request goes upstream, in the one order that is right:

  1. expand repair, then the answer to a stray call to our adjudication tool;
  2. the fixed-restore anchor;
  3. the pipeline (Pre.Apply), with the keep-alive start time taken just before it;
  4. the thread (from apply, else resolved here);
  5. Pre.Observed, then Pre.Arrive, then the clear of the stale keep-alive candidate;
  6. the expand injection, then the adjudication injection, then tool deferral.

Steps 1, 2 and 6 run only when the host rewrites the request (not in observe mode, not bypassed). Prepare fails open: a panic in any step, hooks included, gives back Pre.Orig.

type Request

type Request struct {
	Provider bschemas.ModelProvider
	API      string
	Body     []byte
	// Session is the host-supplied session id ("" means a content hash).
	Session string
	Tenant  string
	Models  components.ModelSpec
	// Window and WindowExact are ResolveWindow's answer. CompactionPoint and
	// CompactionPointSource are ResolveCompactionPoint's, as Point.Tokens and Point.Source.
	Window                int
	WindowExact           bool
	CompactionPoint       int
	CompactionPointSource string
	// CacheMode is "auto" | "on" | "off".
	CacheMode string
	Tracker   *modes.Tracker
}

Request is what every call of the pipeline needs, however the host reaches it: the enforced request path, the off-path observation, and the /compact endpoint. One build of these fields keeps the three from drifting (they did once: /compact hard-coded the window as unknown).

func (Request) Opts

func (q Request) Opts() apply.Opts

Opts is the part of apply.Opts all three callers share. A caller sets what is its own on the result: the bypass flag, the rate card, ThreadOf, the cache and keep-alive hooks, the mode.

Jump to

Keyboard shortcuts

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