pd

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: 25 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 pd contains the scoring types used by the PD (prefill-decode) disaggregated-inference router. The scoring logic is split across three files:

  • prefill_scorer.go — PrefillScorePolicy / PrefillScorer interfaces and their built-in implementations (prefix_cache, least_request, conductor, token_load, hybrid_cache_load).
  • decode_scorer.go — DecodeScorePolicy / DecodeScorer interfaces and their built-in implementations (load_balancing, least_request), plus the policy registry used by AIBRIX_DECODE_SCORE_POLICY.
  • trackers.go — PrefillRequestTracker and PendingDecodeTracker, which bridge the gap between pod selection and actual request start.
  • token_load_tracker.go — TokenLoadTracker, the token-weighted prefill load ledger behind the token_load and hybrid_cache_load policies.
  • bucket_serving.go — BucketServeTracker, the gateway half of a BucketServe-style bucketer: prompt-length bands, adapted to the observed traffic, that the prefill path uses to prefer one roleset per band.

Index

Constants

View Source
const (
	// PrefillFailureRequestSetup: the HTTP request could not even be built
	// (bad URL, nil body). The prefill pod was never contacted.
	PrefillFailureRequestSetup = "request_setup"
	// PrefillFailureTimeout: AIBRIX_PREFILL_REQUEST_TIMEOUT elapsed, or the
	// transport reported a timeout. The prefill may be in any state; the
	// gateway can no longer observe it.
	PrefillFailureTimeout = "timeout"
	// PrefillFailureCanceled: the request context was cancelled, i.e. the
	// client went away or the gateway is shutting down.
	PrefillFailureCanceled = "canceled"
	// PrefillFailureTransport: connection refused/reset, DNS, EOF - the
	// prefill pod did not answer.
	PrefillFailureTransport = "transport"
	// PrefillFailureHTTPStatus: the prefill pod answered with a non-200. This
	// is the OOM / crashed-scheduler / bootstrap-timeout case.
	PrefillFailureHTTPStatus = "http_status"
	// PrefillFailureBadResponse: HTTP 200 with a body the gateway cannot
	// parse. For SGLang this means the KV transfer itself completed, so it does
	// NOT abort the decode leg; for an out-of-band handshake (TRT-LLM
	// generation-first) it is treated as terminal instead (see
	// PrefillFailureIsTerminalFor).
	PrefillFailureBadResponse = "bad_response"
)

Prefill failure classes. Low cardinality: they are used as a log field and as a metric label, and the gateway maps them to a client-facing error.

View Source
const (
	ScorePolicyLoadBalancing = string(DecodePolicyLoadBalancing)
	ScorePolicyLeastRequest  = string(DecodePolicyLeastRequest)
	ScorePolicyConductor     = string(DecodePolicyConductor)
	ScorePolicyTokenLoad     = string(DecodePolicyTokenLoad)
)
View Source
const (
	DefaultGPUCachePressureThreshold = 0.9
	DefaultGPUCachePressurePenalty   = 1.5
	DefaultDecodeTBTFallbackMs       = 20.0
)

Default values for ConductorDecodePolicy.

View Source
const (
	// AbortTriggerWatchdogFirstResponse: the decode pod sent no response body
	// after the prefill leg succeeded, whether or not it sent headers
	// (AIBRIX_DECODE_FIRST_RESPONSE_TIMEOUT, or AIBRIX_DECODE_RESPONSE_TIMEOUT
	// for a non-streaming request).
	AbortTriggerWatchdogFirstResponse = "watchdog_first_response"

	// AbortTriggerWatchdogStreamIdle: the decode pod started streaming tokens
	// and then went silent for AIBRIX_DECODE_STREAM_IDLE_TIMEOUT.
	AbortTriggerWatchdogStreamIdle = "watchdog_stream_idle"
)

Abort triggers that are not prefill failures. They travel in the same slot as a prefill failure class - the prefill_failure_class log field and metric label of gateway_pd_decode_abort_total - because a counter's label set is fixed at registration and that counter predates the watchdog.

View Source
const (
	// PrefillScorePolicyPrefixCache selects the prefix-cache scoring policy,
	// which routes prefill requests to pods that already hold matching KV-cache
	// blocks, weighted by the pod's current running-request count.
	PrefillScorePolicyPrefixCache = "prefix_cache"

	// PrefillScorePolicyLeastRequest selects the least-request scoring policy,
	// which routes prefill requests purely by the lowest running-request count
	// without consulting the prefix cache.
	PrefillScorePolicyLeastRequest = "least_request"

	// PrefillScorePolicyConductor selects the conductor scoring policy, which
	// estimates the TTFT (contains queue, prefix, and prefill) for each pod
	PrefillScorePolicyConductor = "conductor"

	// PrefillScorePolicyTokenLoad selects the token-load scoring policy, which
	// routes prefill requests to the pod with the lowest token-weighted load
	// as tracked by TokenLoadTracker, without consulting the prefix cache.
	PrefillScorePolicyTokenLoad = "token_load"

	// PrefillScorePolicyHybridCacheLoad selects the hybrid scoring policy,
	// which discounts a pod's token-weighted load by its prefix-cache match so
	// that cache affinity wins on idle pods and load wins on busy ones.
	PrefillScorePolicyHybridCacheLoad = "hybrid_cache_load"

	// DefaultHybridCacheLoadFactor is how much a full prefix match discounts a
	// pod's token load under hybrid_cache_load: score = load × (1 − factor)
	// at 100 % match.
	DefaultHybridCacheLoadFactor = 0.5

	// DefaultMinMatchPct is the prefix-match percentage below which
	// prefix_cache and hybrid_cache_load treat a match as no match. 0 keeps
	// every match.
	DefaultMinMatchPct = 0.0

	// Default TTFT estimation coefficients for conductor policy.
	// Units: time in milliseconds, tokens are unitless.
	//
	// Prefix time model: T = PrefixTimeCoeffA * tokens + PrefixTimeCoeffB
	DefaultPrefixTimeCoeffA = 0.005
	DefaultPrefixTimeCoeffB = 1.0
	// Prefill time model: T = PrefillTimeCoeffA * tokens^PrefillTimeCoeffB + PrefillTimeCoeffC
	DefaultPrefillTimeCoeffA = 0.001
	DefaultPrefillTimeCoeffB = 1.5
	DefaultPrefillTimeCoeffC = 5.0
)
View Source
const (
	// DefaultTokenLoadKVWeight is the default weight of resident KV tokens in
	// the token-load priority. A prefill pod keeps a request's KV blocks until
	// the decoder has pulled them, so resident KV still costs the pod something
	// after the prefill call itself has returned, but less than active compute.
	DefaultTokenLoadKVWeight = 0.3

	// DefaultTokenLoadRequestCost is the default fixed per-request cost in
	// tokens. It models scheduling and KV-transfer setup work that does not
	// scale with prompt length and keeps very short prompts from looking free.
	DefaultTokenLoadRequestCost = 3500

	// DefaultTokenLoadTTLSeconds bounds how long a charge may stay outstanding
	// before the janitor force-releases it. It must exceed the longest
	// legitimate request; an hour leaves a wide margin while still capping the
	// damage a leaked entry can do. The environment variable must be positive;
	// a TTL of 0 in TokenLoadConfig disables the sweep of stale charges.
	DefaultTokenLoadTTLSeconds = 3600

	// DefaultTokenLoadSessionTTLSeconds bounds how long the last prompt size
	// of a session is remembered for the session-delta cost estimate. It only
	// needs to outlive the gap between two turns of one conversation.
	DefaultTokenLoadSessionTTLSeconds = 1800

	// DefaultTokenLoadMaxSessions bounds how many (model, session) baselines
	// the tracker remembers at once. The session header is client-supplied,
	// so without a bound a stream of distinct IDs could grow the table by
	// QPS × SessionTTL entries before the janitor sweeps them. Once the
	// table is full, new sessions are not recorded and their requests are
	// charged by the prefix-match or whole-prompt rule instead.
	DefaultTokenLoadMaxSessions = 100000
)
View Source
const (
	NewTokensSourceSession     = "session_delta"
	NewTokensSourcePrefixMatch = "prefix_match"
	NewTokensSourcePrompt      = "prompt"
)

