types

package
v0.8.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: Apache-2.0 Imports: 12 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

Copyright 2024 The Aibrix Team.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2024 The Aibrix Team.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const DefaultQueueCapacity = 1024

Variables

View Source
var (
	ErrQueueEmpty = errors.New("queue is empty")
)
View Source
var (
	ErrUnknown = errors.New("unknown error")
)

Functions

func SetDefaultPDOverrides added in v0.8.0

func SetDefaultPDOverrides(o *PDOverrides)

SetDefaultPDOverrides installs the process-wide PD defaults, keeping the routing defaults that are already installed. It exists so a caller that only owns PD knobs (the pd package and its tests) can fill its half of the table without copying the rest.

func SetDefaultRoutingOverrides added in v0.8.0

func SetDefaultRoutingOverrides(o *RoutingOverrides)

SetDefaultRoutingOverrides installs the process-wide defaults of the routing knobs. The routing algorithm package assembles them from the AIBRIX_* variables at startup, so a read site on a request without a model config profile gets the environment values without a per-request copy.

Types

type AutoBlendOverrides added in v0.8.0

type AutoBlendOverrides struct {
	// LoadBalanceWeight is the weight of the auto-blended load-balance scorer.
	// 0 disables the auto-blend for the request.
	LoadBalanceWeight int
	// LeastRequestWeight is the weight of the least-request-top-k scorer the
	// auto-blend adds. 0 disables that addition. The name is the deployed
	// configuration key (env var and profile field) and predates the scorer
	// switching from plain least-request.
	LeastRequestWeight int
	// PrefixCacheWeight is the prefix-cache weight of the dedicated
	// prefix-cache/load-balance ratio a bare "prefix-cache" request gets.
	PrefixCacheWeight int
	// PrefixCacheLoadBalanceWeight is the load-balance weight of that ratio.
	// 0 leaves those requests with prefix-cache scoring alone.
	PrefixCacheLoadBalanceWeight int
}

AutoBlendOverrides mirrors the AIBRIX_ROUTING_AUTO_BLEND_* weights of the load-balance scorer the gateway silently blends behind every non-exclusive strategy.

type AutoBlendProfileConfig added in v0.8.0

type AutoBlendProfileConfig struct {
	LoadBalanceWeight            *int `json:"loadBalanceWeight,omitempty"`
	LeastRequestWeight           *int `json:"leastRequestWeight,omitempty"`
	PrefixCacheWeight            *int `json:"prefixCacheWeight,omitempty"`
	PrefixCacheLoadBalanceWeight *int `json:"prefixCacheLoadBalanceWeight,omitempty"`
}

AutoBlendProfileConfig mirrors the AIBRIX_ROUTING_AUTO_BLEND_* weights.

type ChatCompletionRequest added in v0.7.0

type ChatCompletionRequest struct {
	openai.ChatCompletionNewParams

	// AddGenerationPrompt controls whether to add the generation prompt to the chat template.
	// Default: true (vLLM default)
	// Reference: https://github.com/vllm-project/vllm/blob/main/vllm/entrypoints/openai/chat_completion/protocol.py
	AddGenerationPrompt *bool `json:"add_generation_prompt,omitempty"`

	// AddSpecialTokens controls whether to add special tokens (e.g. BOS) on top of
	// what is added by the chat template.
	// Default: false (vLLM default) - chat template handles special tokens
	// Reference: https://github.com/vllm-project/vllm/blob/main/vllm/entrypoints/openai/chat_completion/protocol.py
	AddSpecialTokens *bool `json:"add_special_tokens,omitempty"`

	// ReturnTokenStrings controls whether to return token strings in tokenization results.
	// This is used for debugging and verification purposes.
	// Default: false
	// Reference: https://github.com/vllm-project/vllm/blob/main/vllm/entrypoints/openai/chat_completion/protocol.py
	ReturnTokenStrings *bool `json:"return_token_strs,omitempty"`
}

ChatCompletionRequest extends OpenAI's ChatCompletionNewParams with vLLM-specific parameters Reference: https://github.com/vllm-project/vllm/blob/main/vllm/entrypoints/openai/chat_completion/protocol.py

type FallbackRouter added in v0.4.0

type FallbackRouter interface {
	Router

	// SetFallback sets the fallback router
	SetFallback(RoutingAlgorithm, RouterProviderFunc)
}

FallbackRouter enables router chaining by set a fallback router.

type LoadBalanceOverrides added in v0.8.0

type LoadBalanceOverrides struct {
	// ImbalanceFactor overrides AIBRIX_LOAD_BALANCE_IMBALANCE_FACTOR: the factor
	// of the mean over which the gate flags the busiest replica as a hotspot.
	// Used for pools of three or more replicas.
	ImbalanceFactor float64
	// ImbalanceMinGap overrides AIBRIX_LOAD_BALANCE_IMBALANCE_MIN_GAP: the
	// minimum absolute gap between the busiest and the least busy replica
	// required to trigger the gate.
	ImbalanceMinGap int
	// QueuedWeight overrides AIBRIX_LOAD_BALANCE_QUEUED_WEIGHT: the weight of
	// queued requests in the score. 0 is the V1 formula, running requests only.
	QueuedWeight float64
	// KVPressureAlpha overrides AIBRIX_LOAD_BALANCE_KV_PRESSURE_ALPHA: the
	// strength of the quadratic KV-pressure penalty. 0 drops the penalty.
	KVPressureAlpha float64
	// KVCriticalFree overrides AIBRIX_LOAD_BALANCE_KV_CRITICAL_FREE: the
	// free-KV fraction below which a replica scores +Inf. 0 disables the
	// guardrail.
	KVCriticalFree float64
}

LoadBalanceOverrides mirrors the AIBRIX_LOAD_BALANCE_* knobs of the load-balance score and its imbalance gate.

type LoadBalanceProfileConfig added in v0.8.0

type LoadBalanceProfileConfig struct {
	ImbalanceFactor *float64 `json:"imbalanceFactor,omitempty"`
	ImbalanceMinGap *int     `json:"imbalanceMinGap,omitempty"`
	QueuedWeight    *float64 `json:"queuedWeight,omitempty"`
	KVPressureAlpha *float64 `json:"kvPressureAlpha,omitempty"`
	KVCriticalFree  *float64 `json:"kvCriticalFree,omitempty"`
}

LoadBalanceProfileConfig mirrors the AIBRIX_LOAD_BALANCE_* knobs of the load-balance score and its imbalance gate.

type OutputPredictor added in v0.4.0

type OutputPredictor interface {
	// AddTrace collects history input and output tokens data.
	AddTrace(inputTokens, outputTokens int, cnt int32)

	// Predict outputs the number of output tokens based on the number of input tokens.
	Predict(promptLen int) (outputLen int)
}

type OutputPredictorProvider added in v0.4.0

type OutputPredictorProvider interface {
	// GetOutputPredictor returns the output predictor
	GetOutputPredictor(modelName string) (OutputPredictor, error)
}

OutputPredictorProvider provides a stateful way to get an output predictor, allowing a struct to provide the output predictor by model.

type PDAbortOverrides added in v0.8.0

type PDAbortOverrides struct {
	// Timeout is the deadline of the decode abort of a failed prefill.
	Timeout time.Duration
	// RetryDelay is the delay between the two abort attempts.
	RetryDelay time.Duration
}

