routingalgorithms

package
v0.8.0 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: 41 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.

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 (
	RouterExternal = externalrouter.Algorithm

	EnvExternalRouterEndpoint            = externalrouter.EnvExternalRouterEndpoint
	EnvExternalRouterPolicyMode          = externalrouter.EnvExternalRouterPolicyMode
	EnvExternalRouterFailureMode         = externalrouter.EnvExternalRouterFailureMode
	EnvExternalRouterFallback            = externalrouter.EnvExternalRouterFallback
	EnvExternalRouterTimeout             = externalrouter.EnvExternalRouterTimeout
	EnvExternalRouterMaxInflight         = externalrouter.EnvExternalRouterMaxInflight
	EnvExternalRouterMaxRequestBytes     = externalrouter.EnvExternalRouterMaxRequestBytes
	EnvExternalRouterMaxResponseBytes    = externalrouter.EnvExternalRouterMaxResponseBytes
	EnvExternalRouterFailureThreshold    = externalrouter.EnvExternalRouterFailureThreshold
	EnvExternalRouterOpenDuration        = externalrouter.EnvExternalRouterOpenDuration
	EnvExternalRouterAuthTokenFile       = externalrouter.EnvExternalRouterAuthTokenFile
	EnvExternalRouterCandidateAttributes = externalrouter.EnvExternalRouterCandidateAttributes
	EnvExternalRouterCandidateMetrics    = externalrouter.EnvExternalRouterCandidateMetrics
	EnvExternalRouterPolicyAttributes    = externalrouter.EnvExternalRouterPolicyAttributes
)
View Source
const (
	RouterPD                 types.RoutingAlgorithm = "pd"
	VLLMEngine               string                 = "vllm"
	SGLangEngine             string                 = "sglang"
	TensorRTLLM              string                 = "trtllm"
	LLMEngineIdentifier      string                 = constants.ModelLabelEngine
	PDRoleSetIdentifier      string                 = "roleset-name"
	PDRoleIdentifier         string                 = "role-name"
	PDRolePrefill            string                 = "prefill"
	PDRoleDecode             string                 = "decode"
	RoleReplicaIndex         string                 = "stormservice.orchestration.aibrix.ai/role-replica-index"
	PodGroupIndex            string                 = "stormservice.orchestration.aibrix.ai/pod-group-index"
	PromptLenBucketMinLength string                 = "prompt-len-bucket-min-length"
	PromptLenBucketMaxLength string                 = "prompt-len-bucket-max-length"
)
View Source
const (
	// KVConnectorTypeIdentifier specifies the KV transfer backend for a PD pod. Supported values include "shfs", "nixl", and "mooncake".
	KVConnectorTypeIdentifier = "model.aibrix.ai/kv-connector-type"
	// KV connector types for different backends
	KVConnectorTypeSHFS     = "shfs"     // Default - AIBrix SHFS/KVCacheManager (GPU)
	KVConnectorTypeNIXL     = "nixl"     // NIXL for Neuron (uses disagg_prefill_resp wrapper)
	KVConnectorTypeMooncake = "mooncake" // Mooncake KV transfer backend

	HeaderPrefillTargetPodIP = "prefill-target-pod-ip"
	HeaderPrefillTargetPod   = "prefill-target-pod"
)
View Source
const (
	PREBLE_TARGET_GPU             = "AIBRIX_ROUTER_PREBLE_TARGET_GPU"
	PREBLE_DECODING_LENGTH        = "AIBRIX_ROUTER_PREBLE_DECODING_LENGTH"
	PREBLE_SLIDING_WINDOW_PERIOD  = "AIBRIX_ROUTER_PREBLE_SLIDING_WINDOW_PERIOD"
	PREBLE_EVICTION_LOOP_INTERVAL = "AIBRIX_ROUTER_PREBLE_EVICTION_LOOP_INTERVAL"
)
View Source
const (
	// Default routing algorithm for slo-family algorithms, setting to RouterSLOLeastLoadPulling.
	RouterSLO types.RoutingAlgorithm = "slo"

	// SLO-aware routing algorithm that using SLOQueue and packLoadRouter as the backend.
	RouterSLOPackLoad types.RoutingAlgorithm = "slo-pack-load"

	// SLO-aware routing algorithm that using SLOQueue and leastLoadRouter (push mode) as the backend.
	RouterSLOLeastLoad types.RoutingAlgorithm = "slo-least-load"

	// SLO-aware routing algorithm that using SLOQueue and leastLoadRouter (pull mode) as the backend.
	RouterSLOLeastLoadPulling types.RoutingAlgorithm = "slo-least-load-pulling"
)
View Source
const DefaultFallbackAlgorithm types.RoutingAlgorithm = RouterRandom
View Source
const RouterLeastBusyTime types.RoutingAlgorithm = "least-busy-time"
View Source
const RouterLeastGpuCache types.RoutingAlgorithm = "least-gpu-cache"
View Source
const RouterLeastKvCache types.RoutingAlgorithm = "least-kv-cache"
View Source
const RouterLeastLatency types.RoutingAlgorithm = "least-latency"
View Source
const RouterLeastRequest types.RoutingAlgorithm = "least-request"
View Source
const RouterLeastRequestTopK types.RoutingAlgorithm = "least-request-top-k"
View Source
const (
	RouterNotSet = ""
)
View Source
const RouterPowerOfTwo types.RoutingAlgorithm = "power-of-two"
View Source
const RouterPrefixCachePreble types.RoutingAlgorithm = "prefix-cache-preble"
View Source
const RouterRandom types.RoutingAlgorithm = "random"
View Source
const RouterSessionAffinity types.RoutingAlgorithm = "session-affinity"
View Source
const RouterThroughput types.RoutingAlgorithm = "throughput"
View Source
const RouterUtil types.RoutingAlgorithm = "least-utilization"