Sources of the NewTokens estimate, for logs.

View Source
const EngineTRTLLM = "trtllm"

EngineTRTLLM is the TensorRT-LLM engine identifier. It is defined here so that packages below routingalgorithms (prefill, engine) can special-case TRT-LLM without importing routingalgorithms (circular).

Variables

View Source
var CommonControlledFields = []string{
	"max_tokens",
	"max_completion_tokens",
	"stream",
	"stream_options",
	"min_tokens",
}

CommonControlledFields lists the top-level keys ApplyPrefillControlFields sets or deletes on every engine's prefill body. Engine handlers and KV transfer agents add their own keys on top (see ControlledFields).

Functions

func AbortDecodeLegOnWatchdog added in v0.8.0

func AbortDecodeLegOnWatchdog(client *http.Client, leg *types.PDLegState, requestID, model, trigger string)

AbortDecodeLegOnWatchdog sends a single best-effort /abort_request for the leg's rid to its decode pod, logged and counted like an abort fired by a prefill failure, with trigger in place of the failure class.

It is the decode watchdog's abort: the watchdog has decided the decode pod stopped answering and is failing the client, and this tells the pod to drop the request instead of generating for a client that is gone. It never blocks: the POST runs in its own goroutine, bounded by the request's AIBRIX_DECODE_ABORT_TIMEOUT, and nothing branches on its outcome. The goroutine is joinable through leg.AbortDone().

One attempt, unlike OnPrefillLegFailed's two. That retry covers an abort overtaking its own decode request on the pod, which cannot happen here: the watchdog only fires after the decode request has been on the pod for at least the configured timeout (and, for a stream-idle kill, after the pod has already answered).

The prefill-failure abort and this one never share a leg: the watchdog is armed by the prefill leg succeeding, the other by it failing, so the leg's abort lifecycle (AbortContext, AbortDone) belongs to whichever ran.

func ApplyPrefillControlFields added in v0.8.0

func ApplyPrefillControlFields(body []byte, llmEngine string) ([]byte, error)

ApplyPrefillControlFields overrides the generation control fields so the prefill pod returns right after filling the KV cache:

  • max_tokens=1 and max_completion_tokens=1 (TRT-LLM only supports max_tokens, so max_completion_tokens is removed instead)
  • stream=false, stream_options and min_tokens removed

Only top-level keys are touched; every other byte of body is preserved.

func ClampMinMatch added in v0.8.0

func ClampMinMatch(matchPct int, minPct float64) int

ClampMinMatch returns matchPct, or 0 when a positive minPct is set and matchPct falls below it.

func EnvOverrides added in v0.8.0

func EnvOverrides() types.PDOverrides

EnvOverrides returns the PD routing knob defaults the environment configures: the decode abort timings, the decode watchdog timeouts, the decode load-balancing weights, the token-load ledger knobs, the hybrid prefix-cache thresholds and the bucket-serve switch and mode. The routing algorithm package folds them into the process default table at startup, and this package's tests install them the same way.

AIBRIX_TOKEN_LOAD_MAX_SESSIONS has no counterpart here on purpose: it caps the shared session table of the token-load tracker, which every model of a gateway process shares, so it is not a per-request knob.

func EstimatePromptTokens added in v0.8.0

func EstimatePromptTokens(reqBody []byte) int

EstimatePromptTokens estimates the prompt length of a request from its body size when no token count is available.

func FindDuplicateTopLevelKey added in v0.8.0

func FindDuplicateTopLevelKey(body []byte, controlledFields []string) (string, bool)

FindDuplicateTopLevelKey scans the root object of body once and returns the first entry of controlledFields (in slice order) that occurs more than once at the top level, or "" and false when there is none. body must already be a valid JSON object (see ValidateJSONObject).

sjson edits only the first occurrence of a key, so a duplicated controlled key would let the client's second value survive and override whatever the gateway wrote; callers reject such bodies instead.

func InvalidDecodeScore

func InvalidDecodeScore(s float64) bool

InvalidDecodeScore reports whether score s cannot be used for routing. Only NaN is treated as invalid; +Inf is allowed so that a pod with zero free GPU headroom (causing division by zero in load_balancing) is routed last rather than skipped, preserving historical behaviour.

func OnPrefillLegFailed added in v0.8.0

func OnPrefillLegFailed(client *http.Client, leg *types.PDLegState, requestID, model string, err error) *types.PrefillFailure

OnPrefillLegFailed records a terminal prefill failure on the PD leg state and, unless the decode leg is already answering the client, fires a best-effort /abort_request at the decode pod.

Everything it needs is passed in by value or as the per-incarnation *types.PDLegState, never as the RoutingContext: its caller is the async prefill goroutine, which can still be running long after the client stream released the (pooled) routing context. Reading or writing that object here would mean acting on whatever request has since been handed it - closing the wrong wakeup channel and aborting the wrong rid.

It never blocks: the abort POST runs in its own goroutine, on the leg's abort context (the request context is typically already cancelled or about to be) with its own AIBRIX_DECODE_ABORT_TIMEOUT budget per attempt. Nothing downstream waits for, or branches on, the abort result - but the goroutine is joinable through leg.AbortDone(), because it still emits a log line and a metric sample after everything else about the request is over.

The recorded types.PrefillFailure is what the gateway consumes to tell the client that the request died; it is set here, on the same path that already logs prefill_request_failed, so every prefill failure has it regardless of whether an abort was sent.

func PrefillFailureIsTerminal added in v0.8.0

func PrefillFailureIsTerminal(class string) bool

PrefillFailureIsTerminal reports whether a prefill failure of this class means the client request itself can never be served, and not merely that the gateway lost sight of an otherwise healthy prefill.

