inference

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: Apache-2.0 Imports: 58 Imported by: 1 module, 0 packages

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

Documentation

Overview

Package inference's Dispatch is the shape-agnostic per-request flow. It owns: classification branching (proxy vs normal), routing resolution, translator chaining (inbound ↔ canonical ↔ upstream), pipeline invocation, and response wrapping.

Per-shape routes (registered via app/adapter.MountRoutes) own only:

  1. Minimal parse to extract the model name + stream flag.
  2. The Dispatch call with the inbound shape Name.

This keeps shape-specific files out of app/httpapi/inference/.

Package inference is the data-plane HTTP API: /v1/* and /healthz.

Mount(r, deps) wires huma+chi onto an existing chi router and returns the huma.API. The package owns its huma.Config; main.go constructs Deps and calls Mount.

Token verification runs on the request path, so it reads only the held public key and the snapshot, never Postgres. Minting is control-plane only.

The verified-claims cache is deliberately not an LRU: every entry has the same short life, so two generations bound the size without a recency list on the hot path.

Index

Constants

View Source
const (
	// HeaderOrigin is "relay" when relay minted the response (auth,
	// routing, rate limit, admission — or a relay verdict about an upstream
	// failure), "upstream" when the provider's bytes passed through.
	HeaderOrigin = "X-WR-Origin"
	// HeaderUpstreamStatus carries the provider's HTTP status on
	// relay-minted errors that report an upstream failure, so the two
	// layers' statuses are never conflated.
	HeaderUpstreamStatus = "X-WR-Upstream-Status"
)

Error-attribution headers. Relay's error envelope and an OpenAI-shaped upstream's envelope are indistinguishable by body alone, so every response declares which side produced it: a 401 with origin "relay" means your relay key; origin "upstream" means the provider rejected the upstream key.

View Source
const (
	CredentialKey   = "key"
	CredentialToken = "token"
)

Credential kinds a Principal can be authenticated by.

View Source
const MaxAttributionValueBytes = 256

MaxAttributionValueBytes caps one recorded attribution value. The values ride into every usage event, so a caller cannot inflate the record.

Variables

View Source
var (
	ErrInvalidProxyMode   = errors.New("inference: invalid X-WR-Proxy-Mode value")
	ErrMissingUpstreamKey = errors.New("inference: proxy mode requires Authorization: Bearer <upstream-key>")
)

Sentinel errors returned by Classify. The middleware maps these to 400.

View Source
var ErrTokensDisabled = errors.New("inference: tokens are not enabled")

ErrTokensDisabled means no signing key is configured, so no token can be trusted.

Functions

func ClassifyMiddleware

func ClassifyMiddleware() func(http.Handler) http.Handler

ClassifyMiddleware runs Classify once per request and stashes the result on ctx. Shape-invalid requests get a 400 envelope; everything else falls through to the next handler. Gating (Settings.ProxyMode flags, unknown-slug rejection) lives downstream so this middleware stays snapshot-free.

func Dispatch

func Dispatch(d Deps, w http.ResponseWriter, r *http.Request, in DispatchInput)

Dispatch runs the shape-agnostic flow. Called from route handlers after a minimal parse to extract ModelName + Stream.

func ExtractModelStream

func ExtractModelStream(body []byte) (model string, stream bool, err error)

ExtractModelStream parses the caller-supplied model name and stream flag from a request body. Reused by the batch subsystem's per-item runner.

func ForwardUpstreamHeaders

func ForwardUpstreamHeaders(dst, src http.Header)

ForwardUpstreamHeaders copies src → dst, dropping hop-by-hop, and stamps the response origin as "upstream" (Set, not Add — an upstream must not be able to spoof a relay-origin claim). The caller is responsible for any further adjustments (e.g. clearing Content-Length when the body size will change between upstream and client). Exported so adapter packages can use it from their own cross-shape handlers.

func KeyFromContext added in v0.10.0

func KeyFromContext(ctx context.Context) *key.Key

KeyFromContext returns the authenticated relay key from ctx, or nil if no key middleware fired.

func MapPipelineErr

func MapPipelineErr(w http.ResponseWriter, err error)

MapPipelineErr is the exported form for adapter-side cross-shape handlers that drive pipeline.Pipeline.Run directly.

func Mount

func Mount(r chi.Router, d Deps) huma.API

Mount installs the data-plane huma API on r and registers all operations. Returns the huma.API so the caller can attach test-only operations.

func PrincipalMiddleware added in v0.10.0

func PrincipalMiddleware(cat *appcatalog.Catalog, tokens *TokenVerifier) func(http.Handler) http.Handler

PrincipalMiddleware authenticates the inbound credential according to the request's Mode classification (set by ClassifyMiddleware upstream) and resolves who it acts as:

  • ModeNormal — credential is required; lookup must succeed.
  • ModeProxyAuthed — credential is required; lookup must succeed and the principal must be allowed to bring its own upstream key.
  • ModeProxyAnonymous — no credential; this middleware is a no-op and neither a *Key nor a *Principal is stashed on ctx.

The bearer is either a key or a relay-minted token, told apart by shape (looksLikeToken); both resolve to the same Principal and only the lookup differs. Every read is against the in-memory snapshot, re-read per request so admin edits take effect within the NOTIFY debounce window.

func ReadinessMiddleware

func ReadinessMiddleware(cat *appcatalog.Catalog) func(http.Handler) http.Handler

ReadinessMiddleware short-circuits inbound /v1/* requests with 503 until the catalog has built its first snapshot. Until then, lookups against the empty zero-value snapshot would look identical to a legitimately empty catalog — better to refuse traffic explicitly so the caller retries instead of seeing a misleading 404. /healthz is mounted outside this middleware so liveness/readiness probes can still report.

func RewriteModelField

func RewriteModelField(body []byte, upstreamModel string) []byte

RewriteModelField returns body with its "model" field rewritten to upstreamModel (the resolved upstream model name). Reused by the batch subsystem's per-item runner.

func SnapshotFrom added in v0.10.0

func SnapshotFrom(ctx context.Context) *appcatalog.Snapshot

SnapshotFrom returns the catalog view this request was authenticated against, or nil when no credential middleware ran (anonymous proxy). Downstream phases read it rather than cat.Current() so a reload landing mid-request cannot split one request across two snapshots.

func SplitSSEChunks

func SplitSSEChunks(data []byte, atEOF bool) (advance int, token []byte, err error)

SplitSSEChunks is exported so adapter packages can use the same SSE chunking logic in their cross-shape stream handlers.

func StripUnsupportedParams added in v0.9.12

func StripUnsupportedParams(body []byte, m *model.Model, paramPaths map[string]string) ([]byte, []string)

StripUnsupportedParams applies the routed model's UnsupportedParams to a vendor-shaped body via the spec's ParamPaths, recording the per-param drop metric. Reused by runners that build pipeline requests outside Dispatch (batch) so capability gating holds on every path to Pipeline.Run.

func WithClassification

func WithClassification(ctx context.Context, c Classification) context.Context

WithClassification returns a child ctx carrying c.

func WithSnapshot added in v0.10.0

func WithSnapshot(ctx context.Context, snap *appcatalog.Snapshot) context.Context

WithSnapshot pins snap as the catalog view for everything downstream of ctx. The credential middleware and the WebSocket per-frame path are the only writers.

func WriteAPIError

func WriteAPIError(w http.ResponseWriter, status int, errType, code, msg string, attrs ...any)

WriteAPIError emits relay's error envelope. Exported so per-shape route packages (app/adapters/<name>/routes.go) can use it without depending on shape-specific helpers. Extra slog attrs are attached to the warning log only — never to the client envelope.

Types

type Classification

type Classification struct {
	Mode Mode
	// Key is the raw inbound key token. Empty in
	// ModeProxyAnonymous. In ModeNormal pulled from X-WR-API-Key first,
	// then Authorization (Bearer). In ModeProxyAuthed pulled from
	// X-WR-API-Key only.
	Key string
	// UpstreamAuth is the verbatim Authorization header value (including
	// the "Bearer " prefix when present) supplied by the caller for proxy
	// mode. The proxy forwarder re-attaches it on the outbound request.
	// Empty in ModeNormal.
	UpstreamAuth string
	// UpstreamHost is the X-WR-Upstream-Host slug naming a configured
	// Host row. Empty in ModeNormal. Required in proxy mode; the proxy
	// dispatcher rejects missing/unknown values.
	UpstreamHost string
	// ClientIP is the resolved client address — XFF-walked when the peer
	// matches RELAY_TRUSTED_PROXIES, RemoteAddr otherwise.
	ClientIP string
}

Classification carries the result of Classify. Stashed on ctx by the classifier middleware and read by downstream handlers / pipeline / proxy. The classifier is pure — it does not touch the catalog snapshot or any settings; gating decisions happen later.

func ClassificationFrom

func ClassificationFrom(ctx context.Context) Classification

ClassificationFrom returns the mode classification from ctx. The zero Classification (Mode == ModeUnknown) is returned if no classifier ran.

func Classify

func Classify(r *http.Request) (Classification, error)

Classify extracts the mode, credentials, and client IP from r. Pure; no ctx writes, no snapshot reads. Returns an error only for shape- invalid inputs (bad header value, missing upstream key in proxy mode); the caller maps errors to HTTP responses.

type Deps

type Deps struct {
	// Pinger reports backend health for /healthz. Storage satisfies
	// this; tests can pass a stub.
	Pinger Pinger

	// Catalog is the in-memory snapshot used for key auth lookup
	// and the /v1/models listing.
	Catalog *appcatalog.Catalog

	// Tokens verifies relay-minted inference tokens. nil rejects every
	// token bearer, which is the posture when tokens are disabled.
	Tokens *TokenVerifier

	// Resolver translates inbound model+policy refs into a pipeline-
	// ready Plan against the snapshot.
	Resolver *routing.Resolver

	// Pipeline orchestrates one normal-mode inference request.
	Pipeline *pipeline.Pipeline

	// Proxy orchestrates a proxy-mode (BYO upstream key) request.
	Proxy *proxy.Pipeline

	// Lifecycle is the observer registry. Dispatch uses it to fire a
	// failure post-flight event for requests rejected before a runner is
	// reached (routing / proxy gating / translate errors) — runner-stage
	// failures are fired by the runner. Same registry the runners hold.
	Lifecycle *lifecycle.Registry

	// Adapters keys the wire-protocol implementation by adapters.Name.
	// Handlers look up the binding's Adapter Name here at request time;
	// proxy mode looks up the extractor by inbound endpoint shape.
	Adapters map[adapters.Name]pipeline.Adapter

	// Specs is the generic adapter registry. Dispatch uses it to look up
	// inbound and upstream translators and to determine routing strategy
	// (byte-pass vs canonical cross-shape). Built once at boot and
	// populated from cmd/relay/main.go.
	Specs *adapter.Registry

	// RouteMounters are per-adapter route registration functions. Each
	// adapter (or the generic framework) exposes a MountRoutes function
	// that satisfies RouteMounter; cmd/relay/main.go wires them in.
	RouteMounters []RouteMounter

	// Profiles are the client profiles this deployment serves, registered
	// at the composition root. Nil means none: no /{profile}/ routes, no
	// profile on the request context, behaviour unchanged.
	Profiles *clientprofile.Registry

	// PublicURL is the externally reachable base of this data plane
	// (RELAY_INFERENCE_API_URL). A client document that has to print the
	// endpoint its reader should call needs it; empty means derive it per
	// request from the origin the caller arrived on.
	PublicURL string

	// TokenCalibrator answers the count-tokens endpoint from the ratio relay measured on completed requests, for upstreams with no counter of their own. Nil is safe: those requests fall through to a byte estimate.
	TokenCalibrator *tokencount.Calibrator

	// StreamKeepAlive is how long a streamed response may go without bytes before relay emits the inbound shape's no-op frame itself (RELAY_STREAM_KEEPALIVE_S). Upstreams stay silent through long prompt processing or thinking, and coding-agent clients abort a stream after a few minutes of silence. 0 disables the keepalive.
	StreamKeepAlive time.Duration

	// TrustEventTime makes Dispatch honor the X-WR-Event-Time header as
	// the usage Event timestamp (RELAY_DEV_TRUST_EVENT_TIME). Dev/replay
	// tooling only; off by default.
	TrustEventTime bool
}

Deps is the typed dependency bundle for the data plane.

type DispatchInput

type DispatchInput struct {
	// Inbound is the wire shape the caller spoke (the route's Name).
	Inbound adapters.Name

	// Body is the raw inbound request body, already consumed from r.Body.
	Body []byte

	// ModelName is the caller-supplied model identifier extracted by the
	// per-shape minimal parse. Routing resolution uses this.
	ModelName string

	// Stream is the caller-supplied stream flag from the minimal parse.
	// Determines whether the response leg streams chunks or buffers + emits.
	Stream bool
}

DispatchInput is what a per-shape route passes to Dispatch after its own minimal parse. The route knows the inbound shape Name (because it owns the URL); Dispatch handles everything from routing onward.

type Mode

type Mode int

Mode classifies the proxy mode of an inbound inference request.

const (
	ModeUnknown Mode = iota
	// ModeNormal — default; no X-WR-Proxy-Mode; relay key authenticates
	// against a Policy and the upstream key comes from the keypool.
	ModeNormal
	// ModeProxyAuthed — X-WR-Proxy-Mode: Proxy + relay key in X-WR-API-Key
	// + caller-supplied upstream key in Authorization. Logged against the
	// relay key; subject to the inference-api-proxy system rate limit.
	ModeProxyAuthed
	// ModeProxyAnonymous — X-WR-Proxy-Mode: Proxy + caller-supplied
	// upstream key in Authorization, no relay key. Subject to the
	// inference-api-proxy-anonymous per-IP rate limit. Gated by
	// Settings.ProxyMode.AllowUnauthenticated.
	ModeProxyAnonymous
)

type Pinger

type Pinger interface {
	Ping(ctx context.Context) error
}

Pinger reports backend health for /healthz. Storage satisfies this via its own Ping method; tests can supply a stub.

type Principal added in v0.10.0

type Principal struct {
	Subjects                     []string
	UserID, ServiceAccountID     string // exactly one set
	ProjectID, TeamID            string // empty for personal keys
	CredentialKind, CredentialID string // CredentialKey/CredentialToken; key id or jti
	KeyHash                      string // hash presented; empty for tokens
	Key                          *key.Key
	ServiceAccount               *serviceaccount.ServiceAccount
	Policy                       *policy.Policy // nil → policy-less
	PassthroughAllowed           bool
	PayloadLogging               bool

	// TokenExp/TokenVer are the claims a token credential was admitted
	// under, kept so a long-lived connection can re-check them without the
	// bearer. Zero for a key.
	TokenExp int64
	TokenVer int
}

Principal is who the request is acting as, resolved once at the edge so nothing downstream re-derives it. Credential-specific fields (CredentialKind, CredentialID) name the credential presented, not the subject.

func PrincipalFrom added in v0.10.0

func PrincipalFrom(ctx context.Context) *Principal

PrincipalFrom returns the resolved principal from ctx, or nil when the request carried no credential (anonymous proxy mode).

func (*Principal) PolicyID added in v0.10.0

func (p *Principal) PolicyID() string

PolicyID returns the resolved policy's id, or "" for the policy-less flow. Nil-safe so error paths can call it unguarded.

func (*Principal) Recheck added in v0.10.0

func (p *Principal) Recheck(snap *appcatalog.Snapshot, now time.Time) error

Recheck re-validates an already-admitted principal against the current snapshot. The HTTP path resolves once per request and never needs it; a WebSocket admits on the upgrade and then serves frames for hours, so every frame re-runs the revocation checks the upgrade made. Snapshot reads only — no signature work, no Postgres.

type RouteMounter

type RouteMounter = func(api huma.API, d Deps, mw huma.Middlewares)

RouteMounter is what an adapter package exposes to mount its own inbound HTTP surface. Each adapter (openai, anthropic, ...) provides a MountRoutes(api, deps, mw) function matching this signature.

func MountRegistry

func MountRegistry(reg *adapter.Registry) RouteMounter

MountRegistry returns a RouteMounter that registers one POST route per InboundPath across all specs in reg. Each route performs a minimal JSON parse (model + stream), then calls Dispatch with the spec's Name as the inbound shape.

This is the generic route mounter that replaces per-shape MountRoutes functions. The composition root calls it once with the populated registry.

type TokenVerifier added in v0.10.0

type TokenVerifier struct {
	// contains filtered or unexported fields
}

TokenVerifier holds the public half of the token signing key. The composition root swaps the key in when the auth:tokens section changes; a nil verifier (or one with no key) rejects every token, which is what a deployment with tokens disabled wants.

func (*TokenVerifier) PreviousPublicKey added in v0.10.0

func (v *TokenVerifier) PreviousPublicKey() ed25519.PublicKey

PreviousPublicKey returns the key a rotation retired, or nil.

func (*TokenVerifier) PublicKey added in v0.10.0

func (v *TokenVerifier) PublicKey() ed25519.PublicKey

PublicKey returns the key tokens are currently minted under, or nil.

func (*TokenVerifier) SetCacheSize added in v0.10.0

func (v *TokenVerifier) SetCacheSize(n int)

SetCacheSize bounds the verified-claims cache. 0 turns it off.

func (*TokenVerifier) SetKey added in v0.10.0

func (v *TokenVerifier) SetKey(pub ed25519.PublicKey)

SetKey installs the verification key, demoting the one it replaces so tokens already minted under it keep verifying. A nil key disables tokens and drops both.

func (*TokenVerifier) SetKeys added in v0.10.0

func (v *TokenVerifier) SetKeys(current, previous ed25519.PublicKey)

SetKeys installs the current key alongside the one rotation replaced, so a pod that did not perform the rotation still verifies tokens minted before it. A nil current key disables tokens and drops both.

func (*TokenVerifier) Verify added in v0.10.0

func (v *TokenVerifier) Verify(token string) (crypto.TokenClaims, error)

Verify checks the signature and returns the claims. Claim policy (expiry, issuer, version) is the caller's.

Jump to

Keyboard shortcuts

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