Variables

View Source
var (
	ErrExternalPolicyDenied      = externalrouter.ErrExternalPolicyDenied
	ErrExternalRouterUnavailable = externalrouter.ErrExternalRouterUnavailable
	ErrExternalRouterDisabled    = externalrouter.ErrExternalRouterDisabled
)
View Source
var (
	RandomRouter             = &randomRouter{}
	RandomRouterProviderFunc = func(_ *types.RoutingContext) (types.Router, error) { return RandomRouter, nil }
)
View Source
var (
	ErrInitTimeout           = errors.New("router initialization timeout")
	ErrFallbackNotSupported  = errors.New("router not support fallback")
	ErrFallbackNotRegistered = errors.New("fallback router not registered")
)
View Source
var (
	ErrorNoAvailablePod = fmt.Errorf("no pod available")
)
View Source
var ModelRouterFactory = NewSLORouter
View Source
var RouterLoadBalance types.RoutingAlgorithm = "load-balance"
View Source
var (
	RouterPrefixCache types.RoutingAlgorithm = "prefix-cache"
)

Functions

func ApplyLoadImbalanceGate added in v0.8.0

func ApplyLoadImbalanceGate(ctx *types.RoutingContext, c cache.Cache, readyPods []*v1.Pod) []*v1.Pod

ApplyLoadImbalanceGate narrows readyPods to the least-loaded subset when running-request load is severely skewed (see getTargetPodListOnLoadImbalance). Returns readyPods unchanged if not imbalanced.

It is exported so the gateway can apply this hotspot safeguard once, centrally, ahead of whichever routing strategy a request actually resolves to — including "load-balance" itself, whose own Route() relies on the caller having already applied this gate rather than calling it again. Callers should skip invoking this for exclusive strategies (pd, slo*), which manage their own pod subsets and would have their role split disrupted by a blanket running-request-count filter applied ahead of time.

func GetPodModelMetricsSimplePrometheusValue added in v0.6.0

func GetPodModelMetricsSimplePrometheusValue(cache cache.Cache, podname, namespace, modelname, metricname string) float64

func GetPodModelMetricsSimpleValue added in v0.6.0

func GetPodModelMetricsSimpleValue(cache cache.Cache, podname, namespace, modelname, metricname string) float64

func HasEligibleRoleset added in v0.8.0

func HasEligibleRoleset(readyPods []*v1.Pod) bool

HasEligibleRoleset reports whether at least one PD roleset has both a prefill and decode pod ready for disaggregated routing.

func Init

func Init()