It is the same predicate that decides whether to abort the decode leg, and deliberately so: the decode leg is aborted exactly when the KV cache will never arrive, which is exactly when the client must be told the request failed instead of being left to wait out the bootstrap timeout.

Everything except PrefillFailureBadResponse qualifies: for engines whose KV handshake completes inside the prefill HTTP body (SGLang), a 200 with an unparseable body still means the KV transfer completed, and aborting then would kill a healthy request. Engines whose KV transfer is out of band use PrefillFailureIsTerminalFor instead.

func PrefillFailureIsTerminalFor added in v0.8.0

func PrefillFailureIsTerminalFor(class string, resetAfterHeaders bool) bool

PrefillFailureIsTerminalFor is PrefillFailureIsTerminal under an engine's async dispatch policy. resetAfterHeaders is true for engines whose decode leg can answer before the KV cache arrives (TRT-LLM generation-first).

For those engines PrefillFailureBadResponse is terminal too: KV moves over the transceiver, not in the context HTTP body, so a 200 the gateway cannot parse leaves it unable to tell whether context processing succeeded while generation keeps waiting for KV it may never get.

func PrefixMatchPercent added in v0.8.0

func PrefixMatchPercent(scorer PrefillScorer, podKey string) int

PrefixMatchPercent returns the prefix-match percentage scorer reports for podKey, or -1 when scorer does not implement PrefixMatchScorer.

func RecordPrefillFailure added in v0.8.0

func RecordPrefillFailure(leg *types.PDLegState, err error) *types.PrefillFailure

RecordPrefillFailure classifies err and records it on the PD leg state as the terminal failure of the prefill leg. The first failure wins; the returned value always describes the error passed in, so callers can log the class of the failure they just observed.

It takes the leg rather than the RoutingContext on purpose: the async prefill goroutine can outlive the client stream, and the RoutingContext is pooled, so recording through the context risks recording onto an unrelated request (see types.PDLegState). Request-path callers pass routingCtx.PDLeg().

This is the state the gateway consumes: it is what turns "the prefill goroutine logged an error somewhere" into something the goroutine owning the client stream can act on.

func RegisterDecodePolicy

func RegisterDecodePolicy(name string, factory func() DecodeScorePolicy)

RegisterDecodePolicy registers a custom decode scoring policy factory under name (case-insensitive, trimmed). Calling this with a name that already exists replaces the previous factory. Nil factories are rejected with a warning. Must be called before ResolveDecodePolicy is invoked for the same name; safe for concurrent use.

func ResolveDecodePolicy

func ResolveDecodePolicy(raw string) (policy DecodeScorePolicy, canonical DecodePolicyName, unknown bool)

ResolveDecodePolicy resolves raw (e.g. from AIBRIX_DECODE_SCORE_POLICY) to a DecodeScorePolicy. It checks the custom registry first, then the built-in factory map, both after lower-casing and trimming raw. An empty raw string resolves to load_balancing. Returns unknown=true when raw is not recognised, in which case policy is load_balancing and canonical is DecodePolicyLoadBalancing.

func UsesDecodeTokenLoad added in v0.8.0

func UsesDecodeTokenLoad(policy DecodeScorePolicy) bool

UsesDecodeTokenLoad reports whether policy scores from the decode ledger, so the router must charge the ledger when it selects a decode pod.

func UsesTokenLoad added in v0.8.0

func UsesTokenLoad(policy PrefillScorePolicy) bool

UsesTokenLoad reports whether policy scores from a TokenLoadTracker, i.e. whether the router must charge the tracker for requests scored by it.

func ValidDecodePolicyNames

func ValidDecodePolicyNames() []string

ValidDecodePolicyNames returns the sorted list of all recognised decode policy names, including both built-in and dynamically registered custom ones. Used in log/error messages to guide operators toward valid values.

func ValidateJSONObject added in v0.8.0

func ValidateJSONObject(body []byte, what string) error

ValidateJSONObject rejects bodies that are not syntactically valid JSON or whose top-level value is not an object, so the sjson edits applied afterwards are well-defined. gjson.ValidBytes alone accepts arrays/scalars and gjson.ParseBytes on malformed input yields Null without an error, hence both checks. what names the body in the error message.

Types

type BandResult added in v0.8.0

type BandResult struct {
	// Roleset is the roleset the plan prefers for the request. Empty when the
	// plan has no opinion: no band covers the length, or no roleset needs
	// traffic there.
	Roleset string

	// Max is the upper prompt-length bound of the band that covers the
	// request. It is meaningful only when Roleset is non-empty.
	Max int

	// Plan is the recomputed plan, sorted by Min, shared with the tracker and
	// must not be modified. It is set only when Refreshed is true.
	Plan []BucketBand

	// Dropped lists the rolesets that left every live plan on this refresh,
	// in name order: they were named before, and neither the new plan nor a
	// cached plan still inside its refresh interval holds a band for them now,
	// so a caller can delete their gauge series. It is set only when
	// Refreshed is true.
	Dropped []string

	// Refreshed reports whether this call recomputed the plan rather than
	// serving the cached one.
	Refreshed bool
}

BandResult reports what one Band call observed: the roleset the plan prefers for the request's prompt length, the upper bound of that band, and the plan itself when the call recomputed it.

type BucketBand added in v0.8.0

type BucketBand struct {
	Min, Max int
	Group    string
}

BucketBand is one routing unit of a plan: prompts in [Min, Max] prefer the band's roleset. A plan carries no band for a length interval no roleset needs, and there the routing path keeps every covering roleset a candidate.

type BucketGroup added in v0.8.0

type BucketGroup struct {
	Name     string
	Min, Max int
	Replicas int
}

BucketGroup is one roleset that can serve a prompt-length range, in inclusive token bounds. Replicas is the roleset's prefill replica count, which is how much of the model's traffic the roleset should carry.

type BucketMode added in v0.8.0

type BucketMode string

BucketMode selects what the adaptive cut points balance.

const (
	// BucketModeRPS splits shared ranges at request-count quantiles, so the
	// traffic a roleset is banded tracks the replica share it still needs,
	// counted in requests. It is the mode for latency-sensitive,
	// request-bound deployments.
	BucketModeRPS BucketMode = "rps"

	// BucketModeThroughput splits shared ranges at prompt-token quantiles,
	// so the traffic a roleset is banded tracks the replica share it still
	// needs, counted in prompt tokens. It is the mode for throughput-bound
	// deployments, where padding cost and GPU time track tokens rather than
	// request counts.
	BucketModeThroughput BucketMode = "throughput"
)

func EnvBucketServe added in v0.8.0

func EnvBucketServe() (bool, BucketMode)

EnvBucketServe returns the bucket-serve knobs the environment selects: AIBRIX_BUCKET_SERVE turns the adaptive plan on and AIBRIX_BUCKET_SERVE_MODE picks what its cut points balance. A config profile may then switch the plan, or select another mode, for the models it routes. An unknown mode name is refused with a warning and the default stays in place, the way the other environment loaders treat a value they would not accept.