PDAbortOverrides mirrors AIBRIX_DECODE_ABORT_TIMEOUT and AIBRIX_DECODE_ABORT_RETRY_DELAY. Zero is a meaningful value for both: it disables decode aborts, and it reduces the abort to a single attempt.

type PDDecodeLBOverrides added in v0.8.0

type PDDecodeLBOverrides struct {
	WeightRunning    float64
	WeightThroughput float64
}

PDDecodeLBOverrides mirrors AIBRIX_DECODE_LB_WEIGHT_RUNNING and AIBRIX_DECODE_LB_WEIGHT_THROUGHPUT, the weights of the decode score terms.

type PDLegState added in v0.8.0

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

PDLegState is the prefill/decode leg state of one *incarnation* of a request.

It exists as a separate heap object because RoutingContext is pooled (requestPool) while the async prefill leg is fire-and-forget: the goroutine that posts the prefill request routinely outlives the client stream. The prefill HTTP call is made on a context derived from the request context, so a client cancel fails the prefill leg at the very instant the stream goroutine runs its terminal path and hands the RoutingContext back to the pool.

If that goroutine reported through the pooled RoutingContext, its report could land on whichever request had since taken the object out of the pool: reset() clears the failure slot, so the stale report would win the CAS on the *new* occupant, close the new request's wakeup channel and fail a healthy stream - and the decode abort that follows would carry the new request's rid. Capturing a *PDLegState before launching the goroutine closes that window by construction: reset() installs a brand-new PDLegState, so a goroutine holding a retired one can only ever mutate an object that nothing selects on any more.

Every method is nil-receiver-safe: a RoutingContext built as a struct literal (the gateway does that for metric emission) has no leg, and callers should not have to care.

func (*PDLegState) AbortContext added in v0.8.0

func (l *PDLegState) AbortContext() context.Context

AbortContext returns the context that bounds the best-effort abort of this request's decode leg.

It is rooted at context.Background(), not at the request context: by the time a prefill failure surfaces, the request context is usually cancelled already and the abort is precisely the work that has to outlive it. It is cancellable all the same, because the abort has a stop condition of its own - see MarkDecodeResponded.

The context is built on first use, so the overwhelming majority of requests, which never abort anything, do not pay for one.

func (*PDLegState) AbortDone added in v0.8.0

func (l *PDLegState) AbortDone() <-chan struct{}

AbortDone returns a channel that is closed once the decode-abort handling of this incarnation has finished: the abort goroutine has exited, or the prefill-failure path decided not to start one.

The abort is fire-and-forget yet still writes a log line and a metric sample, so it needs a join point: a test that drives a prefill failure has to be able to wait for it, or the goroutine outlives the test and races whatever the test tears down on its way out.

It is *not* a "nothing is running" predicate: the channel of a leg whose prefill never failed stays open, because no failure was handled on it. Callers wait on it once they know a failure was reported. A nil leg has no abort to wait for and gets an already-closed channel.

func (*PDLegState) DecodeResponded added in v0.8.0

func (l *PDLegState) DecodeResponded() bool

DecodeResponded reports whether anything has come back from the decode pod.

func (*PDLegState) DecodeTarget added in v0.8.0

func (l *PDLegState) DecodeTarget() (addr string, podName string)

DecodeTarget returns the decode leg's address and pod name, or ("", "") when the request was never routed to a decode pod.

func (*PDLegState) FinishDecodeAbort added in v0.8.0

func (l *PDLegState) FinishDecodeAbort()

FinishDecodeAbort ends the decode-abort lifecycle of this incarnation: it releases the abort context and makes AbortDone() ready. It is idempotent, and every path through the prefill-failure handling has to reach it - including the ones that send no abort at all - or a waiter is left hanging.

func (*PDLegState) LastDecodeChunk added in v0.8.0

func (l *PDLegState) LastDecodeChunk() time.Time

LastDecodeChunk returns when the decode pod last sent a response body chunk, or the zero time when it has sent none.

func (*PDLegState) MarkDecodeChunk added in v0.8.0

func (l *PDLegState) MarkDecodeChunk()

MarkDecodeChunk records that a response body chunk came back from the decode pod just now. Called for every chunk, so it is deliberately a single atomic store.

func (*PDLegState) MarkDecodeResponded added in v0.8.0

func (l *PDLegState) MarkDecodeResponded()

MarkDecodeResponded records that the decode pod has started answering, and cancels the abort context with it: a decode leg that is producing tokens has received its KV cache, so an /abort_request still in flight - or a retry still waiting out its delay - is now pointless work aimed at a healthy request.

The flag is stored before the cancel so that an abort context built concurrently with this call comes back already cancelled: AbortContext re-reads the flag under the same lock.

func (*PDLegState) MarkPrefillSucceeded added in v0.8.0

func (l *PDLegState) MarkPrefillSucceeded()

MarkPrefillSucceeded records that the prefill leg returned successfully and closes PrefillSucceeded(). Only the first call has any effect, and only the winner of the CAS closes the channel, so the close happens exactly once however many goroutines race here - the same contract as SetPrefillFailure.

For an SGLang PD request this is the point at which the decode pod has taken the KV transfer and owes the client a response, which is what the decode watchdog times. A non-terminal prefill failure (a 200 whose body the gateway could not parse) marks it too, next to the recorded failure: the KV transfer completed all the same.

func (*PDLegState) PDOverrides added in v0.8.0

func (l *PDLegState) PDOverrides() *PDOverrides

PDOverrides returns the request's PD routing overrides, or the process defaults when none were recorded. The returned struct is read-only and never nil.

func (*PDLegState) PrefillFailed added in v0.8.0

func (l *PDLegState) PrefillFailed() <-chan struct{}

PrefillFailed returns a channel that is closed when the prefill leg of this request fails. It never carries a value: the failure itself is read back with PrefillFailure(). A nil leg yields a nil channel, which blocks forever in a select - the correct "this can never fire" semantics for a non-PD stream.

func (*PDLegState) PrefillFailure added in v0.8.0

func (l *PDLegState) PrefillFailure() *PrefillFailure

PrefillFailure returns the recorded prefill failure, or nil when the prefill leg has not failed (yet).

func (*PDLegState) PrefillSucceeded added in v0.8.0

func (l *PDLegState) PrefillSucceeded() <-chan struct{}

PrefillSucceeded returns a channel that is closed when the prefill leg of this request completes successfully. Like PrefillFailed it never carries a value, and a nil leg yields a nil channel, which blocks forever in a select.

func (*PDLegState) PrefillSucceededAt added in v0.8.0

func (l *PDLegState) PrefillSucceededAt() time.Time

PrefillSucceededAt returns when the prefill leg succeeded, or the zero time when it has not (yet).

func (*PDLegState) RID added in v0.8.0

func (l *PDLegState) RID() string

RID returns the engine-visible request id injected into both PD legs, or "" when this request has no gateway-owned rid.

func (*PDLegState) ResetAfterHeaders added in v0.8.0

func (l *PDLegState) ResetAfterHeaders() bool

ResetAfterHeaders reports whether a terminal prefill failure observed after the decode pod started responding must reset the stream.

func (*PDLegState) SetDecodeTarget added in v0.8.0

func (l *PDLegState) SetDecodeTarget(addr, podName string)

SetDecodeTarget records the address and pod name of the decode leg, so a prefill failure can be aimed at the pod that is waiting for the KV transfer.

func (*PDLegState) SetPDOverrides added in v0.8.0

func (l *PDLegState) SetPDOverrides(o *PDOverrides)