func Lookup added in v0.8.0

func Lookup(algorithm types.RoutingAlgorithm) (types.Router, error)

func NewExternalRouter added in v0.8.0

func NewExternalRouter() (types.Router, error)

func NewExternalRouterWithCache added in v0.8.0

func NewExternalRouterWithCache(metricCache cache.Cache) (types.Router, error)

func NewLeastBusyTimeRouter

func NewLeastBusyTimeRouter() (types.Router, error)

func NewLeastExpectedLatencyRouter

func NewLeastExpectedLatencyRouter() (types.Router, error)

func NewLeastGpuCacheRouter added in v0.4.0

func NewLeastGpuCacheRouter() (types.Router, error)

func NewLeastKvCacheRouter

func NewLeastKvCacheRouter() (types.Router, error)

func NewLeastKvCacheRouterWithCache added in v0.8.0

func NewLeastKvCacheRouterWithCache(c cache.Cache) (types.Router, error)

NewLeastKvCacheRouterWithCache constructs least-kv-cache with an explicit cache.

func NewLeastLatencyRouterWithCache added in v0.8.0

func NewLeastLatencyRouterWithCache(c cache.Cache) (types.Router, error)

NewLeastLatencyRouterWithCache constructs least-latency with an explicit cache.

func NewLeastLoadPullingRouter added in v0.4.0

func NewLeastLoadPullingRouter(provider cache.CappedLoadProvider) (types.Router, error)

NewLeastLoadRouter creates leastLoadRouter instance in the pull mode.

func NewLeastLoadRouter added in v0.4.0

func NewLeastLoadRouter(provider cache.LoadProvider) (types.Router, error)

NewLeastLoadRouter creates leastLoadRouter instance in the push mode.

func NewLeastRequestRouter

func NewLeastRequestRouter() (types.Router, error)

func NewLeastRequestRouterWithCache added in v0.8.0

func NewLeastRequestRouterWithCache(c cache.Cache) (types.Router, error)

NewLeastRequestRouterWithCache constructs least-request with an explicit cache.

func NewLeastRequestTopKRouter added in v0.8.0

func NewLeastRequestTopKRouter() (types.Router, error)

NewLeastRequestTopKRouter creates a LeastRequestTopKRouter backed by the global cache.

func NewLeastUtilRouter added in v0.4.0

func NewLeastUtilRouter() (types.Router, error)

func NewLoadBalanceRouter added in v0.8.0

func NewLoadBalanceRouter() (types.Router, error)

func NewLoadBalanceRouterWithCache added in v0.8.0

func NewLoadBalanceRouterWithCache(c cache.Cache) (types.Router, error)

NewLoadBalanceRouterWithCache constructs load-balance with an explicit cache.

func NewPDRouter added in v0.4.0

func NewPDRouter() (types.Router, error)

func NewPDRouterWithCacheAndPrefixIndexer added in v0.8.0

func NewPDRouterWithCacheAndPrefixIndexer(c cache.Cache, sharedPrefixTable *prefixcacheindexer.PrefixHashTable) (types.Router, error)

NewPDRouterWithCacheAndPrefixIndexer builds a PD router on an explicit cache and prefix table instead of the process-global ones, so an isolated RouterManager (see NewRouterManagerWithCacheAndPrefixIndexer) can route "pd" without initialising the global cache. A nil sharedPrefixTable gets a fresh table.

func NewPackLoadRouter added in v0.4.0

func NewPackLoadRouter(provider cache.CappedLoadProvider) (types.Router, error)

NewPackLoadRouter creates packLoadRouter instance.

func NewPowerOfTwoRouter added in v0.8.0

func NewPowerOfTwoRouter() (types.Router, error)

NewPowerOfTwoRouter creates a Power of Two router backed by the global cache.

func NewPrefixCacheAndLoadRouter

func NewPrefixCacheAndLoadRouter() (types.Router, error)

func NewPrefixCacheRouter

func NewPrefixCacheRouter() (types.Router, error)

func NewPrefixCacheRouterWithCache added in v0.8.0

func NewPrefixCacheRouterWithCache(c cache.Cache) (types.Router, error)

NewPrefixCacheRouterWithCache constructs the prefix-cache router with an explicit cache while preserving tokenizer and indexer behavior.