func ParseBucketMode added in v0.8.0

func ParseBucketMode(name string) (BucketMode, bool)

ParseBucketMode parses a bucket-serve mode name. An unknown name returns ok=false and the caller keeps its current value.

type BucketServeTracker added in v0.8.0

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

BucketServeTracker is the per-process bucket-serving state of every model this gateway has routed. The zero value is not usable; build one with NewBucketServeTracker.

func NewBucketServeTracker added in v0.8.0

func NewBucketServeTracker() *BucketServeTracker

NewBucketServeTracker builds an empty tracker.

func (*BucketServeTracker) Band added in v0.8.0

func (t *BucketServeTracker) Band(model string, mode BucketMode, length int, now time.Time, groups []BucketGroup) BandResult

Band records one routed request and returns the roleset the adaptive plan prefers for its prompt length. It is the request-path entry point: the call decays the model's traffic picture, records the request, recomputes the plan when the cached one is stale or the mode or roleset set changed, and reports the band that covers the length. Calls asking for different modes or fleet shapes keep their own cached plans. It is a no-op on a nil tracker, an empty model and a non-positive length.

type ConductorDecodePolicy added in v0.8.0

type ConductorDecodePolicy struct{}

ConductorDecodePolicy scores decode pods by estimated TBT after adding the request, with a GPU-cache pressure penalty.

estimated_TBT = current_TBT * (1 + 1 / max(running_reqs, 1))
if gpu_cache_usage > threshold: estimated_TBT *= penalty

Lower score is better.

func (ConductorDecodePolicy) Describe added in v0.8.0

func (ConductorDecodePolicy) Describe() string

func (ConductorDecodePolicy) Name added in v0.8.0

func (ConductorDecodePolicy) ScoreDecodePod added in v0.8.0

func (ConductorDecodePolicy) ScoreDecodePod(routingCtx *types.RoutingContext, pod *v1.Pod, in DecodePodInput) float64

type ConductorPrefillPolicyConfig added in v0.8.0

type ConductorPrefillPolicyConfig struct {
	// PrefixTimeCoeffA is the linear coefficient for prefix time estimation.
	// Prefix time model: T = PrefixTimeCoeffA * tokens + PrefixTimeCoeffB
	PrefixTimeCoeffA float64
	// PrefixTimeCoeffB is the constant offset for prefix time estimation.
	PrefixTimeCoeffB float64
	// PrefillTimeCoeffA is the scaling coefficient for prefill time estimation.
	// Prefill time model: T = PrefillTimeCoeffA * tokens^PrefillTimeCoeffB + PrefillTimeCoeffC
	PrefillTimeCoeffA float64
	// PrefillTimeCoeffB is the exponent for prefill time estimation (accounts for attention complexity).
	PrefillTimeCoeffB float64
	// PrefillTimeCoeffC is the constant offset for prefill time estimation.
	PrefillTimeCoeffC float64
}

ConductorPrefillPolicyConfig contains TTFT estimation coefficients for the conductor policy. These coefficients are used to model the time taken for prefix processing and prefill computation.

func NewConductorPrefillPolicyConfig added in v0.8.0

func NewConductorPrefillPolicyConfig() ConductorPrefillPolicyConfig

NewConductorPrefillPolicyConfig returns a config with default coefficients. different GPU device may have different default coefficients A possible solution: add 'device' arg to ConductorPrefillPolicyConfig. like ConductorPrefillPolicyConfig("default"), ConductorPrefillPolicyConfig("a100")

now only support default config. arg not applied.

type DecodePodInput

type DecodePodInput struct {
	RunningReqs     float64 // active decode requests on this pod (incl. pending)
	Throughput      float64 // AvgGenerationThroughputToksPerS for the model
	FreeGPUPercent  float64 // 100 - KVCacheUsagePerc*100, floored at 0.1
	MaxRequestCount float64 // max RunningReqs across the candidate decode pods
	MaxThroughput   float64 // max Throughput across the candidate decode pods
	MaxFreeGPUUsage float64 // max FreeGPUPercent across the candidate decode pods
	DecodeTokens    float64 // decode ledger of this pod (token_load): charged prompt tokens plus estimated generated output
}

DecodePodInput bundles the per-pod metrics and per-batch maxima needed for one decode scoring pass. Maxima are enforced to be positive by the PD router (typically floored at 1.0) so that normalisation denominators are never zero.

type DecodePolicyName

type DecodePolicyName string
const (
	// DecodePolicyLoadBalancing routes to the pod with the best balance of
	// running-request count, generation throughput, and free GPU headroom.
	DecodePolicyLoadBalancing DecodePolicyName = "load_balancing"

	// DecodePolicyLeastRequest routes to the pod with the fewest active decode
	// requests (including pending requests not yet reflected in metrics).
	DecodePolicyLeastRequest DecodePolicyName = "least_request"

	// DecodePolicyConductor routes to the pod with the lowest estimated TBT
	// (time between tokens) after adding the request, accounting for GPU-cache
	// pressure. Uses throughput-derived TBT, sublinear batch-size scaling, and
	// a penalty for pods above the GPU-cache utilization threshold.
	DecodePolicyConductor DecodePolicyName = "conductor"

	// DecodePolicyTokenLoad routes to the pod with the fewest prompt tokens
	// charged to it by the gateway's decode ledger (TokenLoadTracker): the
	// requests routed to it that have not completed, weighted by prompt size.
	DecodePolicyTokenLoad DecodePolicyName = "token_load"
)

type DecodeScorePolicy

type DecodeScorePolicy interface {
	// Name returns the canonical policy identifier used in log lines and metrics.
	Name() DecodePolicyName
	// Describe returns a short human-readable summary for observability (e.g. startup logs).
	Describe() string
	// ScoreDecodePod returns a score for one decode pod; lower is better.
	ScoreDecodePod(routingCtx *types.RoutingContext, pod *v1.Pod, in DecodePodInput) float64
}

DecodeScorePolicy is the stateless scoring strategy for decode pod selection. Implementations are selected via AIBRIX_DECODE_SCORE_POLICY or registered dynamically with RegisterDecodePolicy.

To add a new decode scoring strategy: implement this interface and call RegisterDecodePolicy before NewPDRouter is invoked.

type DecodeScoreRun

type DecodeScoreRun struct {
	PerRoleset   map[string]RolesetDecodePick
	MaxScore     float64
	Err          error
	FallbackUsed bool
	Policy       DecodePolicyName
}

DecodeScoreRun is the outcome of a single call to scoreDecodePods.

  • PerRoleset empty with Err == nil: no decode pod produced a usable score (e.g. the input list was empty or every score was NaN after fallback).
  • Err non-nil: the pass failed in a way the router should surface to the caller.
  • FallbackUsed true: at least one pod's primary-policy score was invalid (NaN) and was replaced by load_balancing for that pod.
  • MaxScore is the largest raw score produced in the pass, used by finalPDScore to normalise decode scores before combining them with prefill scores.