SetPDOverrides records the request's PD routing overrides. A nil argument is a no-op and the read sites keep the process defaults.

func (*PDLegState) SetPrefillFailure added in v0.8.0

func (l *PDLegState) SetPrefillFailure(failure *PrefillFailure) bool

SetPrefillFailure records the terminal failure of the prefill leg and reports whether this call was the one that recorded it. Only the first failure is kept, and the winner of the CAS - and only the winner - closes PrefillFailed(), so the close happens exactly once however many goroutines race here.

No "is this leg still live?" guard is needed: a retired PDLegState is inert by construction. Nothing selects on its channel any more and nothing reads its failure, so a stale report is a write into a private object that is about to be garbage collected.

func (*PDLegState) SetRID added in v0.8.0

func (l *PDLegState) SetRID(rid string)

SetRID records the engine-visible rid. Only the first call has any effect in practice: the PD router derives the rid once, before either leg is sent.

func (*PDLegState) SetResetAfterHeaders added in v0.8.0

func (l *PDLegState) SetResetAfterHeaders(reset bool)

SetResetAfterHeaders records whether a terminal prefill failure must reset the decode stream even once the decode pod has started responding.

type PDOverrides added in v0.8.0

type PDOverrides struct {
	Abort     PDAbortOverrides
	Watchdog  PDWatchdogOverrides
	Spreads   PDSpreadOverrides
	DecodeLB  PDDecodeLBOverrides
	TokenLoad PDTokenLoadOverrides
	// HybridCacheLoadFactor overrides AIBRIX_HYBRID_CACHE_LOAD_FACTOR: the
	// fraction of the hybrid prefix-cache/load score the cache term contributes.
	HybridCacheLoadFactor float64
	// MinMatchPct overrides AIBRIX_MIN_MATCH_PCT: the minimum prefix-match
	// percentage (0 to 100) a candidate needs to score as a cache hit.
	MinMatchPct float64
	// PromptLengthBucketing overrides AIBRIX_PROMPT_LENGTH_BUCKETING for
	// requests routed with this profile.
	PromptLengthBucketing bool
	// BucketServe overrides AIBRIX_BUCKET_SERVE: whether the adaptive
	// bucket-serve plan re-orders this request's prefill candidates.
	BucketServe bool
	// BucketServeMode overrides AIBRIX_BUCKET_SERVE_MODE: what the adaptive
	// cut points balance, "rps" or "throughput".
	BucketServeMode string
	// PrefillRequestTimeout overrides AIBRIX_PREFILL_REQUEST_TIMEOUT: the
	// deadline of this request's prefill HTTP call.
	PrefillRequestTimeout time.Duration
}

PDOverrides carries one request's resolved prefill/decode (PD) routing knobs. Like RoutingOverrides it holds concrete values only: the process defaults with the profile's overrides applied, resolved once per request at the profile boundary. The PD path reads the same values from the request's PD leg (PDLegState.PDOverrides), which parks a copy when the PD route starts because the async prefill and decode-abort paths outlive the pooled routing context.

AIBRIX_TOKEN_LOAD_MAX_SESSIONS has no field here on purpose: it gates the shared session table of the token-load tracker, which every model of a gateway process shares, so a per-request cap would not be a real per-model limit. It keeps its environment-only semantics.

func DefaultPDOverrides added in v0.8.0

func DefaultPDOverrides() *PDOverrides

DefaultPDOverrides returns the PD half of the process defaults, which is what a PD read site falls back to when the request carries no resolved overrides. The returned struct is read-only and never nil.

type PDProfileConfig added in v0.8.0

type PDProfileConfig struct {
	// DecodeAbortTimeout and DecodeAbortRetryDelay override
	// AIBRIX_DECODE_ABORT_TIMEOUT and AIBRIX_DECODE_ABORT_RETRY_DELAY. Zero is
	// meaningful for both: it disables decode aborts and reduces the abort to a
	// single attempt.
	DecodeAbortTimeout    *int `json:"decodeAbortTimeout,omitempty"`
	DecodeAbortRetryDelay *int `json:"decodeAbortRetryDelay,omitempty"`
	// DecodeFirstResponseTimeout and DecodeResponseTimeout override
	// AIBRIX_DECODE_FIRST_RESPONSE_TIMEOUT and AIBRIX_DECODE_RESPONSE_TIMEOUT:
	// the decode watchdog's wait for the first response body chunk from the
	// decode pod after the prefill leg succeeded, for streaming and
	// non-streaming requests respectively. DecodeStreamIdleTimeout overrides
	// AIBRIX_DECODE_STREAM_IDLE_TIMEOUT: the longest gap the watchdog allows
	// between two body chunks of a streaming response. Zero disables the
	// matching phase.
	DecodeFirstResponseTimeout *int `json:"decodeFirstResponseTimeout,omitempty"`
	DecodeResponseTimeout      *int `json:"decodeResponseTimeout,omitempty"`
	DecodeStreamIdleTimeout    *int `json:"decodeStreamIdleTimeout,omitempty"`
	// PrefillRequestTimeout overrides AIBRIX_PREFILL_REQUEST_TIMEOUT.
	PrefillRequestTimeout *int `json:"prefillRequestTimeout,omitempty"`
	// PrefillLoadImbalanceMinSpread, DecodeLoadImbalanceMinSpread,
	// DecodeThroughputImbalanceMinSpread and DecodeScoreRatioThreshold mirror
	// the four load-imbalance thresholds of the prefill and decode fast paths.
	PrefillLoadImbalanceMinSpread      *int32   `json:"prefillLoadImbalanceMinSpread,omitempty"`
	DecodeLoadImbalanceMinSpread       *float64 `json:"decodeLoadImbalanceMinSpread,omitempty"`
	DecodeThroughputImbalanceMinSpread *float64 `json:"decodeThroughputImbalanceMinSpread,omitempty"`
	DecodeScoreRatioThreshold          *float64 `json:"decodeScoreRatioThreshold,omitempty"`
	// DecodeLBWeightRunning and DecodeLBWeightThroughput override
	// AIBRIX_DECODE_LB_WEIGHT_RUNNING and AIBRIX_DECODE_LB_WEIGHT_THROUGHPUT.
	DecodeLBWeightRunning    *float64 `json:"decodeLBWeightRunning,omitempty"`
	DecodeLBWeightThroughput *float64 `json:"decodeLBWeightThroughput,omitempty"`
	// HybridCacheLoadFactor and MinMatchPct override
	// AIBRIX_HYBRID_CACHE_LOAD_FACTOR and AIBRIX_MIN_MATCH_PCT.
	HybridCacheLoadFactor *float64 `json:"hybridCacheLoadFactor,omitempty"`
	MinMatchPct           *float64 `json:"minMatchPct,omitempty"`
	// TokenLoadKVWeight, TokenLoadRequestCost, TokenLoadTTLSeconds and
	// TokenLoadSessionTTLSeconds override the AIBRIX_TOKEN_LOAD_* knobs. Zero is
	// meaningful for both TTLs: it disables, respectively, the sweep of the
	// request's charge and the session-delta rule.
	TokenLoadKVWeight          *float64 `json:"tokenLoadKVWeight,omitempty"`
	TokenLoadRequestCost       *float64 `json:"tokenLoadRequestCost,omitempty"`
	TokenLoadTTLSeconds        *int     `json:"tokenLoadTTLSeconds,omitempty"`
	TokenLoadSessionTTLSeconds *int     `json:"tokenLoadSessionTTLSeconds,omitempty"`
}