func NewPrefixCacheRouterWithOptions added in v0.8.0

func NewPrefixCacheRouterWithOptions(c cache.Cache, indexer *prefixcacheindexer.PrefixHashTable) (types.Router, error)

NewPrefixCacheRouterWithOptions constructs a prefix-cache router with an explicit cache and optional per-instance prefix table. A nil indexer creates a new private table; the production constructor passes the shared table explicitly.

func NewQueueRouter added in v0.4.0

func NewQueueRouter(backend types.Router, queue types.RouterQueue[*types.QueueEntry]) (types.QueueRouter, error)

func NewRandomRouter

func NewRandomRouter() (types.Router, error)

func NewSLORouter added in v0.4.0

func NewSLORouter(modelName string) (types.QueueRouter, error)

func NewSessionAffinityRouter added in v0.6.0

func NewSessionAffinityRouter() (types.Router, error)

func NewThroughputRouter

func NewThroughputRouter() (types.Router, error)

func Register

func Register(algorithm types.RoutingAlgorithm, constructor types.RouterConstructor)

func RegisterProvider added in v0.4.0

func RegisterProvider(algorithm types.RoutingAlgorithm, provider types.RouterProviderFunc)

func ResolveExclusiveStrategy added in v0.8.0

func ResolveExclusiveStrategy(algStr string) (string, bool)

ResolveExclusiveStrategy parses algStr and, if it resolves to a single exclusive strategy (pd, slo*), returns its name and true. algStr may itself already be a multi-strategy string that collapses to one exclusive item (e.g. "pd:1,least-request:1" resolves to "pd") — this lets callers detect exclusivity from the caller's raw, unparsed algorithm string rather than comparing it against the exclusive name directly.

func ResolveRoutingOverrides added in v0.8.0

func ResolveRoutingOverrides(routingCtx *types.RoutingContext)

ResolveRoutingOverrides turns this request's model config profile into its resolved routing overrides and parks them on the routing context, so every strategy and gate on the routing path reads the same values with a single resolve per request. It is a no-op when the profile sets no applicable knob: the read sites then read the process defaults directly.

func RouteByScore added in v0.8.0

func RouteByScore(ctx *types.RoutingContext, readyPodList types.PodList, scorer types.PodScorer) (*v1.Pod, error)

RouteByScore is the shared "least-X"/"most-X" routing pattern used by single-metric strategies (least-request, least-kv-cache, least-busy-time, least-gpu-cache, ...): it scores all ready pods via scorer.ScoreAll, picks the best one per scorer.Polarity() breaking ties randomly, and falls back to a uniformly random ready pod when nothing could be scored.

func Select

func Select(ctx *types.RoutingContext) (types.Router, error)

func SelectByScore added in v0.8.0

func SelectByScore(pods []*v1.Pod, scores []float64, scored []bool, polarity types.Polarity) *v1.Pod

SelectByScore returns the pod with the best score according to polarity (lowest for PolarityLeast, highest for PolarityMost), breaking ties uniformly at random. Pods with scored[i] == false are ignored. Returns nil if no pod could be scored.