type HybridCacheLoadConfig added in v0.8.0

type HybridCacheLoadConfig struct {
	// Factor is the discount a full prefix match applies to a pod's token
	// load; see hybridCacheLoadPrefillPolicy for the formula.
	Factor float64
	// MinMatchPct is the prefix-match percentage below which a match is
	// treated as no match, so a few shared tokens do not attract a request.
	MinMatchPct float64
}

HybridCacheLoadConfig tunes the hybrid_cache_load policy.

func DefaultHybridCacheLoadConfig added in v0.8.0

func DefaultHybridCacheLoadConfig() HybridCacheLoadConfig

DefaultHybridCacheLoadConfig returns the defaults, overridden by the AIBRIX_HYBRID_CACHE_LOAD_FACTOR (0 to 1) and AIBRIX_MIN_MATCH_PCT (0 to 100) environment variables. An unset, empty or out-of-range value keeps the default. A factor of 1 makes a full match score 0, so it always wins; above 1 the discount would go negative, which is why the range stops there.

type JSONEditor added in v0.8.0

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

JSONEditor chains sjson operations on a JSON body and records the first error. sjson.SetBytes / DeleteBytes return new slices, so the body passed to NewJSONEditor is never mutated.

PD request/response mutation must go through byte-level edits like these instead of a map[string]any round trip: sonic re-serialises nested objects (messages, tools, tool parameter schemas) in random key order, which makes prompt_token_ids unstable across requests and between the prefill and decode bodies of the same request, defeating KV-cache prefix reuse.

func NewJSONEditor added in v0.8.0

func NewJSONEditor(body []byte) *JSONEditor

NewJSONEditor starts an edit chain on body.

func (*JSONEditor) Delete added in v0.8.0

func (e *JSONEditor) Delete(path string) *JSONEditor

Delete removes path; deleting a missing path is a no-op.

func (*JSONEditor) Result added in v0.8.0

func (e *JSONEditor) Result() ([]byte, error)

Result returns the edited body, or nil and the first recorded error.

func (*JSONEditor) Set added in v0.8.0

func (e *JSONEditor) Set(path string, value any) *JSONEditor

Set writes value at path. A nil value is written as JSON null.

func (*JSONEditor) SetRaw added in v0.8.0

func (e *JSONEditor) SetRaw(path string, raw []byte) *JSONEditor

SetRaw writes a pre-encoded JSON fragment at path without re-encoding it.

type LeastRequestDecodePolicy

type LeastRequestDecodePolicy struct{}

LeastRequestDecodePolicy scores decode pods solely by their running-request count (including pending decode requests not yet visible in metrics). It is the simplest policy and useful when GPU-memory headroom differences between pods are negligible or when throughput metrics are unavailable.

func (LeastRequestDecodePolicy) Describe

func (LeastRequestDecodePolicy) Describe() string

func (LeastRequestDecodePolicy) Name

func (LeastRequestDecodePolicy) ScoreDecodePod

func (LeastRequestDecodePolicy) ScoreDecodePod(routingCtx *types.RoutingContext, pod *v1.Pod, in DecodePodInput) float64

type LoadBalancingDecodePolicy

type LoadBalancingDecodePolicy struct{}

LoadBalancingDecodePolicy scores decode pods by combining three normalised metrics: running-request count (higher → worse), generation throughput (lower → worse, expressed as inverse), and free GPU headroom (higher → better):

score = (wRun*normRunningReqs + wThru*(1 - normThroughput)) / normFreeGPU

Weights are set by AIBRIX_DECODE_LB_WEIGHT_RUNNING and AIBRIX_DECODE_LB_WEIGHT_THROUGHPUT (default 1.0 each).

func (LoadBalancingDecodePolicy) Describe

func (LoadBalancingDecodePolicy) Describe() string

func (LoadBalancingDecodePolicy) Name

func (LoadBalancingDecodePolicy) ScoreDecodePod

func (LoadBalancingDecodePolicy) ScoreDecodePod(routingCtx *types.RoutingContext, pod *v1.Pod, in DecodePodInput) float64

type PendingDecodeTracker

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

PendingDecodeTracker tracks decode pods that have been selected for a request but whose RealtimeNumRequestsRunning metric has not yet been incremented by the metrics scrape. This bridges the gap between decode pod selection (during routing) and the moment the decode pod actually starts processing the request, preventing concurrent requests from all being routed to the same decode pod during the prefill phase when the metric is still stale.

Pods are identified by their pod key, "namespace/name" (see utils.GeneratePodKey), for the same reason as in PrefillRequestTracker.

All methods are safe for concurrent use, including nil receivers (the tracker is optional and may be nil when disabled).

func NewPendingDecodeTracker

func NewPendingDecodeTracker() *PendingDecodeTracker

NewPendingDecodeTracker creates a new, empty PendingDecodeTracker.

func (*PendingDecodeTracker) AddPendingDecode

func (t *PendingDecodeTracker) AddPendingDecode(requestID, podKey string)

AddPendingDecode records that requestID has been assigned to the pod identified by podKey (see utils.GeneratePodKey) and increments that pod's pending-decode counter. Called by the pod selector as soon as the decode pod is chosen, under the same lock as the selection. RemovePendingDecode is deferred in Route.

func (*PendingDecodeTracker) GetPendingDecodeCount

func (t *PendingDecodeTracker) GetPendingDecodeCount(podKey string) float64

GetPendingDecodeCount returns the current pending-decode request count for the pod identified by podKey as a float64 (for direct addition to metric values). Returns 0 for unknown pods or when the receiver is nil.

func (*PendingDecodeTracker) RemovePendingDecode

func (t *PendingDecodeTracker) RemovePendingDecode(requestID string)

RemovePendingDecode decrements the pending-decode counter for the pod assigned to requestID and removes the request-to-pod mapping. It is a no-op if requestID is unknown. The counter is clamped to zero via a CAS loop to avoid erasing a concurrent Add(1) that races with the clamp.

type PrefillBodyError added in v0.8.0

type PrefillBodyError struct {
	Err error
}

PrefillBodyError is returned when the prefill pod answered 200 but the body could not be parsed. For engines whose KV handshake is the HTTP body (SGLang) the transfer did complete, so the decode leg must not be aborted; engines with an out-of-band handshake classify this as terminal via PrefillFailureIsTerminalFor.

func (*PrefillBodyError) Error added in v0.8.0

func (e *PrefillBodyError) Error() string

func (*PrefillBodyError) Unwrap added in v0.8.0

func (e *PrefillBodyError) Unwrap() error

type PrefillHTTPError added in v0.8.0

type PrefillHTTPError struct {
	StatusCode int
	Body       string
}

PrefillHTTPError is returned by the prefill executor when the prefill pod answers with a non-200, so callers can classify the failure and read the status code back out instead of parsing an error string.

