From 08fa37e48d003910dff0facc7a3792eaced2515a Mon Sep 17 00:00:00 2001 From: Kan Wu Date: Mon, 5 Oct 2026 03:17:32 -0700 Subject: [PATCH] [sgl-router] Add reorg bucket config with per-group admission (#42429) Co-authored-by: Kan Wu Co-authored-by: Claude Opus 5.5 Co-authored-by: Kan Wu --- experimental/sgl-router/POLICY_DESIGN.md | 142 +++++---- experimental/sgl-router/README.md | 40 ++- experimental/sgl-router/src/buckets_reorg.rs | 15 +- experimental/sgl-router/src/config/cli.rs | 139 ++++++++- experimental/sgl-router/src/config/mod.rs | 2 + experimental/sgl-router/src/config/types.rs | 8 +- experimental/sgl-router/src/discovery/k8s.rs | 134 +++++++- .../sgl-router/src/discovery/types.rs | 10 + .../sgl-router/src/policies/dp_rank.rs | 1 + .../sgl-router/src/policies/factory.rs | 2 + .../src/policies_reorg/admission.rs | 94 +++++- .../sgl-router/src/policies_reorg/factory.rs | 294 ++++++++++++++---- .../sgl-router/src/server/app_context.rs | 2 + .../sgl-router/src/server/routes/models.rs | 2 + .../sgl-router/src/server/routes/tokenize.rs | 2 + experimental/sgl-router/src/tokenizer/mod.rs | 2 + .../sgl-router/src/workers/manager.rs | 16 + experimental/sgl-router/src/workers/worker.rs | 24 +- .../tests/component/discovery/static_urls.rs | 2 + .../tests/component/policies_reorg.rs | 1 + .../component/policies_reorg_admission.rs | 108 ++++++- .../component/tokenizer/render_parity.rs | 2 + .../tests/component/workers/manager.rs | 47 +++ .../sgl-router/tests/proxy/bucket_routing.rs | 2 + .../sgl-router/tests/proxy/chat_routing.rs | 2 + .../tests/proxy/chat_routing/reorg.rs | 65 ++-- .../proxy/chat_routing/reorg/session_aware.rs | 2 + .../tests/proxy/common/cache_aware_fixture.rs | 2 + .../sgl-router/tests/proxy/dp_rank_routing.rs | 1 + .../sgl-router/tests/proxy/failover.rs | 2 + .../tests/proxy/graceful_shutdown.rs | 2 + .../tests/proxy/header_forwarding.rs | 2 + .../tests/proxy/pd_bootstrap_injection.rs | 2 + .../tests/proxy/pd_pool_isolation.rs | 3 + .../tests/proxy/pd_protocol_binding.rs | 2 + .../tests/proxy/roundrobin_input_ids.rs | 2 + .../tests/proxy/shared_prefill_admission.rs | 2 + .../tests/proxy/sticky_input_ids.rs | 2 + .../sgl-router/tests/proxy/sticky_routing.rs | 2 + .../sgl-router/tests/proxy/timeout.rs | 2 + 40 files changed, 971 insertions(+), 215 deletions(-) diff --git a/experimental/sgl-router/POLICY_DESIGN.md b/experimental/sgl-router/POLICY_DESIGN.md index 8d2b011dad..2bb911d0fd 100644 --- a/experimental/sgl-router/POLICY_DESIGN.md +++ b/experimental/sgl-router/POLICY_DESIGN.md @@ -39,10 +39,11 @@ workers. Group policy instances are reused across requests. | `WorkerRegistry` | Live workers, model membership, health, and role | | Request handler | Request preparation, ordered bucket attempts, HTTP errors, and dispatch | -`worker_ids: None` means every healthy engine serving the requested model and -role. An explicit empty set means no engines. `EngineGroup::new(policy)` creates -a catch-all membership group. `BucketGroups::Pd` requires both groups, making -partial or mixed plain/PD bucket configurations unrepresentable. +Omitting both `worker_ids` and `worker_services` includes every healthy engine +serving the requested model and role. Explicit empty membership lists are rejected +by the config factory. `EngineGroup::new(policy)` creates a catch-all group. +`BucketGroups::Pd` requires both groups, making partial or mixed plain/PD bucket +configurations unrepresentable. ## 1. Code organization @@ -247,24 +248,25 @@ change buckets, or mutate affinity. An admission policy is a set of per-engine caps, `AdmissionLimits`. Each cap is optional; an unset cap is not checked, and the default admits everything. -A cap admits while the engine's current metric is below it. Request size is -not part of admission: buckets already select by input length and context -capacity, and admission only observes load without reserving it. +Each cap admits while the engine's load is below it. Usage caps are shares, in +(0, 1], of the engine's reported capacity, so one limit fits engines of any +size. The request itself is not counted: an engine just below a cap still takes +it, and the engine queues or retracts if it overflows. Admission observes load +without reserving it. -| Limit | Engine metric | +| Limit | Checks | | --- | --- | -| `max_running_requests` | Reported running requests | +| `max_running_usage` | Running requests against reported max running requests | +| `max_kv_usage` | KV tokens against reported KV capacity | | `max_waiting_requests` | Reported waiting requests | -| `max_kv_tokens` | Reported total KV tokens | | `max_pending_prefill_tokens` | Reported waiting uncached tokens | | `max_inflight_requests` | Router-local in-flight requests | ```json -{"max_running_requests": 64, "max_kv_tokens": 1048576, "max_inflight_requests": 64} +{"max_running_usage": 0.9, "max_kv_usage": 0.95, "max_inflight_requests": 64} ``` -Limits are absolute caps; they do not default to capacities reported by the -engine. Unknown fields are rejected during deserialization. +Unknown fields are rejected during deserialization. The policy reads the selected engine's `EngineMetrics` from the load snapshot it already captured for selection plus the live in-flight counter and calls @@ -447,61 +449,67 @@ selection or dispatch fails. It must not increment dispatch accounting. ## 7. Configuration and compatibility -This conceptual example shows the target attachment model. It is not copyable -current CLI/JSON syntax; existing bucket field names need not change. +Under `--chat-routing reorg`, `--bucket-config` reads a JSON file of complete +buckets. Each bucket sets `plain`, or both `prefill` and `decode`; each group may +set `worker_ids` or `worker_services`, plus `policy` and `admission`. -```yaml -buckets: - - id: short-context - rank: 10 - limits: {min: 0, max: 4096} - max_context_tokens: 8192 - groups: - pd: - prefill: - worker_ids: [P1, P2] - policy: - type: cache_aware - admission: {max_running_requests: 64, max_kv_tokens: 1048576} - decode: - worker_ids: [D1, D2] - policy: - type: power_of_two - admission: {max_running_requests: 64, max_kv_tokens: 1048576} - - - id: long-context - rank: 20 - limits: {min: 0, max: 131072} - max_context_tokens: 131072 - groups: - pd: - prefill: - worker_ids: [P3, P4] - policy: - type: cache_aware - admission: {max_running_requests: 64, max_kv_tokens: 1048576} - decode: - worker_ids: [D3, D4] - policy: - type: power_of_two - admission: {max_running_requests: 64, max_kv_tokens: 1048576} +```json +{ + "ttft_slo": "slo_first", + "buckets": [ + { + "id": "short-context", + "max_input_tokens": 4096, + "max_context_tokens": 8192, + "ttft_ms": 300, + "prefill": {"worker_services": ["inference/prefill-short"], "admission": {"max_pending_prefill_tokens": 32768}}, + "decode": {"worker_services": ["inference/decode-short"], "admission": {"max_kv_usage": 0.9}} + }, + { + "id": "long-context", + "rank": 1, + "max_context_tokens": 131072, + "prefill": {"worker_services": ["inference/prefill-long"]}, + "decode": {"worker_services": ["inference/decode-long"]} + } + ] +} ``` A request with 4k input tokens and a 16k expected peak cannot fit the short bucket's context capacity. It selects the long bucket and both of its P/D groups. With a known peak of 8k or less, the same input selects both groups of the short bucket. -The planned factory validates unique nonempty bucket IDs, token ranges, and -role-compatible membership. Each bucket is either plain or PD. The selected -bucket invokes its required groups through `pick_engines`. The existing worker registry -still rejects mixed plain and PD engines within one model; this PR preserves -that constraint. The engine group's model and stage filters apply on every pick. +Membership has two mutually exclusive forms. `worker_ids` pins exact discovery +identities: URLs for static discovery, `namespace/pod-UID` for Kubernetes pods. +`worker_services` lists Kubernetes `namespace/service` names and matches any +listed Service through its EndpointSlices' `kubernetes.io/service-name` label. +Service membership survives pod replacement and scale-up; worker IDs still +change per pod incarnation so breaker, load and affinity state cannot carry over. +Only Services included by the discovery watch are visible. Multiple slices and +Services selecting one pod contribute the union of its memberships; removing a +slice removes only memberships no longer advertised by another slice. Membership +updates preserve the live worker and its in-flight state. Readiness and routing +use the same group filter, including model, health and role constraints. -Legacy `BucketSpec` represents a single role-specific membership set. Migration -must explicitly associate prefill and decode specs into complete PD buckets; -never infer those associations from matching rank or similar names. Translation -of role-specific ranges/ranks into bucket-level constraints needs explicit -validation and is deferred with the configuration factory. +Omitted group fields mean every engine of the group's role and `--policy` +(power-of-two on decode). Admission limits a group leaves unset take +`--max-in-flight` / `--max-kv-usage`, field by field. JSON `null` also inherits; +there is no per-group disable value. To limit only some groups, leave the CLI +default unset and configure those groups explicitly. A group policy is +`power_of_two` or the `--policy` kind, whose affinity, cache and tokenizer +settings are the ones resolved. Startup rejects empty or duplicate IDs, a bucket +that is not exactly plain or P/D, inverted token ranges, a minimum input above +the context capacity, empty membership lists, blank worker IDs, malformed +Service names, both membership fields together, non-positive capacity or SLO +estimates, usages outside (0, 1], zero count limits, and a policy a stage cannot +serve. Without the flag, reorg builds one plain and one P/D bucket +over all engines. The worker registry still rejects mixed plain and PD engines +within one model. + +Legacy `--bucket-config` files describe role-specific buckets and do not +translate: P/D associations must be written explicitly, never inferred from +rank or names. Retained settings keep their meanings, defaults, units, and validation unless a change is listed below. Policy-specific tuning applies to role groups using that @@ -522,7 +530,8 @@ do not accept and ignore them. - Preserve session and sticky headers, idle timeouts, eviction cadence, and the four sticky fallback choices. Global modes need a bucket-first migration design. - Map `--filter overloaded` and `--max-in-flight` to `max_inflight_requests`; - the existing router-local counter remains the source. + the existing router-local counter remains the source. `--max-kv-usage` sets + `max_kv_usage` for groups that leave it unset. - Preserve configured capacity, pending-prefill, and in-flight checks, including their missing-report behavior. Power-of-two applies admission to its selected engine; other policies explicitly place checks in their selection logic. @@ -589,8 +598,8 @@ Implemented here: - `EngineGroup::pick` owns live candidate filtering, policy invocation, and exact candidate validation, without cross-bucket fallback. - `Policy::pick`, within-group fallback interface, per-engine `EngineAdmission::check`, - and `AdmissionLimits` over running, waiting, KV, pending-prefill and in-flight - metrics. Power-of-two samples two distinct engines, compares stage pressure, + and `AdmissionLimits` with running and KV usage shares plus waiting, + pending-prefill and in-flight counts. Power-of-two samples two distinct engines, compares stage pressure, and checks its selected engine with no replacement on rejection. - Policy-owned load dependency and local observations. Power-of-two passes the selected engine's load record directly to admission, without another snapshot. @@ -619,13 +628,14 @@ Implemented here: The caller owns expiry and sweeper lifecycle. A binding may remain after a later PD group fails, because it records placement rather than dispatch. -Follow-up work includes remaining selection policies and explicit bucket configuration. +- `--bucket-config` builds explicit plain and P/D buckets with per-group + membership, policy and admission; omitting it builds the default buckets. + +Follow-up work includes remaining selection policies. Not yet implemented in the reorg path: - Other concrete selection policies. -- Explicit bucket configuration from the CLI. The YAML above remains illustrative; - `--chat-routing reorg` builds default plain/PD buckets from existing policy flags. - Global session modes and sticky routing-key affinity. - Power-of-k cache-miss fallback configuration and cache decision metrics. - Shared load interpretation, dispatch correction, and policy-specific diff --git a/experimental/sgl-router/README.md b/experimental/sgl-router/README.md index 3b644a682a..826d0afefc 100644 --- a/experimental/sgl-router/README.md +++ b/experimental/sgl-router/README.md @@ -161,7 +161,7 @@ all of it, and the `sgl_router_kv_bootstrap_*` series in ### Reorg routing Use `--chat-routing reorg` to select the new bucket engine. The existing `--policy` -and cache/session flags configure its policies; no separate file is required. +and cache/session flags configure its policies; a bucket file is optional. ```bash sgl-router --model-id qwen3 --worker-urls http://localhost:30001 \ @@ -171,9 +171,36 @@ sgl-router --model-id qwen3 --worker-urls http://localhost:30001 \ Reorg supports `power_of_two` (its default), `cache_aware`, and `session_aware`. Discovery supplies the plain or PD workers; decode uses power-of-two. Cache settings, external indexers, session headers/timeouts, and `--filter overloaded` -with `--max-in-flight` retain their existing flags. Unsupported legacy options -fail at startup. Legacy `--bucket-config` files cannot define complete reorg PD -buckets and are not accepted on this path. +with `--max-in-flight` retain their existing flags. `--max-kv-usage 0.95` rejects +an engine whose KV tokens have reached 95% of its capacity. +Unsupported legacy options fail at startup. + +`--bucket-config buckets.json` replaces the default plain and P/D buckets. Each +bucket is plain or P/D, and each group may set its own engines, policy and +admission; see [POLICY_DESIGN.md](POLICY_DESIGN.md#7-configuration-and-compatibility): + +```json +{"buckets": [{ + "id": "default", + "prefill": {"worker_services": ["inference/prefill"], "admission": {"max_pending_prefill_tokens": 32768}}, + "decode": {"worker_services": ["inference/decode"], "admission": {"max_kv_usage": 0.9}} +}]} +``` + +`worker_services` matches Kubernetes Services by `namespace/name`, using the +`kubernetes.io/service-name` label on watched EndpointSlices. Replacement pods +and new replicas join the same group automatically. The router's discovery +selectors must include those EndpointSlices; this field does not expand the watch. +A worker selected by several Services belongs to each of them. + +For static URL discovery, use `"worker_ids": ["http://worker:30000"]`: each ID +is the configured worker URL. Kubernetes worker IDs are `namespace/pod-UID` +(and change when a pod is replaced), so use `worker_services` for durable pools. +Set only one membership field, or omit both for every engine of the group's role. +Empty membership lists and blank worker IDs are rejected at startup. + +Admission fields left unset or set to `null` inherit CLI defaults. To apply a +limit only to selected groups, omit that CLI default and set it on those groups. Omitting `--chat-routing` keeps the existing policies and defaults. @@ -196,8 +223,9 @@ and queue/saturation gates in favor of these shared affinity settings. `--no-tokenizer` skips tokenizer loading for load-only policies such as `power_of_two` and `session_aware`, on either routing path. Workers tokenize the original messages, and `/v1/tokenize` and `/v1/detokenize` are unavailable. -Cache-aware routing, prefix-cache terms or filters, and `--bucket-config` still -require a tokenizer. +Cache-aware routing, prefix-cache terms or filters, and buckets with token-length +or context limits require a tokenizer. Reorg buckets that only select membership +and load-based policies can use `--no-tokenizer`. ### DP-rank routing diff --git a/experimental/sgl-router/src/buckets_reorg.rs b/experimental/sgl-router/src/buckets_reorg.rs index ce3246f475..ec9a13193d 100644 --- a/experimental/sgl-router/src/buckets_reorg.rs +++ b/experimental/sgl-router/src/buckets_reorg.rs @@ -17,7 +17,7 @@ //! //! The handler tries buckets in order, advancing on missing candidates or admission //! rejection. Both P/D picks must succeed in the same bucket before dispatch. -//! [`WorkerRegistry`] owns live workers; groups reference their IDs. Policies own +//! [`WorkerRegistry`] owns live workers; groups select by ID or Service. Policies own //! their load/KV/affinity dependencies and pass selected observations to admission. use std::collections::HashSet; @@ -41,8 +41,10 @@ impl TokenLimits { #[derive(Debug)] pub struct EngineGroup { - /// `None` includes all registered engines matching the request's model and role. + /// Exact identities. Omit both membership fields to include all engines of the role. pub worker_ids: Option>, + /// Match any named Kubernetes Service (namespace/name), across pod replacements. + pub worker_services: Option>, pub policy: Arc, } @@ -50,6 +52,7 @@ impl EngineGroup { pub fn new(policy: Arc) -> Self { Self { worker_ids: None, + worker_services: None, policy, } } @@ -74,6 +77,11 @@ impl EngineGroup { .as_ref() .is_none_or(|ids| ids.contains(&engine.id)) }) + .filter(|engine| { + self.worker_services + .as_ref() + .is_none_or(|services| engine.matches_services(services)) + }) .collect() } @@ -302,7 +310,8 @@ impl Bucket { } /// Soft preference; nonpreferred buckets remain available for fallback. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "snake_case")] pub enum SloPreference { #[default] Disabled, diff --git a/experimental/sgl-router/src/config/cli.rs b/experimental/sgl-router/src/config/cli.rs index df2a3695c7..ceebfb2170 100644 --- a/experimental/sgl-router/src/config/cli.rs +++ b/experimental/sgl-router/src/config/cli.rs @@ -20,6 +20,7 @@ use crate::config::{ StaticUrlsDiscoveryConfig, StickyConfig, StickyFallbackKind, TokenizerBackend, TokenizerConfig, DEFAULT_FUSE, DEFAULT_KV_BOOTSTRAP_FETCH_TIMEOUT_CAP_MS, DEFAULT_KV_BOOTSTRAP_TIMEOUT_MS, }; +use crate::policies_reorg::admission::AdmissionLimits; const DEFAULT_KV_INDEXER_QUERY_TIMEOUT_MS: u64 = 100; const DEFAULT_KV_INDEXER_QUERY_MAX_INFLIGHT: usize = sgl_kv_indexer::DEFAULT_QUERY_MAX_INFLIGHT; @@ -226,7 +227,8 @@ pub struct RoutingArgs { #[arg(long)] pub dp_aware: bool, - /// Static P/D bucket configuration. Omit to use the global candidate domain. + /// Static bucket configuration JSON; the reorg schema with --chat-routing reorg. + /// Omit to use the global candidate domain (default buckets with reorg). #[arg(long)] pub bucket_config: Option, @@ -244,6 +246,11 @@ pub struct RoutingArgs { #[arg(long)] pub max_in_flight: Option, + /// Reorg admission: reject an engine whose KV tokens have reached this share + /// of its reported capacity, in (0, 1]. + #[arg(long)] + pub max_kv_usage: Option, + /// Minimum cached prompt share for `--filter prefix_cache`. #[arg(long)] pub prefix_cache_min_share: Option, @@ -455,6 +462,10 @@ impl Cli { && self.affinity.affinity_load_gap.is_none(), "prefer, balanced and --affinity-load-* require --chat-routing reorg" ); + ensure!( + self.routing.max_kv_usage.is_none(), + "--max-kv-usage requires --chat-routing reorg" + ); ensure!( self.affinity.affinity_mode.is_none() || self.routing.policy == PolicyKind::SessionAware, @@ -471,12 +482,12 @@ impl Cli { .affinity .build_config(&self.cache, self.routing.policy)?; let discovery = self.discovery.into_config()?; - let bucket_config = self - .routing - .bucket_config - .as_deref() - .map(load_bucket_config) - .transpose()?; + let path = self.routing.bucket_config.as_deref(); + let (bucket_config, reorg_buckets) = match path { + Some(path) if reorg => (None, Some(load_bucket_config(path)?)), + Some(path) => (Some(load_bucket_config(path)?), None), + None => (None, None), + }; let circuit_breaker = self.routing.build_circuit_breaker()?; let kv_bootstrap_timeout_ms = self.cache.kv_bootstrap_timeout_ms; let kv_bootstrap_fetch_timeout_cap_ms = self.cache.kv_bootstrap_fetch_timeout_cap_ms; @@ -507,6 +518,7 @@ impl Cli { } let fused = self.routing.build_fused()?; let eligibility = self.routing.build_eligibility()?; + let reorg_admission = self.routing.build_reorg_admission()?; let sticky = self.affinity.into_sticky_config(self.routing.policy)?; let sampling_overrides = self .model @@ -563,6 +575,8 @@ impl Cli { decode_policy: self.routing.decode_policy, dp_aware: self.routing.dp_aware, bucket_config, + reorg_buckets, + reorg_admission, circuit_breaker, cache_aware, sticky, @@ -746,6 +760,19 @@ impl RoutingArgs { Ok(eligibility) } + + /// Reorg admission for groups without their own limits. + fn build_reorg_admission(&self) -> Result { + let limits = AdmissionLimits { + max_inflight_requests: self.max_in_flight.map(|n| n as u64), + max_kv_usage: self.max_kv_usage, + ..Default::default() + }; + limits + .validate() + .map_err(|error| anyhow!("--max-in-flight / --max-kv-usage: {error}"))?; + Ok(limits) + } } impl CacheArgs { @@ -1051,7 +1078,7 @@ impl AffinityArgs { } } -fn load_bucket_config(path: &str) -> Result { +fn load_bucket_config(path: &str) -> Result { let raw = std::fs::read_to_string(path) .map_err(|error| anyhow!("--bucket-config cannot read {path:?}: {error}"))?; serde_json::from_str(&raw) @@ -1127,16 +1154,18 @@ mod tests { session.model.affinity.unwrap().session_id_header, "x-session" ); - assert_eq!( - parse(&["--filter", "overloaded", "--max-in-flight", "2"]) - .unwrap() - .model - .eligibility - .unwrap() - .max_in_flight, - Some(2) - ); + let overloaded = parse(&["--filter", "overloaded", "--max-in-flight", "2"]) + .unwrap() + .model; + assert_eq!(overloaded.eligibility.unwrap().max_in_flight, Some(2)); + assert_eq!(overloaded.reorg_admission.max_inflight_requests, Some(2)); + let kv = parse(&["--max-kv-usage", "0.9"]).unwrap().model; + assert_eq!(kv.reorg_admission.max_kv_usage, Some(0.9)); + assert!(kv.eligibility.is_none()); + let legacy_kv = Cli::try_parse_from(base.iter().chain(&["--max-kv-usage", "0.9"])); + assert!(legacy_kv.unwrap().into_config().is_err()); for args in [ + vec!["--max-kv-usage", "1.5"], vec!["--policy", "round_robin"], vec!["--decode-policy", "legacy_host_affinity"], vec!["--policy", "session_aware", "--stable-pair"], @@ -2878,6 +2907,82 @@ mod tests { ); } + #[tokio::test] + async fn reorg_bucket_config_builds_complete_buckets_and_rejects_invalid_ones() { + use crate::buckets_reorg::{BucketResolver, SloPreference}; + use serde_json::json; + fn build(buckets: &serde_json::Value) -> Result { + let file = tempfile::NamedTempFile::new()?; + std::fs::write(file.path(), buckets.to_string())?; + let config = into_config_owned(with_model(&[ + "--worker-urls", + "http://worker:30000", + "--chat-routing", + "reorg", + "--policy", + "session_aware", + "--bucket-config", + file.path().to_str().unwrap(), + ]))?; + let state = crate::state::kv_events::KvEventIndex::new(); + let (resolver, _) = + crate::policies_reorg::factory::build_resolver(&config.model, &state, None)?; + Ok(resolver) + } + let resolver = build(&json!({ + "ttft_slo": "slo_first", + "buckets": [ + {"id": "short", "max_input_tokens": 4096, "plain": { + "worker_ids": ["a"], "admission": {"max_kv_usage": 0.9} + }}, + {"id": "long", "rank": 1, "prefill": {}, "decode": {"policy": "power_of_two", "worker_services": ["ns/decode"]}} + ] + })) + .unwrap(); + assert_eq!(resolver.ttft_slo, SloPreference::SloFirst); + let shape: Vec<_> = (resolver.buckets.iter()) + .map(|b| (b.id.as_str(), b.rank, b.limits.max)) + .collect(); + assert_eq!(shape, [("short", 0, Some(4096)), ("long", 1, None)]); + let crate::buckets_reorg::BucketGroups::Pd { decode, .. } = &resolver.buckets[1].groups + else { + panic!("expected PD bucket"); + }; + assert_eq!( + decode.worker_services.as_ref().unwrap(), + &["ns/decode".into()].into() + ); + for bad in [ + json!({"buckets": []}), + json!({"buckets": [{"id": "x", "plain": {}, "prefill": {}}]}), + json!({"buckets": [{"id": "x", "prefill": {}}]}), + json!({"buckets": [{"id": "x", "plain": {}}, {"id": "x", "plain": {}}]}), + json!({"buckets": [{"id": "x", "plain": {"policy": "cache_aware"}}]}), + json!({"buckets": [{"id": "x", "plain": {"admission": {"max_kv_usage": 2.0}}}]}), + json!({"buckets": [{"id": "x", "plain": {"admission": {"max_kv_tokens": 1}}}]}), + json!({"buckets": [{"id": "x", "plain": {"admission": {"max_running_usage": 0}}}]}), + json!({"buckets": [{"id": "x", "plain": {"admission": {"max_waiting_requests": 0}}}]}), + json!({"buckets": [{"id": "", "plain": {}}]}), + json!({"buckets": [{"id": "x", "min_input_tokens": 9, "max_input_tokens": 8, "plain": {}}]}), + json!({"buckets": [{"id": "x", "min_input_tokens": 9, "max_context_tokens": 8, "plain": {}}]}), + json!({"buckets": [{"id": "x", "max_context_tokens": 0, "plain": {}}]}), + json!({"buckets": [{"id": "x", "ttft_ms": 0, "plain": {}}]}), + json!({"buckets": [{"id": "x", "tokens_per_second": 0.0, "plain": {}}]}), + json!({"buckets": [{"id": "x", "plain": {"worker_ids": []}}]}), + json!({"buckets": [{"id": "x", "plain": {"worker_ids": [""]}}]}), + json!({"buckets": [{"id": "x", "plain": {"worker_ids": [" \t"]}}]}), + json!({"buckets": [{"id": "x", "plain": {"worker_services": []}}]}), + json!({"buckets": [{"id": "x", "plain": {"worker_services": ["short"]}}]}), + json!({"buckets": [{"id": "x", "plain": {"worker_services": ["ns/"]}}]}), + json!({"buckets": [{"id": "x", "plain": {"worker_services": ["/short"]}}]}), + json!({"buckets": [{"id": "x", "plain": {"worker_services": ["ns/short/extra"]}}]}), + json!({"buckets": [{"id": "x", "plain": {"worker_services": ["ns/ short"]}}]}), + json!({"buckets": [{"id": "x", "plain": {"worker_ids": ["a"], "worker_services": ["ns/short"]}}]}), + ] { + assert!(build(&bad).is_err(), "accepted {bad}"); + } + } + /// The flag reaches `ModelConfig`, and is opt-in: unset leaves the model /// with an empty sampling contract, so no request is ever checked. #[test] diff --git a/experimental/sgl-router/src/config/mod.rs b/experimental/sgl-router/src/config/mod.rs index 7fd92d4d92..420bfc7ad3 100644 --- a/experimental/sgl-router/src/config/mod.rs +++ b/experimental/sgl-router/src/config/mod.rs @@ -255,6 +255,8 @@ mod tests { decode_policy: DecodePolicyKind::PowerOfTwo, dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, diff --git a/experimental/sgl-router/src/config/types.rs b/experimental/sgl-router/src/config/types.rs index f37d5db2e5..4d38143bb5 100644 --- a/experimental/sgl-router/src/config/types.rs +++ b/experimental/sgl-router/src/config/types.rs @@ -84,7 +84,8 @@ pub struct TokenizerConfig { } /// Routing strategies accepted by `--policy`. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum, Deserialize)] +#[serde(rename_all = "snake_case")] pub enum PolicyKind { #[default] #[value(name = "round_robin")] @@ -345,6 +346,11 @@ pub struct ModelConfig { pub dp_aware: bool, /// Optional static bucket configuration. `None` uses the global domain. pub bucket_config: Option, + /// Reorg `--bucket-config`; `None` builds the default plain and P/D buckets. + pub reorg_buckets: Option, + /// Reorg admission for groups that leave a limit unset: `--max-in-flight` + /// and `--max-kv-usage`. + pub reorg_admission: crate::policies_reorg::admission::AdmissionLimits, pub circuit_breaker: Option, /// Cache-Aware prefix configuration. pub cache_aware: Option, diff --git a/experimental/sgl-router/src/discovery/k8s.rs b/experimental/sgl-router/src/discovery/k8s.rs index 7a77b9436d..448ddaf4ba 100644 --- a/experimental/sgl-router/src/discovery/k8s.rs +++ b/experimental/sgl-router/src/discovery/k8s.rs @@ -152,6 +152,15 @@ fn extract_workers(es: &EndpointSlice, mode: WorkerMode) -> Vec { url, mode, model_ids: Vec::new(), + services: es + .metadata + .labels + .as_ref() + .and_then(|labels| labels.get("kubernetes.io/service-name")) + .filter(|service| !ns.is_empty() && !service.is_empty()) + .map(|service| format!("{ns}/{service}")) + .into_iter() + .collect(), ..Default::default() }); } @@ -202,10 +211,15 @@ async fn emit_diff( per_slice: &HashMap>, prev_union: &mut HashMap, ) -> Result<(), mpsc::error::SendError> { - let union: HashMap = per_slice - .values() - .flat_map(|s| s.iter().map(|(k, v)| (k.clone(), v.clone()))) - .collect(); + // A pod can be selected by several Services or temporarily appear in + // overlapping slices. Keep every membership until its last slice leaves. + let mut union: HashMap = HashMap::new(); + for (id, spec) in per_slice.values().flat_map(|slice| slice.iter()) { + union + .entry(id.clone()) + .and_modify(|worker| worker.services.extend(spec.services.iter().cloned())) + .or_insert_with(|| spec.clone()); + } for (id, spec) in &union { match prev_union.get(id) { @@ -223,6 +237,12 @@ async fn emit_diff( { tx.send(DiscoveryEvent::Removed { id: id.clone() }).await?; tx.send(DiscoveryEvent::Added(spec.clone())).await?; + } else if prev.services != spec.services { + tx.send(DiscoveryEvent::ServicesChanged { + id: id.clone(), + services: spec.services.clone(), + }) + .await?; } } None => { @@ -1181,6 +1201,112 @@ mod tests { assert_eq!(added[0].url, added[1].url); } + /// Service pools must survive pod replacement, and a shared pod must retain + /// its other Service when one EndpointSlice disappears. + #[tokio::test] + async fn service_membership_survives_replacement_and_merges_slices() { + use crate::buckets_reorg::{Bucket, BucketGroups, EngineGroup}; + use crate::discovery::ModelId; + use crate::policies_reorg::{power_of_two::PowerOfTwoPolicy, PickRequest, Stage}; + use crate::state::load_monitor::engine_reported_load::EngineReportedLoadTable; + use crate::workers::WorkerRegistry; + use std::sync::Arc; + + let slice = |uid: &str, pod: &str, namespace: &str, service: &str| { + let mut es = with_uid(make_slice_with_uids(&["10.0.0.1"], 30000, &[pod]), uid); + es.metadata.namespace = Some(namespace.into()); + es.metadata.labels = Some(BTreeMap::from([( + "kubernetes.io/service-name".into(), + service.into(), + )])); + es + }; + let old = slice("slice", "old", "ns", "short"); + let new = slice("slice", "new", "ns", "short"); + let other = slice("other-slice", "new", "ns", "other"); + let overlapping = slice("overlapping-slice", "new", "ns", "short"); + let (tx, mut rx) = mpsc::channel(16); + process_events( + futures::stream::iter(vec![ + Ok(watcher::Event::Apply(old)), + Ok(watcher::Event::Apply(new.clone())), + Ok(watcher::Event::Apply(other)), + Ok(watcher::Event::Apply(overlapping.clone())), + Ok(watcher::Event::Delete(new)), + Ok(watcher::Event::Delete(overlapping)), + ]), + tx, + plain_mode(), + None, + ) + .await; + let mut group = EngineGroup::new(Arc::new(PowerOfTwoPolicy::new( + EngineReportedLoadTable::new(), + ))); + group.worker_services = Some(["ns/short".into()].into()); + let bucket = Bucket::new("short", BucketGroups::Plain(group)); + let BucketGroups::Plain(group) = &bucket.groups else { + unreachable!() + }; + let registry = WorkerRegistry::default(); + let model = ModelId("m".into()); + let request = PickRequest::new(&model, Stage::Plain, 1); + // Same Service name in another namespace must not leak into the pool. + let mut foreign = extract_workers( + &slice("foreign", "foreign", "elsewhere", "short"), + Stage::Plain, + ) + .remove(0); + foreign.model_ids = vec![model.clone()]; + registry.add(foreign).unwrap(); + assert!(!bucket.has_ready_workers(®istry, &model)); + let mut selected = Vec::new(); + let mut membership_updates = Vec::new(); + while let Ok(event) = rx.try_recv() { + match event { + DiscoveryEvent::Added(mut spec) => { + spec.model_ids = vec![model.clone()]; + let spec_id = spec.id.0.clone(); + registry.add(spec).unwrap(); + selected.push(spec_id.clone()); + if spec_id == "ns/old" { + assert_eq!( + group.pick(®istry, &request).await.unwrap().engine.id.0, + "ns/old" + ); + } + assert!(bucket.has_ready_workers(®istry, &model)); + } + DiscoveryEvent::Removed { id } => { + registry.remove(&id); + assert_eq!( + group.pick(®istry, &request).await.unwrap().engine.id.0, + "ns/new" + ); + } + DiscoveryEvent::ServicesChanged { id, services } => { + membership_updates.push(services.clone()); + let worker = registry.get(&id).unwrap(); + worker.set_services(services); + } + _ => panic!("unexpected discovery event"), + } + } + assert_eq!(selected, ["ns/old", "ns/new"]); + assert_eq!( + membership_updates, + vec![ + ["ns/short".into(), "ns/other".into()].into(), + ["ns/other".into()].into(), + ] + ); + assert!(registry.get(&WorkerId("ns/old".into())).is_none()); + let worker = registry.get(&WorkerId("ns/new".into())).unwrap(); + assert_eq!(worker.services(), ["ns/other".into()].into()); + assert!(!bucket.has_ready_workers(®istry, &model)); + assert!(group.pick(®istry, &request).await.is_err()); + } + /// End-to-end reconcile: an EndpointSlice flips `ready=true` while the /// engine's `/server_info` is still failing (503) — the production /// race where K8s readiness (cheap `/health`) leads the diff --git a/experimental/sgl-router/src/discovery/types.rs b/experimental/sgl-router/src/discovery/types.rs index 9c19efd22a..4773e9fb6a 100644 --- a/experimental/sgl-router/src/discovery/types.rs +++ b/experimental/sgl-router/src/discovery/types.rs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; /// Opaque worker identifier. Wraps a string so callsites can't confuse it /// with other string types (e.g. `ModelId`). @@ -66,6 +67,10 @@ pub struct WorkerSpec { pub bootstrap_port: Option, #[serde(default)] pub version_group: Option, + /// Kubernetes Services selecting this worker, as namespace/name. Independent + /// of the pod-incarnation ID; empty for static URL discovery. + #[serde(default)] + pub services: BTreeSet, } /// Event produced by a discovery backend and consumed by `WorkerManager`. @@ -86,6 +91,11 @@ pub enum DiscoveryEvent { Removed { id: WorkerId, }, + /// Service membership changed without replacing the worker or its live state. + ServicesChanged { + id: WorkerId, + services: BTreeSet, + }, /// Used by the k8s backend when only the PD label flips (rare). ModeChanged { id: WorkerId, diff --git a/experimental/sgl-router/src/policies/dp_rank.rs b/experimental/sgl-router/src/policies/dp_rank.rs index 648e0c6107..d2b7903ba1 100644 --- a/experimental/sgl-router/src/policies/dp_rank.rs +++ b/experimental/sgl-router/src/policies/dp_rank.rs @@ -60,6 +60,7 @@ mod tests { model_ids: vec![ModelId("m".into())], bootstrap_port: None, version_group: None, + services: Default::default(), }; let profile = EngineProfile { protocol: WireProtocol::default(), diff --git a/experimental/sgl-router/src/policies/factory.rs b/experimental/sgl-router/src/policies/factory.rs index 7963053c78..1392bee831 100644 --- a/experimental/sgl-router/src/policies/factory.rs +++ b/experimental/sgl-router/src/policies/factory.rs @@ -343,6 +343,8 @@ mod tests { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, diff --git a/experimental/sgl-router/src/policies_reorg/admission.rs b/experimental/sgl-router/src/policies_reorg/admission.rs index 854688a1d7..4368d2d0cf 100644 --- a/experimental/sgl-router/src/policies_reorg/admission.rs +++ b/experimental/sgl-router/src/policies_reorg/admission.rs @@ -25,8 +25,10 @@ pub enum Decision { #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct EngineMetrics { pub running_requests: Option, + pub running_capacity: Option, pub waiting_requests: Option, pub kv_tokens: Option, + pub kv_capacity: Option, pub pending_prefill_tokens: Option, pub inflight_requests: u64, } @@ -36,10 +38,16 @@ impl EngineMetrics { pub fn observe(engine: &Worker, load: &EngineReportedLoadSnapshot) -> Self { let basic = load.fresh_load_for_url(&engine.url); let native = load.fresh_native_cache_load_for_url(&engine.url); + let capacity = |max: u64| (max > 0).then_some(max); Self { - running_requests: basic.map(|load| load.num_running_reqs), + // Native first, so the count covers the ranks `running_capacity` sums. + running_requests: native + .map(|load| load.num_running_reqs) + .or(basic.map(|load| load.num_running_reqs)), + running_capacity: native.and_then(|load| capacity(load.max_running_requests)), waiting_requests: basic.map(|load| load.num_waiting_reqs), kv_tokens: native.map(|load| load.num_total_tokens), + kv_capacity: native.and_then(|load| capacity(load.max_total_num_tokens)), pending_prefill_tokens: native.map(|load| load.num_waiting_uncached_tokens), inflight_requests: engine.router_inflight_load() as u64, } @@ -52,33 +60,66 @@ pub trait EngineAdmission: Send + Sync + Debug { fn check(&self, engine: &Worker, metrics: &EngineMetrics) -> Result; } -/// Per-engine caps; an unset limit is not checked. A limit admits while the -/// metric is below it. Unknown engine metrics fail open. The default allows -/// everything. Checks observe load; they do not reserve capacity. -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +/// Per-engine caps; an unset limit is not checked and unknown metrics fail open. +/// Each admits while the engine's load is below it: counts directly, usages as +/// shares, in (0, 1], of the engine's reported capacity. Checks observe load; +/// they do not reserve capacity, and the request itself may take an engine past +/// a cap. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct AdmissionLimits { - pub max_running_requests: Option, + pub max_running_usage: Option, + pub max_kv_usage: Option, pub max_waiting_requests: Option, - pub max_kv_tokens: Option, pub max_pending_prefill_tokens: Option, pub max_inflight_requests: Option, } +impl AdmissionLimits { + /// Rejects usages outside (0, 1] and zero counts, which would admit nothing. + pub fn validate(&self) -> Result<(), PickError> { + let share = |usage: Option| usage.is_none_or(|u| u > 0.0 && u <= 1.0); + let count = |cap: Option| cap != Some(0); + if !(share(self.max_running_usage) && share(self.max_kv_usage)) { + return Err(PickError::InvalidConfiguration( + "admission usages must be in (0, 1]".into(), + )); + } + if !(count(self.max_waiting_requests) + && count(self.max_pending_prefill_tokens) + && count(self.max_inflight_requests)) + { + return Err(PickError::InvalidConfiguration( + "admission counts must be positive".into(), + )); + } + Ok(()) + } + + /// These limits, with each unset one taken from `defaults`. + pub fn or(&self, defaults: &Self) -> Self { + Self { + max_running_usage: self.max_running_usage.or(defaults.max_running_usage), + max_kv_usage: self.max_kv_usage.or(defaults.max_kv_usage), + max_waiting_requests: self.max_waiting_requests.or(defaults.max_waiting_requests), + max_pending_prefill_tokens: self + .max_pending_prefill_tokens + .or(defaults.max_pending_prefill_tokens), + max_inflight_requests: self + .max_inflight_requests + .or(defaults.max_inflight_requests), + } + } +} + impl EngineAdmission for AdmissionLimits { fn check(&self, _: &Worker, engine: &EngineMetrics) -> Result { - let limits = [ - ( - "max_running_requests", - self.max_running_requests, - engine.running_requests, - ), + let counts = [ ( "max_waiting_requests", self.max_waiting_requests, engine.waiting_requests, ), - ("max_kv_tokens", self.max_kv_tokens, engine.kv_tokens), ( "max_pending_prefill_tokens", self.max_pending_prefill_tokens, @@ -90,13 +131,36 @@ impl EngineAdmission for AdmissionLimits { Some(engine.inflight_requests), ), ]; - for (name, max, current) in limits { + for (name, max, current) in counts { if let (Some(max), Some(current)) = (max, current) { if current >= max { return Ok(Decision::Reject(name.into())); } } } + let usages = [ + ( + "max_running_usage", + self.max_running_usage, + engine.running_requests, + engine.running_capacity, + ), + ( + "max_kv_usage", + self.max_kv_usage, + engine.kv_tokens, + engine.kv_capacity, + ), + ]; + for (name, share, used, capacity) in usages { + if let (Some(share), Some(used), Some(capacity)) = (share, used, capacity) { + // Dividing exact integers lands on the share itself at the + // boundary; multiplying the share can round to either side. + if used as f64 / capacity as f64 >= share { + return Ok(Decision::Reject(name.into())); + } + } + } Ok(Decision::Allow) } } diff --git a/experimental/sgl-router/src/policies_reorg/factory.rs b/experimental/sgl-router/src/policies_reorg/factory.rs index f25b07f3d5..62da5a875f 100644 --- a/experimental/sgl-router/src/policies_reorg/factory.rs +++ b/experimental/sgl-router/src/policies_reorg/factory.rs @@ -1,12 +1,19 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 The SGLang Authors // SPDX-License-Identifier: Apache-2.0 +use std::collections::HashSet; use std::{sync::Arc, time::Duration}; use anyhow::{bail, ensure, Result}; +use serde::Deserialize; -use crate::buckets_reorg::{Bucket, BucketGroups, BucketResolver, EngineGroup}; -use crate::config::{DecodePolicyKind, FilterKind, ModelConfig, PolicyKind, SessionAffinityMode}; +use crate::buckets_reorg::{ + Bucket, BucketGroups, BucketResolver, EngineGroup, SloPreference, TokenLimits, +}; +use crate::config::{ + AffinityConfig, DecodePolicyKind, FilterKind, ModelConfig, PolicyKind, SessionAffinityMode, +}; +use crate::discovery::WorkerId; use crate::state::kv_events::RadixTreePrefixProvider; use crate::state::{ kv_events::KvEventIndex, load_monitor::router_inflight_load::JanitorHandle, AffinityStore, @@ -17,9 +24,72 @@ use super::{ cache_aware::{CacheAwarePolicy, CacheSource}, power_of_two::PowerOfTwoPolicy, session_aware::SessionAwarePolicy, - Policy, + Policy, Stage, }; +/// Reorg `--bucket-config`: plain or P/D buckets whose groups each own their +/// membership, policy and admission. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct BucketsConfig { + pub buckets: Vec, + pub ttft_slo: SloPreference, + pub tps_slo: SloPreference, +} + +/// Set either `plain` or both `prefill` and `decode`. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct BucketSpec { + pub id: String, + pub rank: u32, + pub min_input_tokens: Option, + pub max_input_tokens: Option, + pub max_context_tokens: Option, + pub ttft_ms: Option, + pub tokens_per_second: Option, + pub plain: Option, + pub prefill: Option, + pub decode: Option, +} + +/// Omitted fields mean every engine of the role and `--policy` (power-of-two on +/// decode); admission limits left unset take `--max-in-flight` / `--max-kv-usage`. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct GroupSpec { + pub worker_ids: Option>, + /// Any listed Kubernetes Service, as namespace/name; exclusive with worker_ids. + pub worker_services: Option>, + pub policy: Option, + pub admission: Option, +} + +impl BucketsConfig { + /// Discovery decides which bucket has candidates. Plain ranks first so plain + /// deployments do not scan for prefill engines on every request. + fn default_buckets() -> Self { + let all = || Some(GroupSpec::default()); + Self { + buckets: vec![ + BucketSpec { + id: "plain".into(), + plain: all(), + ..Default::default() + }, + BucketSpec { + id: "pd".into(), + rank: 1, + prefill: all(), + decode: all(), + ..Default::default() + }, + ], + ..Default::default() + } + } +} + pub fn validate(model: &ModelConfig) -> Result<()> { ensure!( matches!( @@ -30,7 +100,7 @@ pub fn validate(model: &ModelConfig) -> Result<()> { ); ensure!( model.bucket_config.is_none(), - "legacy --bucket-config cannot define complete reorg buckets" + "reorg routing reads reorg_buckets, not the legacy bucket_config" ); ensure!( model.decode_policy == DecodePolicyKind::PowerOfTwo, @@ -58,39 +128,174 @@ pub fn validate(model: &ModelConfig) -> Result<()> { Ok(()) } -/// Build the default plain and PD buckets. Callers run [`validate`] first; -/// `Cli::into_config` does so before startup reaches this point. +/// Build `model.reorg_buckets`, or the default plain and P/D buckets. Callers +/// run [`validate`] first; `Cli::into_config` does so before startup reaches this point. pub fn build_resolver( model: &ModelConfig, state: &KvEventIndex, external_index: Option>, ) -> Result<(BucketResolver, Option)> { - let admission = Arc::new(AdmissionLimits { - max_inflight_requests: model - .eligibility - .as_ref() - .and_then(|e| e.max_in_flight) - .map(|n| n as u64), - ..Default::default() - }); - let mut decode = PowerOfTwoPolicy::new(state.engine_reported_load()); - decode.admission = admission.clone(); - let decode: Arc = Arc::new(decode); - let affinity = model.affinity.clone().unwrap_or_default(); - let mut cleanup = None; - let policy: Arc = match model.policy { - PolicyKind::PowerOfTwo => decode.clone(), - PolicyKind::SessionAware => { - let store = AffinityStore::new(Duration::from_secs(affinity.session_idle_secs)); - cleanup = - store.spawn_sweeper(Duration::from_secs(affinity.session_eviction_interval_secs)); - let mut policy = SessionAwarePolicy::new(store, state.engine_reported_load()); - policy.admission = admission; - policy.config = affinity; - Arc::new(policy) + let mut groups = Groups { + model, + state, + external_index, + affinity: model.affinity.clone().unwrap_or_default(), + store: None, + cleanup: None, + source: None, + }; + let default_buckets; + let config = match &model.reorg_buckets { + Some(config) => config, + None => { + default_buckets = BucketsConfig::default_buckets(); + &default_buckets } - PolicyKind::CacheAware => { - let source = match external_index { + }; + ensure!(!config.buckets.is_empty(), "--bucket-config has no buckets"); + let mut ids = HashSet::new(); + let mut buckets = Vec::new(); + for spec in &config.buckets { + let id = &spec.id; + ensure!( + !id.is_empty() && ids.insert(id), + "bucket id {id:?} must be non-empty and unique" + ); + ensure!( + spec.min_input_tokens + .zip(spec.max_input_tokens) + .is_none_or(|(min, max)| min <= max) + && spec.max_context_tokens != Some(0) + && (spec.min_input_tokens) + .zip(spec.max_context_tokens) + .is_none_or(|(min, context)| min <= context) + && spec.ttft_ms != Some(0) + && spec + .tokens_per_second + .is_none_or(|t| t.is_finite() && t > 0.0), + "bucket {id:?} needs min input tokens <= max input and context tokens, \ + and positive capacity and SLO estimates" + ); + let bucket_groups = match (&spec.plain, &spec.prefill, &spec.decode) { + (Some(plain), None, None) => { + BucketGroups::Plain(groups.build(id, Stage::Plain, plain)?) + } + (None, Some(prefill), Some(decode)) => BucketGroups::Pd { + prefill: groups.build(id, Stage::Prefill, prefill)?, + decode: groups.build(id, Stage::Decode, decode)?, + }, + _ => bail!("bucket {id:?} needs either plain or both prefill and decode"), + }; + let mut bucket = Bucket::new(id.clone(), bucket_groups); + bucket.rank = spec.rank; + bucket.limits = TokenLimits { + min: spec.min_input_tokens, + max: spec.max_input_tokens, + }; + bucket.max_context_tokens = spec.max_context_tokens; + bucket.ttft_ms = spec.ttft_ms; + bucket.tokens_per_second = spec.tokens_per_second; + buckets.push(bucket); + } + let mut resolver = BucketResolver::new(buckets)?; + resolver.ttft_slo = config.ttft_slo; + resolver.tps_slo = config.tps_slo; + Ok((resolver, groups.cleanup)) +} + +/// Builds group policies; session stores and cache sources are shared by all groups. +struct Groups<'a> { + model: &'a ModelConfig, + state: &'a KvEventIndex, + external_index: Option>, + affinity: AffinityConfig, + store: Option>, + cleanup: Option, + source: Option>, +} + +impl Groups<'_> { + fn build(&mut self, bucket: &str, stage: Stage, spec: &GroupSpec) -> Result { + let default = match stage { + Stage::Decode => PolicyKind::PowerOfTwo, + _ => self.model.policy, + }; + let kind = spec.policy.unwrap_or(default); + // Only --policy has its affinity, cache and tokenizer settings resolved. + ensure!( + kind == PolicyKind::PowerOfTwo || kind == self.model.policy, + "bucket groups use power_of_two or --policy, not {kind:?}" + ); + ensure!( + spec.worker_ids.as_ref().is_none_or(|ids| { + !ids.is_empty() && ids.iter().all(|id| !id.0.trim().is_empty()) + }), + "bucket {bucket:?} {stage:?} worker_ids and their values must not be empty; omit it for every engine" + ); + ensure!( + spec.worker_ids.is_none() || spec.worker_services.is_none(), + "bucket {bucket:?} {stage:?} must use either worker_ids or worker_services" + ); + ensure!( + spec.worker_services.as_ref().is_none_or(|services| { + !services.is_empty() && services.iter().all(|service| { + service.split_once('/').is_some_and(|(namespace, name)| { + !namespace.trim().is_empty() && !name.trim().is_empty() + && !name.contains('/') && !service.chars().any(char::is_whitespace) + }) + }) + }), + "bucket {bucket:?} {stage:?} worker_services must be a nonempty list of namespace/service names" + ); + let defaults = &self.model.reorg_admission; + let admission = spec + .admission + .as_ref() + .map_or(defaults.clone(), |a| a.or(defaults)); + admission.validate()?; + let admission = Arc::new(admission); + let load = self.state.engine_reported_load(); + let policy: Arc = match kind { + PolicyKind::PowerOfTwo => { + let mut policy = PowerOfTwoPolicy::new(load); + policy.admission = admission; + Arc::new(policy) + } + PolicyKind::SessionAware => { + let mut policy = SessionAwarePolicy::new(self.store(), load); + policy.admission = admission; + policy.config = self.affinity.clone(); + Arc::new(policy) + } + PolicyKind::CacheAware => { + let mut policy = CacheAwarePolicy::new(self.source(), load, self.affinity.clone())?; + policy.admission = admission; + Arc::new(policy) + } + other => bail!("reorg routing does not implement --policy {other:?}"), + }; + Ok(EngineGroup { + worker_ids: spec.worker_ids.clone(), + worker_services: spec.worker_services.clone(), + policy, + }) + } + + fn store(&mut self) -> Arc { + let affinity = &self.affinity; + let cleanup = &mut self.cleanup; + Arc::clone(self.store.get_or_insert_with(|| { + let store = AffinityStore::new(Duration::from_secs(affinity.session_idle_secs)); + *cleanup = + store.spawn_sweeper(Duration::from_secs(affinity.session_eviction_interval_secs)); + store + })) + } + + fn source(&mut self) -> Arc { + let (state, index) = (self.state, self.external_index.clone()); + Arc::clone(self.source.get_or_insert_with(|| { + Arc::new(match index { Some(index) => CacheSource::Remote { index, block_size: state.block_size_oracle(), @@ -99,28 +304,7 @@ pub fn build_resolver( state.tree(), state.block_size_oracle(), )), - }; - let mut policy = - CacheAwarePolicy::new(Arc::new(source), state.engine_reported_load(), affinity)?; - policy.admission = admission; - Arc::new(policy) - } - other => bail!("reorg routing does not implement --policy {other:?}"), - }; - // Discovery determines which serving mode has candidates. Rank the plain - // bucket first so plain deployments do not scan for prefill engines on - // every request; buckets otherwise tie and would sort by ID ("pd" first). - let mut pd = Bucket::new( - "pd", - BucketGroups::Pd { - prefill: EngineGroup::new(policy.clone()), - decode: EngineGroup::new(decode), - }, - ); - pd.rank = 1; - let resolver = BucketResolver::new(vec![ - Bucket::new("plain", BucketGroups::Plain(EngineGroup::new(policy))), - pd, - ])?; - Ok((resolver, cleanup)) + }) + })) + } } diff --git a/experimental/sgl-router/src/server/app_context.rs b/experimental/sgl-router/src/server/app_context.rs index a8d63405ae..94fbaedc6b 100644 --- a/experimental/sgl-router/src/server/app_context.rs +++ b/experimental/sgl-router/src/server/app_context.rs @@ -218,6 +218,8 @@ impl AppContext { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, diff --git a/experimental/sgl-router/src/server/routes/models.rs b/experimental/sgl-router/src/server/routes/models.rs index 2985837ed2..291e5881eb 100644 --- a/experimental/sgl-router/src/server/routes/models.rs +++ b/experimental/sgl-router/src/server/routes/models.rs @@ -56,6 +56,8 @@ mod tests { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, diff --git a/experimental/sgl-router/src/server/routes/tokenize.rs b/experimental/sgl-router/src/server/routes/tokenize.rs index cbb13c0d03..aa83c3fbf1 100644 --- a/experimental/sgl-router/src/server/routes/tokenize.rs +++ b/experimental/sgl-router/src/server/routes/tokenize.rs @@ -130,6 +130,8 @@ mod tests { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, diff --git a/experimental/sgl-router/src/tokenizer/mod.rs b/experimental/sgl-router/src/tokenizer/mod.rs index f9af2ce276..9d8dd619bf 100644 --- a/experimental/sgl-router/src/tokenizer/mod.rs +++ b/experimental/sgl-router/src/tokenizer/mod.rs @@ -245,6 +245,8 @@ mod tests { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, diff --git a/experimental/sgl-router/src/workers/manager.rs b/experimental/sgl-router/src/workers/manager.rs index 7b99cd3896..474bde25a8 100644 --- a/experimental/sgl-router/src/workers/manager.rs +++ b/experimental/sgl-router/src/workers/manager.rs @@ -355,6 +355,14 @@ async fn handle_discovery_event( al.forget_worker(&id); } } + DiscoveryEvent::ServicesChanged { id, services } => { + if let Some(prev) = pending.remove(&id) { + let _ = prev.await; + } + if let Some(worker) = registry.get(&id) { + worker.set_services(services); + } + } DiscoveryEvent::ModeChanged { id, mode } => { if let Some(prev) = pending.remove(&id) { // Same rationale as Removed: wait for the registry @@ -443,6 +451,7 @@ fn reconcile_unresolved_workers( model_ids: worker.model_ids.clone(), bootstrap_port: worker.bootstrap_port(), version_group: worker.version_group().map(str::to_owned), + services: worker.services(), }; // `debug!` not `info!`: this fires every interval for each // still-unresolved worker, so info-level would spam for one that is @@ -628,6 +637,8 @@ mod tests { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: Some(RawCbConfig { threshold: NonZeroU32::new(threshold).unwrap(), cool_down_secs, @@ -1293,6 +1304,7 @@ mod tests { model_ids: vec![model.clone()], bootstrap_port: None, version_group: Some("v1".into()), + services: ["ns/prefill".into()].into(), })) .await .unwrap(); @@ -1315,6 +1327,10 @@ mod tests { .unwrap(); assert_eq!(registry.healthy_workers_for(&model).len(), 1); assert_eq!(registry.get(&id).unwrap().version_group(), Some("v1")); + assert_eq!( + registry.get(&id).unwrap().services(), + ["ns/prefill".into()].into() + ); drop(tx); manager.await.unwrap(); } diff --git a/experimental/sgl-router/src/workers/worker.rs b/experimental/sgl-router/src/workers/worker.rs index 17b0191981..fc140b29ee 100644 --- a/experimental/sgl-router/src/workers/worker.rs +++ b/experimental/sgl-router/src/workers/worker.rs @@ -3,9 +3,9 @@ use crate::discovery::{ModelId, WorkerId, WorkerMode}; use crate::health::circuit_breaker::{CircuitBreaker, CircuitBreakerConfig}; -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap, HashSet}; use std::sync::atomic::{AtomicU64, AtomicU8, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, RwLock}; use std::time::{Duration, Instant}; /// How long a prefill stays unroutable, after joining its model pool, while @@ -221,6 +221,7 @@ pub struct Worker { /// PD pairing scope; carried from `WorkerSpec`. See /// [`crate::discovery::WorkerSpec`]. version_group: Option, + services: RwLock>, /// Router in-flight requests per DP rank; one slot per rank. dp_rank_inflight: Arc<[AtomicUsize]>, } @@ -259,10 +260,27 @@ impl Worker { bootstrap_port: spec.bootstrap_port, pooled_at: tokio::time::Instant::now(), version_group: spec.version_group, + services: RwLock::new(spec.services), dp_rank_inflight: (0..dp_ranks.max(1)).map(|_| AtomicUsize::new(0)).collect(), } } + pub fn services(&self) -> BTreeSet { + self.services.read().unwrap().clone() + } + + pub fn matches_services(&self, services: &HashSet) -> bool { + self.services + .read() + .unwrap() + .iter() + .any(|s| services.contains(s)) + } + + pub(crate) fn set_services(&self, services: BTreeSet) { + *self.services.write().unwrap() = services; + } + /// Hostname carried on PD-disagg request bodies as `bootstrap_host`. pub fn bootstrap_host(&self) -> &str { &self.bootstrap_host @@ -377,7 +395,7 @@ pub fn paired_prefills( mut prefills: Vec>, decoders: &[Arc], ) -> Vec> { - let groups: std::collections::HashSet<_> = decoders.iter().map(|d| d.version_group()).collect(); + let groups: HashSet<_> = decoders.iter().map(|d| d.version_group()).collect(); prefills.retain(|p| groups.contains(&p.version_group())); prefills } diff --git a/experimental/sgl-router/tests/component/discovery/static_urls.rs b/experimental/sgl-router/tests/component/discovery/static_urls.rs index 7f79d40a6d..f67b2a8d87 100644 --- a/experimental/sgl-router/tests/component/discovery/static_urls.rs +++ b/experimental/sgl-router/tests/component/discovery/static_urls.rs @@ -137,6 +137,8 @@ async fn static_urls_pd_role_resolved_end_to_end() { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, diff --git a/experimental/sgl-router/tests/component/policies_reorg.rs b/experimental/sgl-router/tests/component/policies_reorg.rs index f7567b5920..7b2f6dfeca 100644 --- a/experimental/sgl-router/tests/component/policies_reorg.rs +++ b/experimental/sgl-router/tests/component/policies_reorg.rs @@ -114,6 +114,7 @@ fn registry() -> Arc { fn group(members: &[&str], policy: Arc) -> EngineGroup { EngineGroup { + worker_services: None, worker_ids: Some(members.iter().map(|id| WorkerId((*id).into())).collect()), policy, } diff --git a/experimental/sgl-router/tests/component/policies_reorg_admission.rs b/experimental/sgl-router/tests/component/policies_reorg_admission.rs index 2f7412af51..ee3a34acaf 100644 --- a/experimental/sgl-router/tests/component/policies_reorg_admission.rs +++ b/experimental/sgl-router/tests/component/policies_reorg_admission.rs @@ -49,12 +49,12 @@ fn reject(name: &str) -> Decision { #[test] fn limits_are_flat_optional_fields() { let limits: AdmissionLimits = - serde_json::from_value(json!({"max_inflight_requests": 4, "max_kv_tokens": 100})).unwrap(); + serde_json::from_value(json!({"max_inflight_requests": 4, "max_kv_usage": 0.9})).unwrap(); assert_eq!( limits, AdmissionLimits { max_inflight_requests: Some(4), - max_kv_tokens: Some(100), + max_kv_usage: Some(0.9), ..Default::default() } ); @@ -66,14 +66,13 @@ fn limits_are_flat_optional_fields() { } #[test] -fn each_limit_caps_its_metric_and_fails_open_when_unknown() { +fn each_count_caps_its_metric_and_fails_open_when_unknown() { let engine = engine(); let known = EngineMetrics { - running_requests: Some(3), waiting_requests: Some(1), - kv_tokens: Some(80), pending_prefill_tokens: Some(90), inflight_requests: 2, + ..Default::default() }; let unknown = EngineMetrics { inflight_requests: 2, @@ -82,9 +81,7 @@ fn each_limit_caps_its_metric_and_fails_open_when_unknown() { let limit = |field: &str, max| { let mut limits = AdmissionLimits::default(); *match field { - "max_running_requests" => &mut limits.max_running_requests, "max_waiting_requests" => &mut limits.max_waiting_requests, - "max_kv_tokens" => &mut limits.max_kv_tokens, "max_pending_prefill_tokens" => &mut limits.max_pending_prefill_tokens, "max_inflight_requests" => &mut limits.max_inflight_requests, _ => unreachable!(), @@ -96,9 +93,7 @@ fn each_limit_caps_its_metric_and_fails_open_when_unknown() { Decision::Allow ); for (field, below, at) in [ - ("max_running_requests", 4, 3), ("max_waiting_requests", 2, 1), - ("max_kv_tokens", 81, 80), ("max_pending_prefill_tokens", 91, 90), ("max_inflight_requests", 3, 2), ] { @@ -125,8 +120,10 @@ async fn metrics_come_from_the_selection_snapshot_and_live_inflight_count() { EngineMetrics::observe(&engine, &table.capture_snapshot(Instant::now())), EngineMetrics { running_requests: Some(1), + running_capacity: Some(100), waiting_requests: Some(2), kv_tokens: Some(80), + kv_capacity: Some(1000), pending_prefill_tokens: Some(5), inflight_requests: 1, } @@ -150,17 +147,18 @@ async fn metrics_come_from_the_selection_snapshot_and_live_inflight_count() { let mut policy = PowerOfTwoPolicy::new(table.clone()); policy.admission = Arc::new(AdmissionLimits { - max_running_requests: Some(2), - max_kv_tokens: Some(100), + max_running_usage: Some(0.02), + max_kv_usage: Some(0.1), ..Default::default() }); + let engines = [engine]; let model = ModelId("m".into()); let request = PickRequest::new(&model, Stage::Plain, 10); - let engines = [engine]; + // Capacities are 100 running requests and 1000 KV tokens. for (running, kv_tokens, rejection) in [ - (1, 100, Some("max_kv_tokens")), + (1, 100, Some("max_kv_usage")), (1, 99, None), - (2, 0, Some("max_running_requests")), + (2, 0, Some("max_running_usage")), ] { table.set( &engines[0].url, @@ -178,3 +176,85 @@ async fn metrics_come_from_the_selection_snapshot_and_live_inflight_count() { } } } + +#[test] +fn usages_admit_below_the_share_and_fail_open_without_capacity() { + let limits = AdmissionLimits { + max_running_usage: Some(0.9), + max_kv_usage: Some(0.9), + ..Default::default() + }; + let metrics = |running, kv_tokens, capacity: Option| EngineMetrics { + running_requests: Some(running), + running_capacity: capacity.map(|_| 10), + kv_tokens: Some(kv_tokens), + kv_capacity: capacity, + ..Default::default() + }; + let check = |m| limits.check(&engine(), &m).unwrap(); + assert_eq!(check(metrics(8, 899, Some(1000))), Decision::Allow); + assert_eq!( + check(metrics(9, 0, Some(1000))), + reject("max_running_usage") + ); + assert_eq!(check(metrics(0, 900, Some(1000))), reject("max_kv_usage")); + assert_eq!(check(metrics(9, 900, None)), Decision::Allow); + let kv = |share, kv_tokens| { + let limits = AdmissionLimits { + max_kv_usage: Some(share), + ..Default::default() + }; + let metrics = EngineMetrics { + kv_tokens: Some(kv_tokens), + kv_capacity: Some(100), + ..Default::default() + }; + limits.check(&engine(), &metrics).unwrap() + }; + // A full share still admits one more request below it, whatever its size. + assert_eq!(kv(1.0, 99), Decision::Allow); + assert_eq!(kv(1.0, 100), reject("max_kv_usage")); + // `0.07 * 100.0` rounds above 7; the boundary still rejects exactly at the share. + assert_eq!(kv(0.07, 6), Decision::Allow); + assert_eq!(kv(0.07, 7), reject("max_kv_usage")); +} + +#[test] +fn validation_rejects_out_of_range_usages_and_zero_counts() { + for bad in [ + json!({"max_kv_usage": 1.5}), + json!({"max_running_usage": 0.0}), + json!({"max_waiting_requests": 0}), + json!({"max_pending_prefill_tokens": 0}), + json!({"max_inflight_requests": 0}), + ] { + let limits: AdmissionLimits = serde_json::from_value(bad.clone()).unwrap(); + assert!(limits.validate().is_err(), "accepted {bad}"); + } + let ok: AdmissionLimits = + serde_json::from_value(json!({"max_kv_usage": 1.0, "max_inflight_requests": 1})).unwrap(); + assert!(ok.validate().is_ok()); +} + +#[test] +fn group_limits_override_defaults_field_by_field() { + let defaults = AdmissionLimits { + max_inflight_requests: Some(64), + max_kv_usage: Some(0.95), + ..Default::default() + }; + let group = AdmissionLimits { + max_kv_usage: Some(0.9), + max_waiting_requests: Some(8), + ..Default::default() + }; + assert_eq!( + group.or(&defaults), + AdmissionLimits { + max_inflight_requests: Some(64), + max_kv_usage: Some(0.9), + max_waiting_requests: Some(8), + ..Default::default() + } + ); +} diff --git a/experimental/sgl-router/tests/component/tokenizer/render_parity.rs b/experimental/sgl-router/tests/component/tokenizer/render_parity.rs index 28dfe3edbf..747c1c0388 100644 --- a/experimental/sgl-router/tests/component/tokenizer/render_parity.rs +++ b/experimental/sgl-router/tests/component/tokenizer/render_parity.rs @@ -118,6 +118,8 @@ fn registry(model_id: &str, tokenizer_path: PathBuf) -> TokenizerRegistry { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, affinity: None, diff --git a/experimental/sgl-router/tests/component/workers/manager.rs b/experimental/sgl-router/tests/component/workers/manager.rs index 8bc39ec5e4..470f770c33 100644 --- a/experimental/sgl-router/tests/component/workers/manager.rs +++ b/experimental/sgl-router/tests/component/workers/manager.rs @@ -905,3 +905,50 @@ async fn reconcile_recovers_worker_with_unresolved_model_ids() { h.await.unwrap(); let _ = shutdown_tx.send(()); } + +/// Membership updates race initial introspection and must update the live +/// worker without resetting its in-flight accounting or circuit breaker. +#[tokio::test] +async fn service_membership_updates_preserve_live_worker_state() { + let (url, _shutdown) = spawn_fake_worker(json!({"served_model_name": "m"})).await; + let (tx, rx) = mpsc::channel(16); + let registry = Arc::new(WorkerRegistry::default()); + let handle = tokio::spawn(manager::run(rx, registry.clone())); + let spec = spec_for("w", &url, WorkerMode::Plain); + let id = spec.id.clone(); + tx.send(DiscoveryEvent::Added(spec)).await.unwrap(); + // This must wait for registration, rather than losing the membership. + tx.send(DiscoveryEvent::ServicesChanged { + id: id.clone(), + services: ["ns/short".into()].into(), + }) + .await + .unwrap(); + wait_until( + || { + registry + .get(&id) + .is_some_and(|w| w.services().contains("ns/short")) + }, + "initial service membership", + ) + .await; + let worker = registry.get(&id).unwrap(); + let _guard = worker.load_guard(); + tx.send(DiscoveryEvent::ServicesChanged { + id: id.clone(), + services: ["ns/long".into()].into(), + }) + .await + .unwrap(); + wait_until( + || worker.services().contains("ns/long"), + "changed service membership", + ) + .await; + assert!(!worker.services().contains("ns/short")); + assert!(Arc::ptr_eq(&worker, ®istry.get(&id).unwrap())); + assert_eq!(worker.router_inflight_load(), 1); + drop(tx); + handle.await.unwrap(); +} diff --git a/experimental/sgl-router/tests/proxy/bucket_routing.rs b/experimental/sgl-router/tests/proxy/bucket_routing.rs index 0fd4de16aa..706625b999 100644 --- a/experimental/sgl-router/tests/proxy/bucket_routing.rs +++ b/experimental/sgl-router/tests/proxy/bucket_routing.rs @@ -67,6 +67,8 @@ fn build_app_context( decode_policy: Default::default(), dp_aware: false, bucket_config: Some(bucket_config), + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, diff --git a/experimental/sgl-router/tests/proxy/chat_routing.rs b/experimental/sgl-router/tests/proxy/chat_routing.rs index ddf439ea56..2bff090b14 100644 --- a/experimental/sgl-router/tests/proxy/chat_routing.rs +++ b/experimental/sgl-router/tests/proxy/chat_routing.rs @@ -46,6 +46,8 @@ fn config_for(_worker_url: &str) -> Config { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, diff --git a/experimental/sgl-router/tests/proxy/chat_routing/reorg.rs b/experimental/sgl-router/tests/proxy/chat_routing/reorg.rs index 377fde4a8a..910c472c59 100644 --- a/experimental/sgl-router/tests/proxy/chat_routing/reorg.rs +++ b/experimental/sgl-router/tests/proxy/chat_routing/reorg.rs @@ -94,6 +94,7 @@ fn rejecting_policy() -> Arc { fn group(id: &str, policy: Arc) -> EngineGroup { EngineGroup { + worker_services: None, worker_ids: Some([WorkerId(id.into())].into_iter().collect()), policy, } @@ -148,41 +149,44 @@ fn body(content: &str) -> serde_json::Value { } #[tokio::test] -async fn configured_limits_reject_before_dispatch_and_admit_after_load_drops() { - use sgl_router::policies_reorg::power_of_two::PowerOfTwoPolicy; +async fn bucket_config_limits_reject_before_dispatch_and_admit_after_load_drops() { + use sgl_router::policies_reorg::factory::build_resolver; + use sgl_router::state::kv_events::KvEventIndex; use sgl_router::state::load_monitor::engine_reported_load::{LoadStat, NativeCacheRankLoad}; use std::time::Instant; let worker = MockWorker::start(vec![]).await; let mut ctx = Arc::try_unwrap(context(&[("w", Stage::Plain, &worker)], vec![])) .unwrap_or_else(|_| panic!("context is not shared yet")); - let mut policy = PowerOfTwoPolicy::new(ctx.engine_reported_load.clone()); - policy.admission = Arc::new(AdmissionLimits { - max_running_requests: Some(1), - max_kv_tokens: Some(100), - ..Default::default() - }); - ctx.chat_routing = ChatRouting::Reorg( - [( - ModelId("tiny".into()), - BucketResolver::new(vec![Bucket::new( - "default", - BucketGroups::Plain(EngineGroup { - worker_ids: Some([WorkerId("w".into())].into()), - policy: Arc::new(policy), - }), - )]) - .unwrap(), - )] - .into(), + let state = KvEventIndex::new(); + ctx.engine_reported_load = state.engine_reported_load(); + ctx.config.model.policy = PolicyKind::PowerOfTwo; + // The group sets its usages; the CLI in-flight default still applies. + ctx.config.model.reorg_admission.max_inflight_requests = Some(1); + ctx.config.model.reorg_buckets = Some( + serde_json::from_value(serde_json::json!({"buckets": [{ + "id": "default", + "plain": { + "worker_ids": ["w"], + "admission": {"max_running_usage": 0.1, "max_kv_usage": 0.1} + } + }]})) + .unwrap(), ); + let (resolver, _) = build_resolver(&ctx.config.model, &state, None).unwrap(); + ctx.chat_routing = ChatRouting::Reorg([(ModelId("tiny".into()), resolver)].into()); let ctx = Arc::new(ctx); + let engine = ctx.registry.get(&WorkerId("w".into())).unwrap(); let app = build_router(ctx.clone()); - for (running, kv_tokens, expected) in [ - (1, 0, StatusCode::SERVICE_UNAVAILABLE), - (0, 100, StatusCode::SERVICE_UNAVAILABLE), - (0, 0, StatusCode::OK), + for (running, kv_tokens, inflight, expected) in [ + (1, 0, 0, StatusCode::SERVICE_UNAVAILABLE), + (0, 100, 0, StatusCode::SERVICE_UNAVAILABLE), + (0, 0, 1, StatusCode::SERVICE_UNAVAILABLE), + (0, 0, 0, StatusCode::OK), ] { + engine + .active_requests + .store(inflight, std::sync::atomic::Ordering::Relaxed); ctx.engine_reported_load.set( &worker.url, 0, @@ -670,6 +674,7 @@ async fn cache_aware_routes_tokenized_prompt_and_rechecks_the_next_bucket() { let mut first = Bucket::new( "first", BucketGroups::Plain(EngineGroup { + worker_services: None, worker_ids: Some([WorkerId("rejected".into())].into_iter().collect()), policy: Arc::new(rejecting), }), @@ -678,6 +683,7 @@ async fn cache_aware_routes_tokenized_prompt_and_rechecks_the_next_bucket() { let mut second = Bucket::new( "second", BucketGroups::Plain(EngineGroup { + worker_services: None, worker_ids: Some( [WorkerId("owner".into()), WorkerId("cold".into())] .into_iter() @@ -706,7 +712,7 @@ async fn cache_aware_routes_tokenized_prompt_and_rechecks_the_next_bucket() { #[tokio::test] async fn default_pd_groups_apply_configured_inflight_admission() { - use sgl_router::config::{EligibilityConfig, FilterKind, PolicyKind}; + use sgl_router::config::PolicyKind; use std::sync::atomic::Ordering; let prefill = MockWorker::start(vec![]).await; @@ -720,11 +726,7 @@ async fn default_pd_groups_apply_configured_inflight_admission() { ); let mutable = Arc::get_mut(&mut ctx).unwrap(); mutable.config.model.policy = PolicyKind::PowerOfTwo; - mutable.config.model.eligibility = Some(EligibilityConfig { - filters: vec![FilterKind::Overloaded], - max_in_flight: Some(1), - min_prefix_share: None, - }); + mutable.config.model.reorg_admission.max_inflight_requests = Some(1); let state = sgl_router::state::kv_events::KvEventIndex::new(); let (resolver, _) = sgl_router::policies_reorg::factory::build_resolver(&mutable.config.model, &state, None) @@ -975,6 +977,7 @@ async fn full_decode_group_falls_back_to_another_version_group() { model_ids: vec![ModelId("tiny".into())], bootstrap_port: Some(8998), version_group: Some(group.into()), + services: Default::default(), }) .unwrap(); } diff --git a/experimental/sgl-router/tests/proxy/chat_routing/reorg/session_aware.rs b/experimental/sgl-router/tests/proxy/chat_routing/reorg/session_aware.rs index 660bc499f4..9a0221a354 100644 --- a/experimental/sgl-router/tests/proxy/chat_routing/reorg/session_aware.rs +++ b/experimental/sgl-router/tests/proxy/chat_routing/reorg/session_aware.rs @@ -79,6 +79,7 @@ async fn rejected_session_binding_advances_buckets_without_reassignment_or_dispa Bucket::new( "a-primary", BucketGroups::Plain(EngineGroup { + worker_services: None, worker_ids: Some([WorkerId("primary".into())].into_iter().collect()), policy: Arc::new(rejected), }), @@ -86,6 +87,7 @@ async fn rejected_session_binding_advances_buckets_without_reassignment_or_dispa Bucket::new( "b-backup", BucketGroups::Plain(EngineGroup { + worker_services: None, worker_ids: Some([WorkerId("backup".into())].into_iter().collect()), policy: Arc::new(accepted), }), diff --git a/experimental/sgl-router/tests/proxy/common/cache_aware_fixture.rs b/experimental/sgl-router/tests/proxy/common/cache_aware_fixture.rs index 1e333d2cfd..a47223d0c7 100644 --- a/experimental/sgl-router/tests/proxy/common/cache_aware_fixture.rs +++ b/experimental/sgl-router/tests/proxy/common/cache_aware_fixture.rs @@ -50,6 +50,8 @@ pub fn config() -> Config { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: Some(CacheAwareConfig::default()), affinity: None, diff --git a/experimental/sgl-router/tests/proxy/dp_rank_routing.rs b/experimental/sgl-router/tests/proxy/dp_rank_routing.rs index c3e23b71bf..523e1c4ce4 100644 --- a/experimental/sgl-router/tests/proxy/dp_rank_routing.rs +++ b/experimental/sgl-router/tests/proxy/dp_rank_routing.rs @@ -58,6 +58,7 @@ fn router( model_ids: vec![ModelId(MODEL.into())], bootstrap_port: (mode == WorkerMode::Prefill).then_some(8998), version_group: None, + services: Default::default(), }; let profile = EngineProfile { protocol: WireProtocol::default(), diff --git a/experimental/sgl-router/tests/proxy/failover.rs b/experimental/sgl-router/tests/proxy/failover.rs index 25098ae17d..bc6dbe2259 100644 --- a/experimental/sgl-router/tests/proxy/failover.rs +++ b/experimental/sgl-router/tests/proxy/failover.rs @@ -41,6 +41,8 @@ async fn failover_when_one_worker_dies() { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: Some(CircuitBreakerConfig { threshold: std::num::NonZeroU32::new(1).unwrap(), // open after first failure cool_down_secs: 30, diff --git a/experimental/sgl-router/tests/proxy/graceful_shutdown.rs b/experimental/sgl-router/tests/proxy/graceful_shutdown.rs index ae4d73cfb0..9a4214950b 100644 --- a/experimental/sgl-router/tests/proxy/graceful_shutdown.rs +++ b/experimental/sgl-router/tests/proxy/graceful_shutdown.rs @@ -59,6 +59,8 @@ fn build_ctx_with_worker(worker_url: &str) -> Arc { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, diff --git a/experimental/sgl-router/tests/proxy/header_forwarding.rs b/experimental/sgl-router/tests/proxy/header_forwarding.rs index 307c451a1e..014b25dfed 100644 --- a/experimental/sgl-router/tests/proxy/header_forwarding.rs +++ b/experimental/sgl-router/tests/proxy/header_forwarding.rs @@ -37,6 +37,8 @@ async fn forwards_whitelisted_headers_strips_others() { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, diff --git a/experimental/sgl-router/tests/proxy/pd_bootstrap_injection.rs b/experimental/sgl-router/tests/proxy/pd_bootstrap_injection.rs index 6d567135c4..8c3d60d443 100644 --- a/experimental/sgl-router/tests/proxy/pd_bootstrap_injection.rs +++ b/experimental/sgl-router/tests/proxy/pd_bootstrap_injection.rs @@ -52,6 +52,8 @@ fn config() -> Config { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, diff --git a/experimental/sgl-router/tests/proxy/pd_pool_isolation.rs b/experimental/sgl-router/tests/proxy/pd_pool_isolation.rs index 829cfe5d61..d777d40c6f 100644 --- a/experimental/sgl-router/tests/proxy/pd_pool_isolation.rs +++ b/experimental/sgl-router/tests/proxy/pd_pool_isolation.rs @@ -51,6 +51,8 @@ fn config() -> Config { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, @@ -547,6 +549,7 @@ fn pd_spec( model_ids: vec![ModelId("tiny".into())], bootstrap_port: port, version_group: group.map(str::to_owned), + services: Default::default(), } } diff --git a/experimental/sgl-router/tests/proxy/pd_protocol_binding.rs b/experimental/sgl-router/tests/proxy/pd_protocol_binding.rs index b9c5653ecf..7918e6850f 100644 --- a/experimental/sgl-router/tests/proxy/pd_protocol_binding.rs +++ b/experimental/sgl-router/tests/proxy/pd_protocol_binding.rs @@ -139,6 +139,8 @@ fn config() -> Config { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, diff --git a/experimental/sgl-router/tests/proxy/roundrobin_input_ids.rs b/experimental/sgl-router/tests/proxy/roundrobin_input_ids.rs index 2999019c2e..d9a260f659 100644 --- a/experimental/sgl-router/tests/proxy/roundrobin_input_ids.rs +++ b/experimental/sgl-router/tests/proxy/roundrobin_input_ids.rs @@ -49,6 +49,8 @@ fn config() -> Config { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, diff --git a/experimental/sgl-router/tests/proxy/shared_prefill_admission.rs b/experimental/sgl-router/tests/proxy/shared_prefill_admission.rs index eae3fc70c5..447fdb37b9 100644 --- a/experimental/sgl-router/tests/proxy/shared_prefill_admission.rs +++ b/experimental/sgl-router/tests/proxy/shared_prefill_admission.rs @@ -155,6 +155,8 @@ fn config(policy: PolicyKind) -> Config { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None, diff --git a/experimental/sgl-router/tests/proxy/sticky_input_ids.rs b/experimental/sgl-router/tests/proxy/sticky_input_ids.rs index 96b16015e7..eed1968e63 100644 --- a/experimental/sgl-router/tests/proxy/sticky_input_ids.rs +++ b/experimental/sgl-router/tests/proxy/sticky_input_ids.rs @@ -60,6 +60,8 @@ fn config() -> Config { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, // Push eviction far out so the background sweeper never fires diff --git a/experimental/sgl-router/tests/proxy/sticky_routing.rs b/experimental/sgl-router/tests/proxy/sticky_routing.rs index bb725758d1..5babaeae9e 100644 --- a/experimental/sgl-router/tests/proxy/sticky_routing.rs +++ b/experimental/sgl-router/tests/proxy/sticky_routing.rs @@ -48,6 +48,8 @@ fn build_sticky_ctx(header_name: &str, worker_urls: &[String]) -> Arc Config { decode_policy: Default::default(), dp_aware: false, bucket_config: None, + reorg_buckets: None, + reorg_admission: Default::default(), circuit_breaker: None, cache_aware: None, sticky: None,