best is seeded with +Inf/-Inf rather than the first scored value so a NaN score (e.g. a metric that hasn't warmed up) can never become "best": every comparison against NaN is false, so a pod that started as best could never be dethroned or matched by a real value.

func SelectRandomPodAsFallback

func SelectRandomPodAsFallback(ctx *types.RoutingContext, pods []*v1.Pod, randomFunc func(int) int) (*v1.Pod, error)

SelectRandomPodAsFallback selects a pod randomly as a fallback. This method should only be used when all other selection mechanisms have failed.

func SetFallback added in v0.4.0

func SetFallback(router types.Router, fallback types.RoutingAlgorithm) error

func Validate

func Validate(algorithms string) (types.RoutingAlgorithm, bool)

func ValidateAndGetLLMEngine added in v0.8.0

func ValidateAndGetLLMEngine(pods []*v1.Pod) (string, error)

ValidateAndGetLLMEngine validates that all pods use the same LLM engine label and returns it.

Types

type FallbackRouter added in v0.4.0

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

func (*FallbackRouter) Route added in v0.4.0

func (r *FallbackRouter) Route(ctx *types.RoutingContext, pods types.PodList) (string, error)

func (*FallbackRouter) SetFallback added in v0.4.0

func (r *FallbackRouter) SetFallback(fallback types.RoutingAlgorithm, provider types.RouterProviderFunc)

type LeastRequestTopKRouter added in v0.8.0

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

LeastRequestTopKRouter picks uniformly at random among the ready pods that are both among the K least-loaded and within leastRequestTopKEpsilon of the minimum, instead of always the minimum. Unlike power-of-two, every candidate comes from the least-loaded end of the fleet.

It is a types.Router (Route, as a standalone strategy) and a types.PodScorer (ScoreAll, for blending with other strategies).

func NewLeastRequestTopKRouterWithCache added in v0.8.0

func NewLeastRequestTopKRouterWithCache(c cache.Cache) *LeastRequestTopKRouter

NewLeastRequestTopKRouterWithCache creates a LeastRequestTopKRouter that reads load from the given cache.

func (*LeastRequestTopKRouter) Polarity added in v0.8.0

func (r *LeastRequestTopKRouter) Polarity() types.Polarity

Polarity implements types.PodScorer: fewer requests is better, as for least-request.

func (*LeastRequestTopKRouter) Route added in v0.8.0

func (r *LeastRequestTopKRouter) Route(ctx *types.RoutingContext, readyPodList types.PodList) (string, error)

Route implements types.Router: a uniform random pick among the eligible pods.

func (*LeastRequestTopKRouter) ScoreAll added in v0.8.0

func (r *LeastRequestTopKRouter) ScoreAll(ctx *types.RoutingContext, readyPodList types.PodList) ([]float64, []bool, error)

ScoreAll implements types.PodScorer so the strategy can be blended with others. The blend sums normalized scores deterministically and takes the argmax, so Route's random pick has no equivalent there: identical scores would let the other strategy's tie-break favor the same pod every time. Instead each eligible pod scores its count minus fresh random jitter in [0, epsilon), which can reorder the eligible cluster but never lift an ineligible pod above it. Ineligible pods keep their plain count.

func (*LeastRequestTopKRouter) SubscribedMetrics added in v0.8.0

func (r *LeastRequestTopKRouter) SubscribedMetrics() []string

SubscribedMetrics implements types.Router. It reads the live cross-gateway running-request count, not a scraped metric, so there is nothing to subscribe to.

type MultiRouterConfig added in v0.7.0

type MultiRouterConfig struct {
	Items []RouterItem
}

MultiRouterConfig holds the parsed routing algorithms and their weight coefficients.

func ParseMultiRouterConfig added in v0.7.0

func ParseMultiRouterConfig(routerStr string) (*MultiRouterConfig, error)

ParseMultiRouterConfig parses a multi-router string into a MultiRouterConfig. Format example: "prefix-cache:2,least-latency:1,least-request" - Weight coefficients must be integers in range [0, 1000000]. - Default weight coefficient is 1 if omitted. - Weight coefficient 0 means the routing algorithm should be skipped.

type PDRolesetEligibility added in v0.8.0

type PDRolesetEligibility struct {
	Roleset         string
	PrefillReplicas int
	DecodeReplicas  int
	PrefillPods     string
	DecodePods      string
	Eligible        bool
}

PDRolesetEligibility describes one roleset's readiness for PD routing.

func DescribePDRolesetEligibility added in v0.8.0

func DescribePDRolesetEligibility(readyPods []*v1.Pod) (fleetMaxPrefill, fleetMaxDecode int, statuses []PDRolesetEligibility, eligibleCount int)

DescribePDRolesetEligibility returns fleet-wide max replica counts (for diagnostics) and per-roleset eligibility (≥1 prefill and ≥1 decode).

type PowerOfTwoRouter added in v0.7.0

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

PowerOfTwoRouter implements the power of two choices algorithm: it samples two distinct ready pods at random and routes to the one with fewer running requests.

The router keeps no counters of its own. The running-request count of a pod is the one the cache maintains for every routed request (see Cache.GetPodsRunningRequests): the gateway increments it when a request is dispatched and decrements it when the request completes, whichever router chose the pod. When Redis is configured the count is aggregated across gateway replicas; otherwise it is this gateway's own count.

func NewPowerOfTwoRouterWithCache added in v0.8.0

func NewPowerOfTwoRouterWithCache(c cache.Cache) *PowerOfTwoRouter

NewPowerOfTwoRouterWithCache creates a Power of Two router that reads load from the given cache.

func (*PowerOfTwoRouter) Route added in v0.7.0

func (p *PowerOfTwoRouter) Route(ctx *types.RoutingContext, readyPodList types.PodList) (string, error)

Route implements types.Router using power of two choices algorithm. It randomly selects two pods and routes to the one with fewer running requests.

A data-parallel pod serves several ports, and the port is then chosen the way least-request chooses it: the one with the lowest per-port realtime running-requests metric. The cache keeps no true per-port count -- that metric slot holds the pod's total running requests as of the last request that started or finished on the port -- so this is only approximately load-aware. The choice of pod above does not depend on it.

func (*PowerOfTwoRouter) SubscribedMetrics added in v0.7.0

func (p *PowerOfTwoRouter) SubscribedMetrics() []string

SubscribedMetrics implements types.Router.

type PrefillTimeParams

type PrefillTimeParams struct {
	NumRequests      int
	NumBatchedTokens int
	TotalContext     int
	InputIDLens      []int
	NumUniqueKV      int
	SeqLens          []int
}

type PrefixCacheMetrics added in v0.4.0

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

PrefixCacheMetrics holds all prefix cache metrics

type RedisBackedRouter added in v0.8.0

type RedisBackedRouter interface {
	Start(stopCh <-chan struct{}, redisClient *redis.Client)
}

RedisBackedRouter is implemented by routers that persist routing state to Redis and need a background sync loop started once both Redis and a process shutdown signal are available -- typically later than the router itself is constructed (see RouterManager.Init). The gateway server type- asserts to this interface after building its own shutdown channel.

type RouterItem added in v0.7.0

type RouterItem struct {
	Name        string
	Coefficient int // Integer weight coefficient (0 to 1000000)
}

RouterItem represents a single routing algorithm and its weight coefficient for multi-router config.

type RouterManager added in v0.4.0

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

func DefaultRouterManager added in v0.8.0

func DefaultRouterManager() *RouterManager

DefaultRouterManager returns the production process-wide router manager.

func NewRouterManager added in v0.4.0

func NewRouterManager() *RouterManager

func NewRouterManagerWithCache added in v0.8.0

func NewRouterManagerWithCache(c cache.Cache) *RouterManager

NewRouterManagerWithCache creates an isolated manager whose cache-backed constructors capture c instead of consulting the process-global cache.

func NewRouterManagerWithCacheAndPrefixIndexer added in v0.8.0

func NewRouterManagerWithCacheAndPrefixIndexer(c cache.Cache, indexer *prefixcacheindexer.PrefixHashTable) *RouterManager

NewRouterManagerWithCacheAndPrefixIndexer creates an isolated manager whose cache-backed constructors capture c and whose prefix-cache constructor uses indexer when it is non-nil. A nil indexer preserves the default per-manager prefix table behavior.

func NewRouterManagerWithDefaults added in v0.8.0

func NewRouterManagerWithDefaults() *RouterManager

NewRouterManagerWithDefaults creates an isolated manager with the standard Gateway routing constructors. Unlike Init, it does not mutate the process global manager.

func (*RouterManager) Init added in v0.4.0

func (rm *RouterManager) Init()

func (*RouterManager) InitializationError added in v0.8.0

func (rm *RouterManager) InitializationError(algorithm types.RoutingAlgorithm) error

InitializationError reports the most recent constructor failure for a strategy. Disabled optional routers may use a sentinel error that callers explicitly ignore; invalid enabled configuration remains fail-fast.

func (*RouterManager) Lookup added in v0.8.0

func (rm *RouterManager) Lookup(algorithm types.RoutingAlgorithm) (types.Router, error)

Lookup returns algorithm's constructed singleton router, as registered via Register/RegisterProvider and built by Init. It exists for callers (like the gateway server) that need the concrete instance directly -- for example to start a router's own background maintenance loop -- rather than going through Select's per-request algorithm resolution and blending. The probe context mirrors Validate's: providers built via Register ignore it entirely, since they already constructed their singleton at Init time, but it's supplied anyway so a ctx-dependent provider (e.g. SLO's) never sees a nil pointer.