PDProfileConfig mirrors the prefill/decode knobs a profile may set under routingConfig.pd. Each field maps to one AIBRIX_* variable the PD path reads; types.PDOverrides documents the mapping. A knob the profile leaves unset, or sets to a value the matching environment variable would reject, keeps the environment default.

type PDSpreadOverrides added in v0.8.0

type PDSpreadOverrides struct {
	// PrefillLoadImbalanceMinSpread overrides
	// AIBRIX_PREFILL_LOAD_IMBALANCE_MIN_SPREAD.
	PrefillLoadImbalanceMinSpread int32
	// DecodeLoadImbalanceMinSpread overrides
	// AIBRIX_DECODE_LOAD_IMBALANCE_MIN_SPREAD.
	DecodeLoadImbalanceMinSpread float64
	// DecodeThroughputImbalanceMinSpread overrides
	// AIBRIX_DECODE_THROUGHPUT_IMBALANCE_MIN_SPREAD.
	DecodeThroughputImbalanceMinSpread float64
	// DecodeScoreRatioThreshold overrides
	// AIBRIX_DECODE_SCORE_RATIO_THRESHOLD: the max/min drain-rate score ratio
	// above which the decode fast path treats a replica as a hotspot.
	DecodeScoreRatioThreshold float64
}

PDSpreadOverrides mirrors the four load-imbalance thresholds of the prefill and decode fast paths.

type PDTokenLoadOverrides added in v0.8.0

type PDTokenLoadOverrides struct {
	// KVWeight is the weight of the KV-token cost term.
	KVWeight float64
	// RequestCost is the fixed cost charged per request, in tokens.
	RequestCost float64
	// TTL bounds how long a request's charge stays in the tracker.
	TTL time.Duration
	// SessionTTL bounds how long a session's last prompt is remembered.
	SessionTTL time.Duration
}

PDTokenLoadOverrides mirrors the AIBRIX_TOKEN_LOAD_* knobs of the token-load prefill policy. Zero is meaningful for both TTLs: it disables, respectively, the sweep of the request's charge and the session-delta rule.

type PDWatchdogOverrides added in v0.8.0

type PDWatchdogOverrides struct {
	// FirstResponseTimeout bounds, for a streaming request, the wait between
	// the prefill leg succeeding and the first response body chunk from the
	// decode pod, i.e. its first token. Response headers do not end the wait.
	FirstResponseTimeout time.Duration
	// ResponseTimeout is the same bound for a non-streaming request, where the
	// first body chunk from the decode pod is the finished answer.
	ResponseTimeout time.Duration
	// StreamIdleTimeout bounds, for a streaming request, the gap between two
	// response body chunks from the decode pod once the first one arrived.
	StreamIdleTimeout time.Duration
}

PDWatchdogOverrides mirrors the AIBRIX_DECODE_*_TIMEOUT knobs of the decode watchdog, which fails an SGLang PD request whose decode pod stops answering after the prefill leg succeeded. Zero disables the matching phase.

type PodList

type PodList interface {
	// Len returns the number of pods in the list.
	Len() int

	// All returns a slice of all pods in the list.
	All() []*v1.Pod

	// Indexes returns a slice of indexes for querying pods by index.
	Indexes() []string

	// ListByIndex returns a slice of pods that match the given index.
	ListByIndex(index string) []*v1.Pod

	// ListPortsForPod returns the ports each pod serves on, keyed by pod key
	// (namespace/name, see utils.GeneratePodKey).
	ListPortsForPod() map[string][]int
}

PodList is an interface for a list of pods and support for indexing and querying pods by index.

type PodScorer added in v0.7.0

type PodScorer interface {
	ScoreAll(ctx *RoutingContext, readyPodList PodList) (scores []float64, scored []bool, err error)
	Polarity() Polarity
}

PodScorer defines the interface for strategies that support batch soft-scoring

type Polarity added in v0.7.0

type Polarity int

Polarity indicates whether a higher or lower score is better for a routing strategy

const (
	PolarityLeast Polarity = iota // Lower score is better
	PolarityMost                  // Higher score is better
)

type PostRouteUpdater added in v0.7.0

type PostRouteUpdater interface {
	PostRouteUpdate(ctx *RoutingContext, readyPodList PodList, targetPod *v1.Pod) error
}

PostRouteUpdater defines the interface for strategies that need to update internal state after a target pod has been selected.

type PrebleOverrides added in v0.8.0

type PrebleOverrides struct {
	// TargetGPU overrides AIBRIX_ROUTER_PREBLE_TARGET_GPU: the GPU the cost
	// model assumes for its replicas. "A6000" and "V100" are the known values.
	TargetGPU string
	// DecodingLength overrides AIBRIX_ROUTER_PREBLE_DECODING_LENGTH: the assumed
	// number of decoding tokens per request of the cost model.
	DecodingLength int
}

PrebleOverrides mirrors the prefix-cache-preble cost-model knobs that are read per request.

type PrebleProfileConfig added in v0.8.0

type PrebleProfileConfig struct {
	TargetGPU      *string `json:"targetGPU,omitempty"`
	DecodingLength *int    `json:"decodingLength,omitempty"`
}

PrebleProfileConfig mirrors the prefix-cache-preble cost-model knobs that are read per request.

type PrefillFailure added in v0.8.0

type PrefillFailure struct {
	// Class is a coarse, low-cardinality failure category
	// ("timeout", "transport", "http_status", ...) suitable as a metric label.
	Class string
	// StatusCode is the prefill pod's HTTP status when Class is "http_status",
	// 0 otherwise.
	StatusCode int
	// Message is the error text, for logging and for the client-facing error
	// the gateway synthesises.
	Message string
	// At is when the failure was observed.
	At time.Time
}

PrefillFailure describes a terminal failure of the prefill leg of a disaggregated (PD) request. For engines whose prefill handshake is self-coordinating (SGLang) the prefill leg is fire-and-forget, so the failure is recorded on the request's PD leg state instead of being returned: the gateway goroutine that owns the client stream picks it up from there.

func (*PrefillFailure) ClassOrEmpty added in v0.8.0

func (f *PrefillFailure) ClassOrEmpty() string

ClassOrEmpty returns the failure class, or "" for a nil failure. It lets a caller log the class of a failure it has just recorded without first having to decide whether one was recorded at all.

type PrefixCacheOverrides added in v0.8.0

type PrefixCacheOverrides struct {
	// StandardDeviationFactor is how many standard deviations above the mean
	// replica request count a prefix-match candidate may sit before it is
	// skipped. Read by prefix-cache and by the PD prefill scorer.
	StandardDeviationFactor int
}

PrefixCacheOverrides mirrors AIBRIX_PREFIX_CACHE_STANDARD_DEVIATION_FACTOR.

type PrefixCacheProfileConfig added in v0.8.0

type PrefixCacheProfileConfig struct {
	StandardDeviationFactor *int `json:"standardDeviationFactor,omitempty"`
}

PrefixCacheProfileConfig mirrors AIBRIX_PREFIX_CACHE_STANDARD_DEVIATION_FACTOR.

type QueueEntry added in v0.8.0

type QueueEntry struct {
	*RoutingContext

	// EnqueuedAt is when the request entered the queue; queue wait time is measured
	// from it.
	EnqueuedAt time.Time

	// Model and BaseModel shadow the routing context's fields with the values frozen
	// at enqueue time. Reading them never touches the pooled context.
	Model     string
	BaseModel string
}