func (*PrefillHTTPError) Error added in v0.8.0

func (e *PrefillHTTPError) Error() string

type PrefillRequestTracker

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

PrefillRequestTracker tracks the number of active prefill requests per pod. It is used by the prefill scorer to avoid routing new requests to pods that are already heavily loaded, and by the load-imbalance detector to select the least-loaded pod when the spread exceeds AIBRIX_PREFILL_LOAD_IMBALANCE_MIN_SPREAD.

Pods are identified by their pod key, "namespace/name" (see utils.GeneratePodKey): the tracker is shared by every model the router serves, and pods in different namespaces may share a name.

All methods are safe for concurrent use.

func NewPrefillRequestTracker

func NewPrefillRequestTracker() *PrefillRequestTracker

NewPrefillRequestTracker creates a new, empty PrefillRequestTracker.

func (*PrefillRequestTracker) AddPrefillRequest

func (t *PrefillRequestTracker) AddPrefillRequest(requestID, podKey string)

AddPrefillRequest records that requestID has been assigned to the pod identified by podKey (see utils.GeneratePodKey) and increments that pod's active-request counter. Called by the pod selector as soon as the prefill pod is chosen, under the same lock as the selection, so concurrent routing sees in-flight assignments. Must be paired with RemovePrefillRequest when prefill completes or the assignment is abandoned.

func (*PrefillRequestTracker) GetPrefillRequestCountsForPod

func (t *PrefillRequestTracker) GetPrefillRequestCountsForPod(podKey string) int

GetPrefillRequestCountsForPod returns the current active prefill request count for the pod identified by podKey, or 0 if no requests have been recorded for that pod.

func (*PrefillRequestTracker) GetPrefillRequestCountsForPods

func (t *PrefillRequestTracker) GetPrefillRequestCountsForPods(pods []*v1.Pod) map[string]int32

GetPrefillRequestCountsForPods returns a map of pod key (namespace/name) → active prefill request count for each pod in pods. Pods with no recorded requests are included with a count of 0.

func (*PrefillRequestTracker) RemovePrefillRequest

func (t *PrefillRequestTracker) RemovePrefillRequest(requestID string)

RemovePrefillRequest decrements the active-request counter for the pod that was assigned requestID and removes the request-to-pod mapping. It is a no-op if requestID was never added (e.g. the tracker was bypassed). The counter is clamped to zero if it would otherwise go negative.

type PrefillScorePolicy

type PrefillScorePolicy interface {
	// Prepare is called once per request. pods and readyPodsMap represent the
	// same candidate set; readyPodsMap is keyed by pod key (namespace/name, see
	// utils.GeneratePodKey) and is provided for O(1) lookups.
	// Returns an error only when scoring cannot proceed at all (e.g. tokenization
	// failure); in that case the router falls back to skipping the request.
	Prepare(routingCtx *types.RoutingContext, pods []*v1.Pod, readyPodsMap map[string]struct{}) (PrefillScorer, error)

	// Name returns the policy identifier used in log lines and metrics.
	Name() string
}

PrefillScorePolicy is the stateless factory for per-request PrefillScorers. The policy itself holds only immutable config (e.g. tokenizer and cache index handles). All per-request state is captured inside the PrefillScorer returned by Prepare, so the policy is safe to share across concurrent goroutines.

To add a new prefill scoring strategy: implement this interface and register it in NewPDRouter (pd_disaggregation.go) by handling the new policy name in the AIBRIX_PREFILL_SCORE_POLICY switch statement.

func NewConductorPrefillPolicy added in v0.8.0

func NewConductorPrefillPolicy(tok tokenizer.Tokenizer, prefixCacheIndexer *prefixcacheindexer.PrefixHashTable, metricCache cache.MetricCache, config ConductorPrefillPolicyConfig) PrefillScorePolicy

NewConductorPrefillPolicy constructs a conductor PrefillScorePolicy with the given tokenizer, shared prefix-hash table, metric cache, and TTFT estimation config.

func NewHybridCacheLoadPrefillPolicy added in v0.8.0

func NewHybridCacheLoadPrefillPolicy(tok tokenizer.Tokenizer, prefixCacheIndexer *prefixcacheindexer.PrefixHashTable, tracker *TokenLoadTracker) PrefillScorePolicy

NewHybridCacheLoadPrefillPolicy constructs a hybrid_cache_load PrefillScorePolicy over the given tokenizer, shared prefix-hash table and token-load tracker. The discount factor and the minimum match percentage are not properties of the policy: they are the request's resolved overrides, so a model config profile can retune them without rebuilding the policy.

func NewLeastRequestPrefillPolicy

func NewLeastRequestPrefillPolicy() PrefillScorePolicy

NewLeastRequestPrefillPolicy returns a least_request PrefillScorePolicy that routes to the pod with the fewest active prefill requests.

func NewPrefixCachePrefillPolicy

func NewPrefixCachePrefillPolicy(tok tokenizer.Tokenizer, prefixCacheIndexer *prefixcacheindexer.PrefixHashTable) PrefillScorePolicy

NewPrefixCachePrefillPolicy constructs a prefix_cache PrefillScorePolicy over the given tokenizer and shared prefix-hash table. The minimum match percentage is not a property of the policy: it is the request's resolved MinMatchPct override, so a model config profile can raise it for its own requests without rebuilding the policy.

func NewTokenLoadPrefillPolicy added in v0.8.0

func NewTokenLoadPrefillPolicy(tracker *TokenLoadTracker) PrefillScorePolicy

NewTokenLoadPrefillPolicy returns a token_load PrefillScorePolicy reading from tracker.

type PrefillScorer

type PrefillScorer interface {
	// ScorePod returns a score for pod (lower is better). reqCnt is the pod's
	// current running-request count; maxRequestCount is the maximum across all
	// candidate pods and is used for normalization. Implementations may use pod
	// for logging or metadata lookups (e.g. prefix_cache); implementations that
	// score purely by count (e.g. least_request) may ignore it.
	ScorePod(pod *v1.Pod, reqCnt, maxRequestCount float64) float64

	// PrefixHashes returns the token-prefix hashes used to warm the prefix-cache
	// index after a pod is selected. Returns nil when the policy does not use
	// the prefix cache (e.g. least_request).
	PrefixHashes() []uint64
}

PrefillScorer is a request-scoped scorer created by PrefillScorePolicy. Prepare for a single request. Each call to Prepare returns a fresh instance; no state is shared across concurrent requests.

type PrefillSetupError added in v0.8.0

type PrefillSetupError struct {
	Err error
}

PrefillSetupError marks a failure to build the prefill HTTP request.

func (*PrefillSetupError) Error added in v0.8.0

func (e *PrefillSetupError) Error() string

func (*PrefillSetupError) Unwrap added in v0.8.0

func (e *PrefillSetupError) Unwrap() error

type PrefixMatchScorer added in v0.8.0