func (*RouterManager) Register added in v0.4.0

func (rm *RouterManager) Register(algorithm types.RoutingAlgorithm, constructor types.RouterConstructor)

func (*RouterManager) RegisterProvider added in v0.4.0

func (rm *RouterManager) RegisterProvider(algorithm types.RoutingAlgorithm, provider types.RouterProviderFunc)

func (*RouterManager) Select added in v0.4.0

func (rm *RouterManager) Select(ctx *types.RoutingContext) (types.Router, error)

Select the user provided router provider supported by gateway, no error reported and fallback to random router Call Validate before this function to ensure expected behavior.

func (*RouterManager) SetFallback added in v0.4.0

func (rm *RouterManager) SetFallback(router types.Router, fallback types.RoutingAlgorithm) error

func (*RouterManager) Validate added in v0.4.0

func (rm *RouterManager) Validate(algorithms string) (types.RoutingAlgorithm, bool)

Validate validates if user provided routing routers is supported by gateway

type SLORouter added in v0.4.0

type SLORouter struct {
	FallbackRouter
	*queue.SLOQueue
}

SLORouter is a router that add FallbackRouter mechanism to the queue.

func (*SLORouter) Route added in v0.4.0

func (r *SLORouter) Route(ctx *types.RoutingContext, pods types.PodList) (string, error)