QueueEntry is one request's residency in a RouterQueue: the routing context a queue hands a router, plus the metadata the queue reports from.

The metadata lives here rather than on RoutingContext because that context is pooled: as soon as the requester is unblocked - by a route that sets its target pod, or by cancellation - the gateway can return the context to the pool and another request can reset it, while this entry is still queued. Anything a queue reports after that point (wait time, metric labels) reads these frozen fields, never the context.

func NewQueueEntry added in v0.8.0

func NewQueueEntry(ctx *RoutingContext, enqueuedAt time.Time) *QueueEntry

NewQueueEntry freezes the metadata a queue reports from, before the requester can be unblocked and its context recycled.

type QueueRouter added in v0.4.0

type QueueRouter interface {
	Router

	Len() int
}

QueueRouter defines the interface for routers that contains built-in queue and offers queue status query.

type RequestFeatures added in v0.4.0

type RequestFeatures []float64

type ResolvedConfigProfile added in v0.6.0

type ResolvedConfigProfile struct {
	// LockedRoutingStrategy pins the routing strategy model-wide when set.
	// It takes precedence over the routing-strategy request header, the profile
	// RoutingStrategy and the ROUTING_ALGORITHM environment variable.
	LockedRoutingStrategy string
	// AuthoritativeRoutingPolicy records that routing diagnostics must be omitted
	// from the client response. Client routing inputs are cleared before the
	// resolved profile is stored here.
	AuthoritativeRoutingPolicy bool
	RoutingStrategy            string
	RoutingConfig              json.RawMessage
	// Routing is RoutingConfig in its typed form, parsed once when this profile
	// is resolved. Nil when the profile sets no routingConfig or it does not
	// parse; routingalgorithms.ResolveRoutingOverrides turns it into the
	// request's concrete overrides.
	Routing *RoutingConfig
	// RequestsPerSecond is the per-model request-rate limit enforced by enforceModelRPS,
	// resolved from the profile's requestsPerSecond or from its requestsPerSecondPerReplica
	// (which takes precedence and scales it by the model's current routable replica count).
	// Zero means unset/unlimited.
	RequestsPerSecond int64
	// RateWindowSeconds is the window size, in seconds, that RequestsPerSecond is enforced
	// over. Defaults to a 1s window (0 or 1 both mean "1s") when unset; set above 1 for
	// sub-1 RPS values expressed as "1 request every N seconds".
	RateWindowSeconds int64
	// RequestsInflight is the maximum number of concurrent (in-flight) requests allowed on
	// a single replica, enforced per pod rather than as an aggregate. Zero means unset.
	RequestsInflight int64
	// TTFTThresholdS is the per-model time-to-first-token threshold in seconds, resolved
	// from the profile's ttftThresholdS. Zero means unset, in which case the response-body
	// path keeps using the process-wide AIBRIX_TTFT_THRESHOLD_S default.
	TTFTThresholdS int64
}

ResolvedConfigProfile holds the resolved model config profile for a request. Populated from model.aibrix.ai/config annotation based on config-profile header or defaultProfile. Nil when no config is present;

type Router

type Router interface {
	// Route selects a target pod from the provided list of pods.
	// The input pods is guaranteed to be non-empty and contain only routable pods.
	Route(ctx *RoutingContext, readyPodList PodList) (string, error)
}

Router defines the interface for routing logic to select target pods.

type RouterConstructor

type RouterConstructor func() (Router, error)

RouterConstructor defines a constructor for a router.

type RouterProvider

type RouterProvider interface {
	// GetRouter returns the router
	GetRouter(ctx *RoutingContext) (Router, error)
}

RouterProvider provides a stateful way to get a router, allowing a struct to provide the router by strategy and model.

type RouterProviderFunc

type RouterProviderFunc func(*RoutingContext) (Router, error)

RouterProviderFunc provides a stateless way to get a router

type RouterProviderRegistrationFunc

type RouterProviderRegistrationFunc func() RouterProviderFunc

RouterProviderRegistrationFunc provides a way to register RouterProviderFunc

type RouterQueue added in v0.4.0

type RouterQueue[V comparable] interface {
	Enqueue(V, time.Time) error
	Peek(time.Time, PodList) (V, error)
	Dequeue(time.Time) (V, error)
	Len() int
}

type RoutingAlgorithm

type RoutingAlgorithm string

RoutingAlgorithm defines the routing algorithms

func (RoutingAlgorithm) NewContext added in v0.4.0

func (alg RoutingAlgorithm) NewContext(ctx context.Context, model, message, requestID, user string) *RoutingContext

NewContext gets a RoutingContext with current RoutingAlgorithm.

type RoutingConfig added in v0.8.0

type RoutingConfig struct {
	// PromptTokensGte, PromptTokensLt, MaxTokensGte and MaxTokensLt are the
	// auto-selection hints of the "auto" config-profile header.
	PromptTokensGte *int   `json:"promptTokensGte,omitempty"`
	PromptTokensLt  *int   `json:"promptTokensLt,omitempty"`
	MaxTokensGte    *int64 `json:"maxTokensGte,omitempty"`
	MaxTokensLt     *int64 `json:"maxTokensLt,omitempty"`

	// PromptLenBucketMinLength, PromptLenBucketMaxLength and Combined configure
	// prompt-length bucketing of the PD prefill scoring.
	PromptLenBucketMinLength *int  `json:"promptLenBucketMinLength,omitempty"`
	PromptLenBucketMaxLength *int  `json:"promptLenBucketMaxLength,omitempty"`
	Combined                 *bool `json:"combined,omitempty"`
	// PromptLengthBucketing overrides AIBRIX_PROMPT_LENGTH_BUCKETING for
	// requests routed with this profile. Flat, next to the promptLenBucket*
	// fields it interacts with.
	PromptLengthBucketing *bool `json:"promptLengthBucketing,omitempty"`
	// BucketServe and BucketServeMode override AIBRIX_BUCKET_SERVE and
	// AIBRIX_BUCKET_SERVE_MODE for requests routed with this profile. Flat,
	// next to the bucketing switch whose candidates the plan re-orders.
	BucketServe     *bool   `json:"bucketServe,omitempty"`
	BucketServeMode *string `json:"bucketServeMode,omitempty"`
	// PrefillScorePolicy and DecodeScorePolicy select the PD scoring policies
	// for requests routed with this profile.
	PrefillScorePolicy string `json:"prefillScorePolicy,omitempty"`
	DecodeScorePolicy  string `json:"decodeScorePolicy,omitempty"`

	// LoadBalance, PrefixCache, Preble, VTC and AutoBlend mirror the knob
	// families of the matching routing strategies.
	LoadBalance *LoadBalanceProfileConfig `json:"loadBalance,omitempty"`
	PrefixCache *PrefixCacheProfileConfig `json:"prefixCache,omitempty"`
	Preble      *PrebleProfileConfig      `json:"preble,omitempty"`
	VTC         *VTCProfileConfig         `json:"vtc,omitempty"`
	AutoBlend   *AutoBlendProfileConfig   `json:"autoBlend,omitempty"`

	// PD carries the prefill/decode knobs in one flat object, so
	// "routingConfig.pd.decodeAbortTimeout" reads as one knob instead of a
	// four-level path.
	PD *PDProfileConfig `json:"pd,omitempty"`
}

RoutingConfig is the typed form of a model config profile's routingConfig. It is parsed once per request, when the model config profile is resolved (configprofiles.ParseRoutingConfig), and every consumer reads it through ResolvedConfigProfile.Routing: the auto-selection hints, the PD algorithm configuration and the per-request knobs all come from that single parse.