type PrefixMatchScorer interface {
	// PrefixMatchPercent returns how much of the request's prompt (0-100) the
	// pod with the given pod key (namespace/name) already holds in its prefix
	// cache, or -1 when unknown.
	PrefixMatchPercent(podKey string) int
}

PrefixMatchScorer is implemented by PrefillScorers that looked the request up in the prefix cache during Prepare. The router uses it to charge only the uncached part of the prompt to the token-load tracker.

type RolesetDecodePick

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

RolesetDecodePick is the winning decode pod for one roleset after comparing scores within that roleset (lower score is better).

type TokenLoadConfig added in v0.8.0

type TokenLoadConfig struct {
	// KVWeight is the weight of resident KV tokens in GetPriority.
	KVWeight float64
	// RequestCost is the fixed per-request cost added to every charge, in tokens.
	RequestCost float64
	// TTL is the maximum age of an outstanding charge; 0 disables the sweep
	// of stale charges.
	TTL time.Duration
	// SessionTTL is how long a session's last prompt size is remembered for
	// the session-delta cost estimate; 0 disables session tracking.
	SessionTTL time.Duration
	// MaxSessions bounds the number of sessions remembered at once; 0 selects
	// DefaultTokenLoadMaxSessions.
	MaxSessions int
}

TokenLoadConfig holds the tunables of a TokenLoadTracker.

func DefaultTokenLoadConfig added in v0.8.0

func DefaultTokenLoadConfig() TokenLoadConfig

DefaultTokenLoadConfig returns the defaults, overridden by the AIBRIX_TOKEN_LOAD_KV_WEIGHT, AIBRIX_TOKEN_LOAD_REQUEST_COST, AIBRIX_TOKEN_LOAD_TTL_SECONDS, AIBRIX_TOKEN_LOAD_SESSION_TTL_SECONDS and AIBRIX_TOKEN_LOAD_MAX_SESSIONS environment variables. Each must be positive, except that a session TTL of 0 turns session tracking off; an unset, empty or invalid value keeps the default.

type TokenLoadDecodePolicy added in v0.8.0

type TokenLoadDecodePolicy struct{}

TokenLoadDecodePolicy scores decode pods by the KV the gateway has routed to them: a request is charged its prompt size when its decode pod is selected and released when it completes (see TokenLoadTracker), and the router adds an estimate of the output the outstanding requests have generated since (see TokenLoadTracker.DecodeGrowth). A decode pod receives the whole prompt's KV from the prefill pod, so this tracks the KV each decoder holds, updated synchronously with every selection instead of once per metric refresh. Lower is better.

func (TokenLoadDecodePolicy) Describe added in v0.8.0

func (TokenLoadDecodePolicy) Describe() string

func (TokenLoadDecodePolicy) Name added in v0.8.0

func (TokenLoadDecodePolicy) ScoreDecodePod added in v0.8.0

func (TokenLoadDecodePolicy) ScoreDecodePod(routingCtx *types.RoutingContext, pod *v1.Pod, in DecodePodInput) float64

type TokenLoadTracker added in v0.8.0

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

TokenLoadTracker keeps a token-weighted ledger of the prefill load the router has assigned to each prefill pod. It is the state behind the token_load prefill score policy.

Pods are identified by their pod key, "namespace/name" as built by utils.GeneratePodKey. One tracker serves every model the router routes, so a bare pod name is not enough: two deployments in different namespaces may name their prefill pods identically, and must not see each other's load.

Two counters are kept per pod:

  • active tokens: prompts the pod is computing right now;
  • kv tokens: prompts whose KV cache is still resident on the pod because the decoder has not finished pulling it.

The lifecycle of a prefill request is

  1. AcquirePrefill(requestID, podKey, cost): both counters += cost. The router calls this under the same lock as the pod selection, so concurrent selections see each other's charges.
  2. ReleaseTokens(requestID): active -= cost, when the prefill HTTP call returns.
  3. ReleaseKVCache(requestID): kv -= cost, when the whole request completes.

The two releases may arrive in either order; each subtracts its part once, and the request is forgotten as soon as both parts are released. Releases are idempotent per request ID and the counters are clamped at zero, so a duplicate release can never drive a pod negative. A charge whose release never arrives (the completion path was skipped) is force-released by the TTL janitor so it cannot pin load on a pod forever. The janitor also drops the counters and gauge series of pods that saw no traffic for a whole sweep interval, so pod churn does not grow the ledger without bound.

The tracker also keeps a decode ledger, the state behind the token_load decode score policy: AcquireDecode(requestID, podKey, cost) charges the decode pod a request was routed to, and ReleaseDecode(requestID) drops the charge when the request completes. A decode pod holds a request's KV from the transfer until the request finishes, so the charge lives that long. The decode charge is independent of the prefill one, with the same idempotent release, TTL sweep and idle-pod pruning.

All methods are safe for concurrent use. Reads do not allocate.

func NewTokenLoadTracker added in v0.8.0

func NewTokenLoadTracker() *TokenLoadTracker

NewTokenLoadTracker creates a tracker with DefaultTokenLoadConfig and starts its TTL janitor when either TTL is positive.

func NewTokenLoadTrackerWithConfig added in v0.8.0

func NewTokenLoadTrackerWithConfig(cfg TokenLoadConfig) *TokenLoadTracker

NewTokenLoadTrackerWithConfig creates a tracker with an explicit config and starts its TTL janitor when cfg.TTL or cfg.SessionTTL is positive.

func (*TokenLoadTracker) AcquireDecodeWithTTL added in v0.8.0

func (t *TokenLoadTracker) AcquireDecodeWithTTL(requestID, podKey string, cost float64, ttl time.Duration)

AcquireDecodeWithTTL charges cost to the decode counter of the pod identified by podKey and records the charge under requestID for ReleaseDecode. A ttl of 0 means the janitor never sweeps the charge. As with AcquirePrefill, a second charge for the same requestID releases the earlier one first, with a warning.

func (*TokenLoadTracker) AcquirePrefill added in v0.8.0

func (t *TokenLoadTracker) AcquirePrefill(requestID, podKey string, cost float64)

AcquirePrefill charges cost to both the active and the resident-KV counter of the pod identified by podKey (see utils.GeneratePodKey) and records the charge under requestID for later release, with the tracker's configured TTL. Request IDs are unique per request, so a second AcquirePrefill for the same requestID is a caller bug; it is tolerated by releasing whatever the earlier charge still holds before the new one replaces it, with a warning.

func (*TokenLoadTracker) AcquirePrefillWithTTL added in v0.8.0

func (t *TokenLoadTracker) AcquirePrefillWithTTL(requestID, podKey string, cost float64, ttl time.Duration)

AcquirePrefillWithTTL is AcquirePrefill with an explicit expiry for this charge, used when the request's model config profile overrides AIBRIX_TOKEN_LOAD_TTL_SECONDS. A ttl of 0 means the janitor never sweeps the charge; the normal releases still drop it.

func (*TokenLoadTracker) Close added in v0.8.0

func (t *TokenLoadTracker) Close()