type Scores added in v0.5.0

type Scores struct {
	Pod   *v1.Pod
	Score float64
}

type SlidingWindowHistogram

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

type TokenizerPool added in v0.4.0

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

TokenizerPool manages model-specific tokenizers with caching and health checking

func NewTokenizerPool added in v0.4.0

func NewTokenizerPool(config TokenizerPoolConfig, cache cache.Cache) *TokenizerPool

NewTokenizerPool creates a new TokenizerPool instance

func (*TokenizerPool) Close added in v0.4.0

func (p *TokenizerPool) Close() error

Close gracefully shuts down the TokenizerPool

func (*TokenizerPool) GetTokenizer added in v0.4.0

func (p *TokenizerPool) GetTokenizer(model string, pods []*v1.Pod) tokenizer.Tokenizer

GetTokenizer returns a tokenizer for the specified model

type TokenizerPoolConfig added in v0.4.0

type TokenizerPoolConfig struct {
	EnableVLLMRemote     bool                // Feature flag
	EndpointTemplate     string              // "http://%s:8000"
	HealthCheckPeriod    time.Duration       // Default: 30s
	TokenizerTTL         time.Duration       // Default: 5m
	MaxTokenizersPerPool int                 // Default: 100
	DefaultTokenizer     tokenizer.Tokenizer // Default when remote fails
	ModelServiceMap      map[string]string   // Model -> Service endpoint mapping
	Timeout              time.Duration       // Request timeout
}

TokenizerPoolConfig represents configuration for the TokenizerPool

type TokenizerPoolInterface added in v0.4.0

type TokenizerPoolInterface interface {
	GetTokenizer(model string, pods []*v1.Pod) tokenizer.Tokenizer
	Close() error
}

TokenizerPoolInterface defines the interface for tokenizer pools

type TokenizerPoolMetrics added in v0.4.0

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

TokenizerPoolMetrics contains Prometheus metrics for the pool

Directories

Path Synopsis
Package external implements the optional HTTP-based replica-selection strategy.
Package external implements the optional HTTP-based replica-selection strategy.
pd
Package pd contains the scoring types used by the PD (prefill-decode) disaggregated-inference router.
Package pd contains the scoring types used by the PD (prefill-decode) disaggregated-inference router.
selector
Package selector defines the PodSelector contract for PD-disaggregated routing.
Package selector defines the PodSelector contract for PD-disaggregated routing.
Package vtc implements the Virtual Token Counter routing algorithms focused on fairness and utilization
Package vtc implements the Virtual Token Counter routing algorithms focused on fairness and utilization

Jump to

Keyboard shortcuts

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