Every field is a pointer so "unset" stays distinguishable from a meaningful zero. Values are validated when the routing overrides are resolved (routingalgorithms.ResolveRoutingOverrides) and not here, so a profile that sets a value the matching AIBRIX_* variable would reject keeps the environment default.

type RoutingContext

type RoutingContext struct {
	context.Context
	Algorithm RoutingAlgorithm
	// ResolvedStrategy is the actual multi-strategy composite RouterManager.Select
	// constructed for this request, including the silent load-balance/least-request-top-k
	// auto-blend when one was added (see appendLoadBalanceBlend) -- e.g.
	// "least-kv-cache,load-balance:1,least-request-top-k:1" for a plain "least-kv-cache"
	// Algorithm. Equal to string(Algorithm) when nothing was blended in, and empty until
	// Select runs (RouterNotSet requests, or a request that errors before selectTargetPod).
	// Algorithm itself is never rewritten to this -- headers, Validate(), and error
	// messages must keep reflecting exactly what the caller asked for.
	ResolvedStrategy string
	Model            string
	// BaseModel is the served base-model name when Model is a LoRA adapter.
	// Empty for base-model requests.
	BaseModel      string
	Engine         string
	Stream         bool
	Message        string
	RequestID      string
	User           *string
	Span           trace.Span // record attrs for main span
	RequestTime    time.Time  // Time when the routing context is created.
	RequestEndTime time.Time  // Time when the routing is done and sent to inference engine.
	PendingLoad    float64    // Normalized pending load of request, available after AddRequestCount call. See cache.PendingLoadProvider
	TraceTerm      int64      // Trace term identifier, available after AddRequestCount call.
	RoutedTime     time.Time  // Time consumed during routing.

	// PrefixMatchText, when set, replaces Message as the text prefix-matching policies
	// hash. The gateway sets it when request-level system/instructions or tools
	// contribute to the prompt before the conversation. Prompt-size estimates keep
	// using Message. Read it through PrefixText.
	PrefixMatchText string

	ReqHeaders       map[string]string
	ReqBody          []byte
	ReqPath          string
	ReqConfigProfile string
	// AsyncJobBackendID is the backend-private identifier used for a pinned
	// asynchronous job request. It is retained only for the lifetime of this
	// routing context so gateway error processing can replace it with the public
	// ID in an upstream error body.
	AsyncJobBackendID string

	PrefillStartTime time.Time // Time when prefill request is started.
	PrefillEndTime   time.Time // Time consumed during prefill.

	// FirstTokenTime records the arrival time of the first response body chunk.
	// Used to compute TTFT/KV-transfer time for streaming responses, where
	// request_end metrics are only emitted on the final chunk.
	FirstTokenTime time.Time

	// RespHeaders holds response headers that the router intends to set.
	// These are typically used to propagate control information back to the client,
	// such as session affinity id.
	// The router implementation (e.g., sessionAffinityRouter) may populate this field
	// during the Route() call.
	RespHeaders map[string]string

	// ConfigProfile holds the resolved model config profile for this request.
	// Set in HandleRequestBody from model.aibrix.ai/config (annotation)
	// based on config-profile header. Nil when no config is present.
	ConfigProfile *ResolvedConfigProfile

	// ReplicaInflightAdmitted is true once the gateway's replica-inflight admission check
	// (enforceReplicaInflight, backed by cache.Store.AdmitPodRunningRequest) has atomically
	// admitted this request AND, in doing so, already applied this gateway's own +1 to the
	// target pod's cross-gateway running-requests counter. Consumers that also increment
	// that counter (addPodStats) must check this first and skip their own increment, or the
	// pod's count would be inflated by an extra, never-decremented +1 for this request.
	ReplicaInflightAdmitted bool
	// contains filtered or unexported fields
}

RoutingContext encapsulates the context information required for routing. It can be extended with more fields as needed in the future.

func NewRoutingContext

func NewRoutingContext(ctx context.Context, algorithms RoutingAlgorithm, model, message, requestID, user string) *RoutingContext

NewRoutingContext gets a RoutingContext from a context pool.

func RecycleRoutingContextForTest added in v0.8.0

func RecycleRoutingContextForTest(r *RoutingContext, ctx context.Context, algorithms RoutingAlgorithm, model, message, requestID, user string) *RoutingContext

RecycleRoutingContextForTest replays, on this exact object, what happens to a pooled RoutingContext when one request ends and the next request picks the same object back out of requestPool: a reset for the new request. It returns r itself, so the caller holds one object that is simultaneously the retired incarnation and the live one - exactly the aliasing that the PD leg state must survive.

It exists only because that aliasing cannot be staged reliably through requestPool from a test: under the race detector sync.Pool.Put drops roughly one in four objects on the floor, so "release it and keep asking until the pool hands the same pointer back" fails at random and no retry loop can fix it. Tests in other packages also cannot call the unexported reset directly.

This is a test seam, not part of the request lifecycle:

  • it never goes through requestPool, so nothing guarantees the object is free - the caller must know it is;
  • it panics outside a test binary (the testing package registers test.v), so a production path cannot reach it even by accident.

Delete remains the one supported way to release a RoutingContext.

func (*RoutingContext) CanAddStats added in v0.4.0

func (r *RoutingContext) CanAddStats() bool

CanAddStats returns true if the first time trying update in-memory realtime statistics.

func (*RoutingContext) CanAddTrace added in v0.4.0

func (r *RoutingContext) CanAddTrace() bool

CanAddTrace returns true if the first time trying add trace to cache.

func (*RoutingContext) CanDoneStats added in v0.4.0

func (r *RoutingContext) CanDoneStats() bool

func (*RoutingContext) CanDoneTrace added in v0.8.0

func (r *RoutingContext) CanDoneTrace() bool

CanDoneTrace returns true only the first time a request finishes its trace bookkeeping. It pairs with CanAddTrace: the model-level pendingRequests counter is incremented once under CanAddTrace, so it must be decremented exactly once here, even though several completion paths (response headers, response body and the receive-error exits) may all call into DoneRequest*.

func (*RoutingContext) ClearRoutingOverrides added in v0.8.0

func (r *RoutingContext) ClearRoutingOverrides()

ClearRoutingOverrides drops the request's resolved overrides, restoring the process defaults. Reset calls it so a pooled context cannot steer the next request with the previous one's profile.

func (*RoutingContext) DecodeResponded added in v0.8.0

func (r *RoutingContext) DecodeResponded() bool

DecodeResponded reports whether the decode pod has started responding.

func (*RoutingContext) DecodeTarget added in v0.8.0

func (r *RoutingContext) DecodeTarget() (addr string, podName string)

DecodeTarget returns where the decode leg of this request was sent.

func (*RoutingContext) Delete

func (r *RoutingContext) Delete()

Delete resolves all waiting TargetPod() calls and releases the RoutingContext to the pool.

func (*RoutingContext) Elapsed added in v0.4.0

func (r *RoutingContext) Elapsed(currentTime time.Time) time.Duration

Elapsed returns the elapsed time since the request was created.

func (*RoutingContext) Features added in v0.4.0

func (r *RoutingContext) Features() (RequestFeatures, error)

Features returns the features corresponding to the request. The feature of a request is defined by the output length and prompt length.

func (*RoutingContext) GetError added in v0.4.0

func (r *RoutingContext) GetError() error

GetError returns the error of the routing context.