Close stops the janitor goroutine, if one was started, and returns once it has exited. Charges and counters stay readable. Safe to call more than once.

func (*TokenLoadTracker) Config added in v0.8.0

func (t *TokenLoadTracker) Config() TokenLoadConfig

Config returns the tracker's tunables.

func (*TokenLoadTracker) DecodeGrowth added in v0.8.0

func (t *TokenLoadTracker) DecodeGrowth(podKey string, ratePerRequest float64) float64

DecodeGrowth estimates the output the requests outstanding on the pod identified by podKey have generated so far: ratePerRequest tokens per second for every outstanding decode charge, since it was made. It is ratePerRequest * (n*now - sum of charge times), O(1) per pod. Unknown pods, pods with no outstanding charge and a non-positive rate report 0.

func (*TokenLoadTracker) DecodeLedgerState added in v0.8.0

func (t *TokenLoadTracker) DecodeLedgerState(podKey string) (tokens float64, charges int64, sumChargedAt float64)

DecodeLedgerState returns the pod's charged decode tokens, its number of outstanding decode charges and the sum of their charge times as Unix seconds on the tracker's clock: what another gateway replica needs to add this replica's ledger, growth included, to its own. The three values are read together, so a charge or release in progress is either fully in them or not.

func (*TokenLoadTracker) GetDecodeLoad added in v0.8.0

func (t *TokenLoadTracker) GetDecodeLoad(podKey string) float64

GetDecodeLoad returns the decode counter of the pod identified by podKey: the charged prompt tokens of the requests routed to it that have not completed. Unknown pods report 0.

func (*TokenLoadTracker) GetLoad added in v0.8.0

func (t *TokenLoadTracker) GetLoad(podKey string) (activeTokens, kvTokens float64)

GetLoad returns the current active and resident-KV token counters of the pod identified by podKey. Unknown pods report 0, 0.

func (*TokenLoadTracker) GetPriority added in v0.8.0

func (t *TokenLoadTracker) GetPriority(podKey string) float64

GetPriority returns the token-load priority of the pod identified by podKey, lower is better:

active_tokens + kv_weight * kv_tokens

func (*TokenLoadTracker) GetPriorityWithKVWeight added in v0.8.0

func (t *TokenLoadTracker) GetPriorityWithKVWeight(podKey string, kvWeight float64) float64

GetPriorityWithKVWeight is GetPriority with an explicit KV weight, used when the request's model config profile overrides AIBRIX_TOKEN_LOAD_KV_WEIGHT.

func (*TokenLoadTracker) NewTokens added in v0.8.0

func (t *TokenLoadTracker) NewTokens(model, sessionID string, promptTokens, matchPct int) (int, string)

NewTokens estimates how many of a request's promptTokens the selected pod has to compute, the new_tokens term of the prefill cost. It returns the estimate and which rule produced it:

  1. When sessionID is set and the (model, session) was seen before with a shorter prompt, the growth since that prompt. Each turn of a conversation resends the whole history, but an engine that still holds the conversation's KV cache only computes the new turn. This rule therefore assumes the earlier turns are reachable from the selected pod (sticky routing, a shared or tiered KV store, or the same pod's prefix cache); callers whose deployment cannot offer that should not send a session ID. The prompt size is recorded for the next turn, so call this once per charged request. A session ID longer than 256 bytes is ignored, and once MaxSessions sessions are live a new one is not recorded, so its requests fall through to the rules below.
  2. Otherwise, when matchPct (0-100) is non-negative, the part of the prompt the pod's prefix cache does not cover: promptTokens × (1 − matchPct/100). Pass a negative matchPct when no match information is available.
  3. Otherwise the whole prompt.

The result is never negative or larger than promptTokens.

func (*TokenLoadTracker) NewTokensWithSessionLimits added in v0.8.0

func (t *TokenLoadTracker) NewTokensWithSessionLimits(model, sessionID string, promptTokens, matchPct int, sessionTTL time.Duration, maxSessions int) (int, string)

NewTokensWithSessionLimits is NewTokens with explicit session limits, used when the request's model config profile overrides AIBRIX_TOKEN_LOAD_SESSION_TTL_SECONDS or AIBRIX_TOKEN_LOAD_MAX_SESSIONS. A sessionTTL of 0 disables the session-delta rule for the request, and a non-positive maxSessions falls back to the tracker's cap.

func (*TokenLoadTracker) PrefillCost added in v0.8.0

func (t *TokenLoadTracker) PrefillCost(promptTokens int) float64

PrefillCost returns the load charged for a prefill of promptTokens tokens: the fixed per-request cost plus the prompt length.

func (*TokenLoadTracker) PrefillCostWithRequestCost added in v0.8.0

func (t *TokenLoadTracker) PrefillCostWithRequestCost(promptTokens int, requestCost float64) float64

PrefillCostWithRequestCost is PrefillCost with an explicit per-request cost, used when the request's model config profile overrides AIBRIX_TOKEN_LOAD_REQUEST_COST.

func (*TokenLoadTracker) ReleaseAll added in v0.8.0

func (t *TokenLoadTracker) ReleaseAll(requestID string)

ReleaseAll releases whatever requestID still holds on the prefill counters and the decode ledger and forgets the request. Use it on terminal paths where nothing of the request can remain on its pods (prefill failure, request completion).

func (*TokenLoadTracker) ReleaseDecode added in v0.8.0

func (t *TokenLoadTracker) ReleaseDecode(requestID string)

ReleaseDecode subtracts requestID's decode charge from its pod's decode counter. No-op for an unknown request ID or a repeated call.

func (*TokenLoadTracker) ReleaseKVCache added in v0.8.0

func (t *TokenLoadTracker) ReleaseKVCache(requestID string)

ReleaseKVCache subtracts requestID's charge from its pod's resident-KV counter. Call it when the request completes. It does not touch the active counter: a request that completes while its prefill call is somehow still outstanding keeps that charge, and stays in the ledger, until ReleaseTokens or the janitor. No-op for an unknown request ID or a repeated call.

func (*TokenLoadTracker) ReleaseTokens added in v0.8.0

func (t *TokenLoadTracker) ReleaseTokens(requestID string)

ReleaseTokens subtracts requestID's charge from its pod's active counter. Call it when the prefill HTTP call returns. The KV charge stays until ReleaseKVCache. No-op for an unknown request ID or a repeated call.

func (*TokenLoadTracker) SetDecodeLedgerListener added in v0.8.0

func (t *TokenLoadTracker) SetDecodeLedgerListener(fn func(podKey string))

SetDecodeLedgerListener registers fn to be called with a pod key after every change to that pod's decode ledger: a charge, a release, a re-acquire and a TTL sweep. fn runs on the caller's path and must not block. nil unregisters.

Directories

Path Synopsis
Package selector defines the PodSelector contract for PD-disaggregated routing.
Package selector defines the PodSelector contract for PD-disaggregated routing.

Jump to

Keyboard shortcuts

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