func (*RoutingContext) GetRoutingDelay added in v0.4.0

func (r *RoutingContext) GetRoutingDelay() time.Duration

GetRoutingDelay returns the time duration used for routing the request. Returns 0 if routing did not complete (e.g., prefill failure before SetTargetPod was called).

func (*RoutingContext) HasError added in v0.4.0

func (r *RoutingContext) HasError() bool

HasError returns true if the request has an error.

func (*RoutingContext) HasRouted

func (r *RoutingContext) HasRouted() bool

HasRouted returns true if the request has been routed or an error has been set.

func (*RoutingContext) LastDecodeChunk added in v0.8.0

func (r *RoutingContext) LastDecodeChunk() time.Time

LastDecodeChunk returns when the decode pod of the current incarnation last sent a response body chunk, or the zero time.

func (*RoutingContext) MarkDecodeChunk added in v0.8.0

func (r *RoutingContext) MarkDecodeChunk()

MarkDecodeChunk records that the decode pod of the current incarnation sent a response body chunk just now. Nil-safe, like every other leg accessor.

func (*RoutingContext) MarkDecodeResponded added in v0.8.0

func (r *RoutingContext) MarkDecodeResponded()

MarkDecodeResponded records that the decode pod has started responding. Nil-safe: the response paths call it without knowing whether a routing context was ever created for the stream.

func (*RoutingContext) MetricLoraAdapter added in v0.8.0

func (r *RoutingContext) MetricLoraAdapter() string

MetricLoraAdapter returns the adapter name for gateway metrics. Empty for base-model requests.

func (*RoutingContext) MetricModel added in v0.8.0

func (r *RoutingContext) MetricModel() string

MetricModel returns the model name to emit on gateway metrics. For a LoRA request this is the attached base model; otherwise the requested name.

func (*RoutingContext) PDLeg added in v0.8.0

func (r *RoutingContext) PDLeg() *PDLegState

PDLeg returns the PD leg state of this incarnation of the request, or nil when there is none. Callers that outlive the client stream - the async prefill goroutine above all - must capture this pointer before they are launched and use it instead of the RoutingContext, which is pooled and may by then belong to another request.

func (*RoutingContext) PDOverrides added in v0.8.0

func (r *RoutingContext) PDOverrides() *PDOverrides

PDOverrides returns the PD routing overrides of this incarnation of the request, or the process defaults when it has none.

func (*RoutingContext) PDRequestID added in v0.8.0

func (r *RoutingContext) PDRequestID() string

PDRequestID returns the engine-visible request id ("rid") injected into both PD legs, or "" when this request has no gateway-owned rid.

func (*RoutingContext) PodAddress added in v0.8.0

func (r *RoutingContext) PodAddress(pod *v1.Pod) string

PodAddress returns the host:port the gateway would forward this request to if pod were its target, without making pod the target. The PD router needs the decode pod's address before SetTargetPod is called, so the abort of a failed prefill lands on exactly the HTTP server that is serving the decode leg.

func (*RoutingContext) PrefillFailed added in v0.8.0

func (r *RoutingContext) PrefillFailed() <-chan struct{}

PrefillFailed returns the wakeup channel of the current incarnation.

func (*RoutingContext) PrefillFailure added in v0.8.0

func (r *RoutingContext) PrefillFailure() *PrefillFailure

PrefillFailure returns the recorded prefill failure of the current incarnation, or nil.

func (*RoutingContext) PrefillSucceeded added in v0.8.0

func (r *RoutingContext) PrefillSucceeded() <-chan struct{}

PrefillSucceeded returns the success wakeup channel of the current incarnation. The prefill goroutine reports through the *PDLegState it captured, never through this pooled context.

func (*RoutingContext) PrefillSucceededAt added in v0.8.0

func (r *RoutingContext) PrefillSucceededAt() time.Time

PrefillSucceededAt returns when the prefill leg of the current incarnation succeeded, or the zero time.

func (*RoutingContext) PrefixText added in v0.8.0

func (r *RoutingContext) PrefixText() string

PrefixText returns the text prefix-matching policies should hash: PrefixMatchText when set, Message otherwise.

func (*RoutingContext) PromptLength added in v0.4.0

func (r *RoutingContext) PromptLength() (int, error)

PromptLength returns the length of the prompt of the request.

func (*RoutingContext) PromptTokens added in v0.4.0

func (r *RoutingContext) PromptTokens() ([]int, error)

PromptTokens returns the tokenized prompt of the request.

func (*RoutingContext) ResetAfterHeaders added in v0.8.0

func (r *RoutingContext) ResetAfterHeaders() bool

ResetAfterHeaders reports whether an after-response prefill failure must reset the decode stream for this request's engine.

func (*RoutingContext) RoutingOverrides added in v0.8.0

func (r *RoutingContext) RoutingOverrides() *RoutingOverrides

RoutingOverrides returns the request's resolved routing overrides, or the process defaults when the request carries none. The returned struct is read-only and never nil.

func (*RoutingContext) SetDecodeTarget added in v0.8.0

func (r *RoutingContext) SetDecodeTarget(addr, podName string)

SetDecodeTarget records where the decode leg of this request was sent.

func (*RoutingContext) SetError added in v0.4.0

func (r *RoutingContext) SetError(err error)

SetError sets the error of the routing context asynchronously. Do not call this function from synchronize routers. Asynchronize routers call this to set an error.

func (*RoutingContext) SetOutputPredictor added in v0.8.0

func (r *RoutingContext) SetOutputPredictor(predictor OutputPredictor) (old OutputPredictor)

SetOutputPredictor enables RoutingContext to use existing OutputPredictor to predict output length.

func (*RoutingContext) SetPDOverrides added in v0.8.0

func (r *RoutingContext) SetPDOverrides(o *PDOverrides)

SetPDOverrides records the PD routing overrides of this incarnation of the request on its PD leg, where the async prefill and abort paths read them.

func (*RoutingContext) SetPDRequestID added in v0.8.0

func (r *RoutingContext) SetPDRequestID(rid string)

SetPDRequestID records the engine-visible request id ("rid") the PD router injected into both disaggregation legs of this request.

func (*RoutingContext) SetPrefillFailure added in v0.8.0

func (r *RoutingContext) SetPrefillFailure(failure *PrefillFailure) bool

SetPrefillFailure records the terminal failure of the prefill leg on the current incarnation. Callers that may outlive the client stream must hold the *PDLegState from PDLeg() instead, or they risk recording onto the next request that takes this pooled object.

func (*RoutingContext) SetResetAfterHeaders added in v0.8.0

func (r *RoutingContext) SetResetAfterHeaders(reset bool)

SetResetAfterHeaders records whether a terminal prefill failure must reset the decode stream even after the decode pod started responding (see PDLegState.SetResetAfterHeaders).

func (*RoutingContext) SetRoutingOverrides added in v0.8.0

func (r *RoutingContext) SetRoutingOverrides(o *RoutingOverrides)

SetRoutingOverrides records the request's resolved routing overrides. A nil value means the request carries no profile overrides, and reads then fall back to the process defaults.

func (*RoutingContext) SetTargetPod

func (r *RoutingContext) SetTargetPod(pod *v1.Pod)

SetTargetPod sets the target pod of the routing context. All routers call this to set the target pod.

func (*RoutingContext) SetTargetPort added in v0.6.0

func (r *RoutingContext) SetTargetPort(port int)

func (*RoutingContext) SetTrustedPolicyAttribute added in v0.8.0

func (r *RoutingContext) SetTrustedPolicyAttribute(key, value string)

SetTrustedPolicyAttribute records a policy attribute produced by trusted Gateway code. It is intentionally separate from ReqHeaders so external routing can never treat arbitrary client headers as trusted policy input.

func (*RoutingContext) TargetAddress

func (r *RoutingContext) TargetAddress() string

TargetAddress returns the routing target address of the request.

func (*RoutingContext) TargetPod

func (r *RoutingContext) TargetPod() *v1.Pod

TargetPod returns the routing target pod of the request. TargetPod blocks until the target pod is set or an error is set.

func (*RoutingContext) TargetPort added in v0.6.0

func (r *RoutingContext) TargetPort() int

func (*RoutingContext) TokenLength added in v0.4.0

func (r *RoutingContext) TokenLength() (int, error)

TokenLength returns the predicted output token length.

func (*RoutingContext) TrustedPolicyAttributes added in v0.8.0

func (r *RoutingContext) TrustedPolicyAttributes(allowlist []string) map[string]string

TrustedPolicyAttributes returns a defensive copy containing only allowlisted names. An empty result is returned when no trusted producer populated a name.

func (*RoutingContext) WithStatsUpdate added in v0.8.0

func (r *RoutingContext) WithStatsUpdate(fn func())

WithStatsUpdate runs fn while holding the request's statistics lock, so a caller that loses CanAddStats inside fn returns only after the winner's update has finished.

type RoutingOverrides added in v0.8.0

type RoutingOverrides struct {
	LoadBalance LoadBalanceOverrides
	PrefixCache PrefixCacheOverrides
	Preble      PrebleOverrides
	VTC         VTCOverrides
	AutoBlend   AutoBlendOverrides
	PD          PDOverrides
}

RoutingOverrides carries one request's resolved routing knobs: the process defaults with the model config profile's overrides applied. Every field is a concrete value, so a read site uses it directly:

factor := routingCtx.RoutingOverrides().LoadBalance.ImbalanceFactor

The values are resolved once per request at the profile boundary (routingalgorithms.ResolveRoutingOverrides): a profile value the matching AIBRIX_* variable would reject is dropped there, with a log, and the environment default is kept. A profile can therefore only narrow or sharpen routing behaviour, never silently drop a threshold. A request whose profile sets nothing reads the process defaults registered by the routing algorithm package through SetDefaultRoutingOverrides.

Knobs that configure state shared by every model of one gateway process keep a field here only when the read site can scope that state to the profile: a profile that sets one gets its own instance of it, keyed by the resolved values, so profiles that agree share one and a request whose profile sets none reads the process-wide default instance exactly as before. That is how the VTC token tracker's window, time unit, token weights and token floors are carried. Knobs whose state cannot be scoped this way have no field here on purpose, because all models of a process share that state and a per-request value could not be applied without splitting or resizing it: the preble histogram window and eviction loop, the session-affinity local cache capacity, the routing string cache bound and the token-load session table cap. Those keep their environment-only semantics.

func DefaultRoutingOverrides added in v0.8.0

func DefaultRoutingOverrides() *RoutingOverrides

DefaultRoutingOverrides returns the process defaults installed by SetDefaultRoutingOverrides. It never returns nil.

type SingleCandidateBypasser added in v0.8.0

type SingleCandidateBypasser interface {
	BypassSingleCandidate() bool
}

SingleCandidateBypasser lets a router declare whether Gateway may use its zero-network single-candidate fast path. Routers that do not implement this interface retain the existing bypass behavior.

type VTCOverrides added in v0.8.0

type VTCOverrides struct {
	// MaxPodLoad overrides AIBRIX_ROUTER_VTC_BASIC_MAX_POD_LOAD: the
	// running-request count at which the utilization score saturates.
	MaxPodLoad float64
	// FairnessWeight overrides AIBRIX_ROUTER_VTC_BASIC_FAIRNESS_WEIGHT: the
	// weight of the fairness term. 0 drops the term.
	FairnessWeight float64
	// UtilizationWeight overrides AIBRIX_ROUTER_VTC_BASIC_UTILIZATION_WEIGHT:
	// the weight of the utilization term. 0 drops the term.
	UtilizationWeight float64
	// InputTokenWeight and OutputTokenWeight override
	// AIBRIX_ROUTER_VTC_BASIC_INPUT_TOKEN_WEIGHT and
	// AIBRIX_ROUTER_VTC_BASIC_OUTPUT_TOKEN_WEIGHT: the weights the token
	// tracker applies to a request's input and output tokens.
	InputTokenWeight  float64
	OutputTokenWeight float64
	// TokenTracker holds the sliding window and the token floors of the
	// tracker. A request whose profile leaves all of them at their defaults
	// shares the process-wide tracker; any other request gets one of its own,
	// so its window and weights never mix with another model's.
	TokenTracker VTCTokenTrackerOverrides
}

VTCOverrides mirrors the vtc-basic score knobs read per request.

type VTCProfileConfig added in v0.8.0

type VTCProfileConfig struct {
	MaxPodLoad        *float64 `json:"maxPodLoad,omitempty"`
	FairnessWeight    *float64 `json:"fairnessWeight,omitempty"`
	UtilizationWeight *float64 `json:"utilizationWeight,omitempty"`
	// InputTokenWeight and OutputTokenWeight override
	// AIBRIX_ROUTER_VTC_BASIC_INPUT_TOKEN_WEIGHT and
	// AIBRIX_ROUTER_VTC_BASIC_OUTPUT_TOKEN_WEIGHT: the weights the token
	// tracker applies to a request's input and output tokens.
	InputTokenWeight  *float64 `json:"inputTokenWeight,omitempty"`
	OutputTokenWeight *float64 `json:"outputTokenWeight,omitempty"`
	// TokenTrackerWindowSize, TokenTrackerTimeUnit, TokenTrackerMinTokens and
	// TokenTrackerMaxTokens override AIBRIX_ROUTER_VTC_TOKEN_TRACKER_*: the
	// sliding window the token counts are bucketed in and the floors the
	// tracker reports while the window holds little activity. Profiles that
	// set any of the four get their own tracker, weights included, so one
	// model's window and weights never mix with another's.
	TokenTrackerWindowSize *int     `json:"tokenTrackerWindowSize,omitempty"`
	TokenTrackerTimeUnit   *string  `json:"tokenTrackerTimeUnit,omitempty"`
	TokenTrackerMinTokens  *float64 `json:"tokenTrackerMinTokens,omitempty"`
	TokenTrackerMaxTokens  *float64 `json:"tokenTrackerMaxTokens,omitempty"`
}

VTCProfileConfig mirrors the vtc-basic score knobs that are read per request.

type VTCTokenTrackerOverrides added in v0.8.0

type VTCTokenTrackerOverrides struct {
	// WindowSize is how many TimeUnit-sized buckets the sliding window spans.
	WindowSize int
	// TimeUnit is the duration of one bucket: "minutes", "seconds" or
	// "milliseconds".
	TimeUnit string
	// MinTokens and MaxTokens are the floors the tracker reports while the
	// window holds too little activity to derive them from.
	MinTokens float64
	MaxTokens float64
}

VTCTokenTrackerOverrides mirrors the AIBRIX_ROUTER_VTC_TOKEN_TRACKER_* knobs together with the two token weights the tracker applies, since all six are baked into the tracker instance rather than read per request.

Jump to

Keyboard shortcuts

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