[Feat] sgl-router: Route prefill buckets by uncached tokens (#45103)

Co-authored-by: Xiufei Li <294029388+lixiufei-leo@users.noreply.github.com>
Co-authored-by: Shangming Cai <csmthu@gmail.com>
This commit is contained in:
lixiufei-leo
2026-10-20 20:56:14 +08:00
committed by GitHub
co-authored by Xiufei Li Shangming Cai
parent eae134d61f
commit df13d5dce3
8 changed files with 386 additions and 16 deletions
+14 -1
View File
@@ -471,6 +471,10 @@ pub struct AffinityArgs {
#[arg(long)]
pub disable_pressure_guard: bool,
/// Match prefill buckets on uncached tokens (--policy cache_aware with --bucket-config).
#[arg(long)]
pub route_by_uncached_tokens: bool,
/// Pressure-guard token gap (session_aware or cache_aware). Defaults to 1024.
#[arg(long)]
pub pressure_abs_threshold_tokens: Option<u64>,
@@ -963,7 +967,8 @@ impl AffinityArgs {
|| cache.cache_switch_margin_tokens.is_some()
|| cache.worker_queue_limit.is_some()
|| cache.saturation_queue_floor.is_some()
|| cache.min_load_choices.is_some();
|| cache.min_load_choices.is_some()
|| self.route_by_uncached_tokens;
// Value checks before the policy check: a value that is wrong under
// every policy should say so, rather than pointing at --policy.
ensure!(
@@ -1102,6 +1107,7 @@ impl AffinityArgs {
.saturation_queue_floor
.or(defaults.saturation_queue_floor),
min_load_choices: cache.min_load_choices.unwrap_or(defaults.min_load_choices),
route_by_uncached_tokens: self.route_by_uncached_tokens,
}))
}
@@ -2864,6 +2870,13 @@ mod tests {
err.contains("cache candidate tuning flags require --policy cache_aware"),
"got: {err}"
);
let err = cfg_of("--policy session_aware --route-by-uncached-tokens")
.expect_err("bucket matching on E only runs under cache_aware")
.to_string();
assert!(
err.contains("cache candidate tuning flags require --policy cache_aware"),
"got: {err}"
);
let err = cfg_of(
"--policy cache_aware --kv-indexer-endpoint http://indexer:50051 \
@@ -658,6 +658,12 @@ pub struct AffinityConfig {
/// size chooses the exact minimum with random ties; 1 draws uniformly without
/// a backup for admission or pressure guards. Separate from cache-owner limits.
pub min_load_choices: usize,
/// Match prefill buckets on uncached tokens E instead of the input length. A
/// request with a reusable prefix uses E's buckets, and spills to a worker
/// with an idle DP rank when every rank in them has pending prefill; a
/// request without one uses every prefill worker whose bucket admits its
/// context.
pub route_by_uncached_tokens: bool,
}
impl Default for AffinityConfig {
@@ -686,6 +692,7 @@ impl Default for AffinityConfig {
worker_queue_limit: None,
saturation_queue_floor: None,
min_load_choices: DEFAULT_MIN_LOAD_CHOICES,
route_by_uncached_tokens: false,
}
}
}
@@ -58,6 +58,35 @@ impl BucketSelector {
&self,
workers: &[Arc<Worker>],
request: BucketRequest,
) -> Vec<CandidateDomain> {
// With no cache hit, E equals L.
self.prefill_domains_for_extend(workers, request, request.input_tokens)
}
/// Prefill domains for a request whose uncached work is `extend_tokens`.
pub fn prefill_domains_for_extend(
&self,
workers: &[Arc<Worker>],
request: BucketRequest,
extend_tokens: u64,
) -> Vec<CandidateDomain> {
self.prefill_domains_matching(workers, request, Some(extend_tokens))
}
/// Prefill domains that admit the request whatever its uncached work.
pub fn prefill_domains_for_any_extend(
&self,
workers: &[Arc<Worker>],
request: BucketRequest,
) -> Vec<CandidateDomain> {
self.prefill_domains_matching(workers, request, None)
}
fn prefill_domains_matching(
&self,
workers: &[Arc<Worker>],
request: BucketRequest,
extend_tokens: Option<u64>,
) -> Vec<CandidateDomain> {
let Some(config) = &self.config else {
return vec![CandidateDomain::global_prefill(workers)];
@@ -65,7 +94,7 @@ impl BucketSelector {
self.ordered_specs(
BucketStage::Prefill,
config.ttft_slo_policy,
|spec| prefill_compatible(spec, request.input_tokens),
|spec| prefill_compatible(spec, extend_tokens, request.input_tokens),
|spec| ttft_eligible(spec, request.ttft_slo_ms),
)
.into_iter()
@@ -253,9 +282,9 @@ impl BucketSelector {
}
}
fn prefill_compatible(spec: &BucketSpec, input_tokens: u64) -> bool {
// With no cache hit, E equals L.
within(input_tokens, spec.min_extend_tokens, spec.max_extend_tokens)
fn prefill_compatible(spec: &BucketSpec, extend_tokens: Option<u64>, input_tokens: u64) -> bool {
extend_tokens
.is_none_or(|extend| within(extend, spec.min_extend_tokens, spec.max_extend_tokens))
&& spec
.max_context_tokens
.is_none_or(|max_context| input_tokens <= max_context)
@@ -203,7 +203,7 @@ fn cap_matched_prefix_blocks(query_blocks: usize, matched_prefix_blocks: u32) ->
matched_prefix_blocks.min(u32::try_from(query_blocks).unwrap_or(u32::MAX))
}
fn estimate_matched_prefix_tokens(
pub(crate) fn estimate_matched_prefix_tokens(
input_tokens: u64,
query_blocks: usize,
matched_prefix_blocks: u32,
@@ -32,6 +32,7 @@ use crate::policies::admission::{
CandidateDomain, CandidateRange, DecisionReason,
};
use crate::policies::buckets::{BucketRequest, BucketSelector};
use crate::policies::cache_aware::estimate_matched_prefix_tokens;
use crate::policies::decode::{
build_decode_policy, resolve_decode_with_capacity_fallback, DecodeSelectionContext,
};
@@ -79,6 +80,8 @@ pub(crate) struct PrefillSelectionInputs<'a> {
pub saturation_queue_floor: Option<u64>,
/// `--min-load-choices`: sample size for the min-load capacity fallback.
pub min_load_choices: usize,
/// `--route-by-uncached-tokens`.
pub route_by_uncached_tokens: bool,
}
/// The queue-gate blind warn is sampled: it fires on a per-request path, and
@@ -146,11 +149,45 @@ pub(crate) fn select_prefill_worker(
},
failure_reason: PolicySelectionFailureReason::ProposalEmpty,
cache_gate_audit: None,
// E: the input beyond the longest prefix any prefill worker can reuse.
// None (cold) when nothing is reusable.
uncached_tokens: inputs
.route_by_uncached_tokens
.then(|| best_reusable_tokens(inputs))
.filter(|&reusable| reusable > 0)
.map(|reusable| inputs.request_sequence_tokens.saturating_sub(reusable)),
};
let selected = selector.run();
selected.ok_or(selector.failure_reason)
}
/// Longest prefix, in tokens, that any of the request's prefill workers can reuse.
fn best_reusable_tokens(inputs: &PrefillSelectionInputs<'_>) -> u64 {
let Some(signal) = inputs.external_prefix else {
return 0;
};
let sgl_kv_indexer::PrefixOutcome::Matched { matches, .. } = &signal.outcome else {
return 0;
};
matches
.iter()
.filter(|entry| {
inputs
.workers
.iter()
.any(|worker| worker.url == entry.address)
})
.map(|entry| {
estimate_matched_prefix_tokens(
inputs.request_sequence_tokens,
signal.query_blocks,
entry.matched_prefix_blocks,
)
})
.max()
.unwrap_or(0)
}
/// Carries the per-request bucket request and the failure reason across rungs.
/// Each rung that gives up overwrites the reason, so the reported one is what
/// the last rung to record any gave — a rung that returns `None` without
@@ -165,6 +202,8 @@ struct Selector<'a> {
/// resolution at all — no load snapshot, or no candidate proposal — which
/// reads as a plain miss because nothing was gated out.
cache_gate_audit: Option<(u64, u64, bool, u32)>,
/// `--route-by-uncached-tokens`: E for a request with a reusable prefix.
uncached_tokens: Option<u64>,
}
impl<'a> Selector<'a> {
@@ -182,8 +221,18 @@ impl<'a> Selector<'a> {
&& inputs.policy.is_bucket_affinity_policy()
&& session_affinity_mode != SessionAffinityMode::Bucket;
// By uncached tokens: a cold request uses every prefill worker, and a warm
// one whose buckets all queue while another worker idles spills there.
let cold = inputs.route_by_uncached_tokens && self.uncached_tokens.is_none();
let idle_spill = self.idle_spill_domains();
let uncached_tokens = self.uncached_tokens;
// Cache-Aware resolves one bounded global candidate set and returns a final winner.
let cache_winner = self.cache_winner();
let cache_winner = if idle_spill.is_some() {
None
} else {
self.cache_winner()
};
let cache_winner_hit = cache_winner.is_some();
let global_affinity_probe = use_global_affinity_probe
@@ -218,10 +267,37 @@ impl<'a> Selector<'a> {
let selected = cache_winner.or_else(|| {
// Materializing the normal domains clones the member list of every
// Bucket, so build them only on the rung that actually reads them.
let prefill_domains = || {
inputs
let prefill_domains = || match (&idle_spill, uncached_tokens) {
(Some(domains), _) => domains.clone(),
(None, Some(extend)) => {
let domains = inputs.bucket_selector.prefill_domains_for_extend(
inputs.workers,
bucket_request,
extend,
);
if domains.is_empty() {
// No bucket admits E: fall back to input-length matching.
inputs
.bucket_selector
.prefill_domains(inputs.workers, bucket_request)
} else {
domains
}
}
// Cold: every worker whose bucket admits the request's context.
(None, None) if cold => {
let mut admitted: Vec<Arc<Worker>> = inputs
.bucket_selector
.prefill_domains_for_any_extend(inputs.workers, bucket_request)
.into_iter()
.flat_map(|domain| domain.workers)
.collect();
admitted.dedup_by(|a, b| a.id == b.id);
vec![CandidateDomain::global_prefill(&admitted)]
}
(None, None) => inputs
.bucket_selector
.prefill_domains(inputs.workers, bucket_request)
.prefill_domains(inputs.workers, bucket_request),
};
if inputs.policy_kind == PolicyKind::CacheAware {
// Cache miss or failure retries ordered domains with ordinary P2.
@@ -252,7 +328,11 @@ impl<'a> Selector<'a> {
if inputs.policy_kind == PolicyKind::CacheAware && !cache_winner_hit && selected.is_some() {
let (rejected, evaluated, fleet_all_queued, blocks) =
self.cache_gate_audit.unwrap_or((0, 0, false, 0));
let decision = cache_aware_fallback_decision(rejected, evaluated, fleet_all_queued);
let decision = if idle_spill.is_some() {
CacheAwareDecision::IdleSpill
} else {
cache_aware_fallback_decision(rejected, evaluated, fleet_all_queued)
};
if matches!(decision, CacheAwareDecision::CacheWorkerQueued) {
// A real diversion: an unqueued destination existed and the
// gate gave up `blocks` of matched prefix to reach it. The
@@ -266,9 +346,63 @@ impl<'a> Selector<'a> {
.metrics
.record_cache_aware_decision(&inputs.model_id.0, decision);
}
if let (true, Some(worker)) = (inputs.route_by_uncached_tokens, &selected) {
tracing::debug!(
model = %inputs.model_id,
input_tokens = bucket_request.input_tokens,
uncached_tokens = ?uncached_tokens,
route = if idle_spill.is_some() { "idle_spill" } else if cold { "cold" } else { "warm" },
selected = %worker.url,
"prefill route by uncached tokens",
);
}
selected
}
/// Workers of the buckets holding E, when routing by uncached tokens.
fn extend_bucket_workers(&self) -> Option<Vec<Arc<Worker>>> {
let extend = self.uncached_tokens?;
let inputs = self.inputs;
let members: Vec<Arc<Worker>> = inputs
.bucket_selector
.prefill_domains_for_extend(inputs.workers, self.bucket_request, extend)
.into_iter()
.flat_map(|domain| domain.workers)
.collect();
// No bucket admits E: the request falls back to input-length matching.
(!members.is_empty()).then_some(members)
}
/// When every DP rank in a warm request's buckets has pending prefill: the
/// workers with an idle DP rank in the other buckets that admit it.
fn idle_spill_domains(&self) -> Option<Vec<CandidateDomain>> {
let targets = self.extend_bucket_workers()?;
let inputs = self.inputs;
let snapshot = inputs.load_snapshot?;
if targets.is_empty()
|| !targets.iter().all(|worker| {
snapshot
.fresh_min_rank_pending_for_url(&worker.url)
.is_some_and(|n| n > 0)
})
{
return None;
}
let domains: Vec<CandidateDomain> = inputs
.bucket_selector
.prefill_domains_for_any_extend(inputs.workers, self.bucket_request)
.into_iter()
.filter_map(|mut domain| {
domain.workers.retain(|worker| {
snapshot.fresh_min_rank_pending_for_url(&worker.url) == Some(0)
&& !targets.iter().any(|target| target.id == worker.id)
});
(!domain.workers.is_empty()).then_some(domain)
})
.collect();
(!domains.is_empty()).then_some(domains)
}
/// The per-request `SelectionContext` every rung starts from.
fn base_context(&self, candidate_range_id: &'a str) -> SelectionContext<'a> {
let inputs = self.inputs;
@@ -293,12 +427,22 @@ impl<'a> Selector<'a> {
.base_context(global_range.id)
.with_load_snapshot(snapshot)
.with_prefill_cache_bucket(inputs.bucket_selector, bucket_request);
let PrefillProposal::CacheCandidates(proposal) = inputs
let PrefillProposal::CacheCandidates(mut proposal) = inputs
.policy
.propose_prefill(global_range.workers, &cache_ctx)?
else {
return None;
};
if let Some(members) = self.extend_bucket_workers() {
proposal.candidates.retain(|candidate| {
members
.iter()
.any(|worker| worker.id == candidate.worker.id)
});
if proposal.candidates.is_empty() {
return None;
}
}
let bounded_candidate_count = proposal.candidates.len();
// The queue gate reads the engine-published load sample and fails open
// per worker. When NO worker has a fresh sample the gate is inert
@@ -715,7 +859,8 @@ mod tests {
CacheAwareDecision, MetricsRegistry, PolicySelectionFailureReason,
};
use crate::state::load_monitor::engine_reported_load::{
EngineReportedLoadSnapshot, EngineReportedSchedulingLoad,
EngineReportedLoadSnapshot, EngineReportedLoadTable, EngineReportedSchedulingLoad,
LoadStat, NativeCacheRankLoad,
};
use crate::workers::Worker;
use std::sync::Arc;
@@ -846,6 +991,7 @@ mod tests {
worker_queue_limit: None,
saturation_queue_floor: None,
min_load_choices: 2,
route_by_uncached_tokens: false,
ttft_slo_ms: None,
tps_slo: None,
session_affinity_mode: SessionAffinityMode::Bucket,
@@ -1282,4 +1428,147 @@ mod tests {
CacheAwareDecision::AllQueued
));
}
/// `short` takes up to 8192 uncached tokens, `long` the rest.
fn short_long_buckets(short_max_context: Option<u64>) -> BucketSelector {
let config: crate::config::BucketConfig = serde_json::from_value(serde_json::json!({
"buckets": [
{"id": "short", "stage": "prefill", "rank": 10, "worker_ids": ["short"],
"max_extend_tokens": 8192, "max_context_tokens": short_max_context},
{"id": "long", "stage": "prefill", "rank": 20, "worker_ids": ["long"],
"min_extend_tokens": 8193}
]
}))
.unwrap();
BucketSelector::new(Some(config))
}
/// The worker picked for a 20,000-token prompt sampled twice (n = 2), with
/// and without `--route-by-uncached-tokens`.
fn route_both_ways(
short_max_context: Option<u64>,
workers: &[Arc<Worker>],
loads: &EngineReportedLoadSnapshot,
signal: Option<&PrefixLookupResult>,
metrics: &MetricsRegistry,
) -> [String; 2] {
let policy = CacheAwarePolicy::new(AffinityConfig::default());
let buckets = short_long_buckets(short_max_context);
let model = ModelId("model".into());
[true, false].map(|route_by_uncached_tokens| {
let mut inputs = prefill_inputs(
&policy,
&buckets,
metrics,
&model,
workers,
Some(loads),
20_000,
);
inputs.request_input_tokens = 40_000;
inputs.policy_kind = PolicyKind::CacheAware;
inputs.external_prefix = signal;
inputs.route_by_uncached_tokens = route_by_uncached_tokens;
select_prefill_worker(&inputs).unwrap().id.0.clone()
})
}
#[test]
fn routes_prefill_buckets_by_uncached_tokens() {
let (short, long) = (worker("short"), worker("long"));
let workers = [Arc::clone(&short), Arc::clone(&long)];
let metrics = MetricsRegistry::new();
// Cold: the less loaded worker, whatever the input-length bucket.
let loads = queued_snapshot(&[(&short, 0, 10, 1_000_000), (&long, 3, 900_000, 1_000_000)]);
assert_eq!(
route_both_ways(None, &workers, &loads, None, &metrics),
["short", "long"]
);
let loads = queued_snapshot(&[(&short, 0, 10, 1_000_000), (&long, 0, 10, 1_000_000)]);
// Warm: 15 of 20 blocks reusable on `long` leave E = 5,000, `short`'s bucket.
let signal = prefix_signal(&[(&long, 15)], 20);
assert_eq!(
route_both_ways(None, &workers, &loads, Some(&signal), &metrics),
["short", "long"]
);
// 10 of 20 blocks leave E = 10,000, `long`'s bucket: n scales the input, not E.
let signal = prefix_signal(&[(&long, 10)], 20);
assert_eq!(
route_both_ways(None, &workers, &loads, Some(&signal), &metrics),
["long", "long"]
);
// Cold with a context cap: only the buckets that hold the prompt.
let loads = queued_snapshot(&[(&short, 0, 10, 1_000_000), (&long, 3, 900_000, 1_000_000)]);
assert_eq!(
route_both_ways(Some(10_000), &workers, &loads, None, &metrics),
["long", "long"]
);
// Warm, E = 5,000 is in `short`'s extend range, but `short`'s context cap
// rejects the prompt and `long` starts at 8,193: fall back to input length.
let loads = queued_snapshot(&[(&short, 0, 10, 1_000_000), (&long, 0, 10, 1_000_000)]);
let signal = prefix_signal(&[(&long, 15)], 20);
assert_eq!(
route_both_ways(Some(10_000), &workers, &loads, Some(&signal), &metrics),
["long", "long"]
);
}
/// `(waiting requests, uncached tokens still to prefill)` on each DP rank.
type RankPending<'a> = &'a [(u64, u64)];
fn rank_snapshot(entries: &[(&Arc<Worker>, RankPending<'_>)]) -> EngineReportedLoadSnapshot {
let table = EngineReportedLoadTable::new();
let now = Instant::now();
for (worker, ranks) in entries {
for (dp_rank, &(waiting, uncached)) in (0..).zip(ranks.iter()) {
let load = LoadStat {
num_running_reqs: 1,
num_waiting_reqs: waiting,
num_tokens: 10,
max_total_num_tokens: 1_000_000,
native_cache: Some(NativeCacheRankLoad {
num_waiting_uncached_tokens: uncached,
num_total_tokens: 10,
max_running_requests: 64,
total_prefill_uncached_tokens: 0,
total_prefill_busy_us: 0,
}),
};
table.set(&worker.url, dp_rank, load, now);
}
}
table.capture_snapshot(now)
}
#[test]
fn spills_to_a_worker_with_an_idle_dp_rank() {
let (short, long) = (worker("short"), worker("long"));
let workers = [Arc::clone(&short), Arc::clone(&long)];
let to_long = prefix_signal(&[(&long, 5)], 20); // E = 15,000: `long`'s bucket
let to_short = prefix_signal(&[(&short, 15)], 20); // E = 5,000: `short`'s bucket
let (busy, idle): (RankPending, RankPending) = (&[(2, 9)], &[(0, 0)]);
for (to, long_ranks, short_ranks, short_max_context, expected) in [
("long", busy, &[(3, 9), (0, 0)][..], None, "short"),
("long", busy, &[(3, 9), (1, 9)][..], None, "long"),
// Still prefilling a chunked prompt: nothing queued, but not idle.
("long", busy, &[(3, 9), (0, 40_000)][..], None, "long"),
// `short`'s context limit does not admit the 20,000-token prompt.
("long", busy, &[(3, 9), (0, 0)][..], Some(10_000), "long"),
// `short` spills only when every one of its ranks has pending work.
("short", idle, &[(3, 9), (0, 0)][..], None, "short"),
("short", idle, &[(3, 9), (1, 9)][..], None, "long"),
] {
let metrics = MetricsRegistry::new();
let loads = rank_snapshot(&[(&long, long_ranks), (&short, short_ranks)]);
let signal = if to == "long" { &to_long } else { &to_short };
let [picked, _] =
route_both_ways(short_max_context, &workers, &loads, Some(signal), &metrics);
let spilled = metrics.render().contains("decision=\"idle_spill\"");
assert_eq!(
(picked.as_str(), spilled),
(expected, expected != to),
"long {long_ranks:?}, short {short_ranks:?}, short max context {short_max_context:?}"
);
}
}
}
@@ -88,6 +88,8 @@
//! deliberately does NOT spell `cache_hit*`: a `decision=~"cache_hit.*"`
//! hit-rate query must not absorb it, or a fully saturated fleet reads as a
//! healthy one.
//! - `idle_spill` — `--route-by-uncached-tokens` sent the request to an idle DP
//! rank in another bucket, skipping the cache-aware selection.
//!
//! `sgl_router_input_ids_forwarding_total` records one outcome per dispatched
//! `/v1/chat/completions` request, so `outcome!="forwarded"` over the sum is
@@ -384,6 +386,7 @@ pub enum CacheAwareDecision {
CacheMiss,
CacheWorkerQueued,
AllQueued,
IdleSpill,
}
impl CacheAwareDecision {
@@ -393,6 +396,7 @@ impl CacheAwareDecision {
Self::CacheMiss => "cache_miss",
Self::CacheWorkerQueued => "cache_worker_queued",
Self::AllQueued => "all_queued",
Self::IdleSpill => "idle_spill",
}
}
}
@@ -1334,7 +1338,7 @@ impl MetricsRegistry {
// cache_aware_decisions_total
out.push_str(
"# HELP sgl_router_cache_aware_decisions_total Final Cache-Aware routing decisions, one per selection that resolved a worker: cache_hit = prefix owner won; cache_miss = no usable owner (a tree miss books here even under saturation, because the gate never fired); cache_worker_queued = queue gate diverted the request off its prefix; all_queued = queue gate fired but every worker is queueing (fleet-saturation signal, not a cache hit).\n",
"# HELP sgl_router_cache_aware_decisions_total Final Cache-Aware routing decisions, one per selection that resolved a worker: cache_hit = prefix owner won; cache_miss = no usable owner (a tree miss books here even under saturation, because the gate never fired); cache_worker_queued = queue gate diverted the request off its prefix; all_queued = queue gate fired but every worker is queueing (fleet-saturation signal, not a cache hit); idle_spill = --route-by-uncached-tokens sent a warm request off its busy buckets to an idle DP rank.\n",
);
out.push_str("# TYPE sgl_router_cache_aware_decisions_total counter\n");
let guard = self.cache_aware_decisions_total.lock();
@@ -551,6 +551,7 @@ fn pick_prefill_worker(
min_load_choices: affinity
.map(|config| config.min_load_choices)
.unwrap_or(DEFAULT_MIN_LOAD_CHOICES),
route_by_uncached_tokens: affinity.is_some_and(|config| config.route_by_uncached_tokens),
})
.map_err(|reason| policy_selection_failed(ctx, &request.model.0, reason))
}
@@ -99,6 +99,8 @@ pub struct EngineReportedSchedulingLoad {
pub struct EngineReportedLoadSnapshot {
pub version: u64,
workers: HashMap<String, EngineReportedWorkerLoad>,
/// Least pending prefill work on any one DP rank, for the workers in `workers`.
min_rank_pending: HashMap<String, u64>,
native_cache_workers: HashMap<String, EngineReportedSchedulingLoad>,
}
@@ -107,6 +109,17 @@ impl EngineReportedLoadSnapshot {
self.workers.get(worker_url)
}
/// Least pending prefill work on any one DP rank of the worker: queued
/// requests plus uncached tokens still to prefill, including a chunked
/// prefill's remainder. Zero means that rank is idle. A snapshot built from
/// aggregates treats the worker as one rank.
pub fn fresh_min_rank_pending_for_url(&self, worker_url: &str) -> Option<u64> {
self.min_rank_pending.get(worker_url).copied().or_else(|| {
self.fresh_load_for_url(worker_url)
.map(|load| load.num_waiting_reqs)
})
}
/// True when some worker in `fleet_urls` has a fresh queue reading
/// strictly below `floor` — a destination where a diverted request would
/// provably wait behind fewer than `floor` others. Workers with no fresh
@@ -148,6 +161,7 @@ impl EngineReportedLoadSnapshot {
Self {
version,
workers,
min_rank_pending: HashMap::new(),
native_cache_workers: HashMap::new(),
}
}
@@ -176,6 +190,7 @@ impl EngineReportedLoadSnapshot {
Self {
version,
workers: basic,
min_rank_pending: HashMap::new(),
native_cache_workers: workers,
}
}
@@ -366,7 +381,12 @@ impl EngineReportedLoadTable {
/// look misleadingly idle and draw *more* traffic.) Callers that never
/// registered expected ranks retain the all-known-ranks rule. The oldest
/// timestamp represents the freshness of the complete aggregate.
fn fresh_worker_loads(&self, now: Instant) -> HashMap<String, EngineReportedWorkerLoad> {
/// Also records each such worker's least pending prefill work on any one rank.
fn fresh_worker_loads(
&self,
now: Instant,
min_rank_pending: &mut HashMap<String, u64>,
) -> HashMap<String, EngineReportedWorkerLoad> {
// url -> rank -> (reported load, fresh, timestamp).
let mut observed: HashMap<String, HashMap<u32, (LoadStat, bool, Instant)>> = HashMap::new();
for entry in self.by_rank.iter() {
@@ -398,6 +418,7 @@ impl EngineReportedLoadTable {
let mut num_waiting_reqs = 0u64;
let mut num_tokens = 0u64;
let mut max_total_num_tokens = 0u64;
let mut min_pending = u64::MAX;
let mut oldest_at = None;
for rank in required {
let (load, fresh, at) = ranks.get(&rank)?;
@@ -409,9 +430,13 @@ impl EngineReportedLoadTable {
num_tokens = num_tokens.saturating_add(load.num_tokens);
max_total_num_tokens =
max_total_num_tokens.saturating_add(load.max_total_num_tokens);
let uncached = load.native_cache.as_ref();
let uncached = uncached.map_or(0, |n| n.num_waiting_uncached_tokens);
min_pending = min_pending.min(load.num_waiting_reqs.saturating_add(uncached));
oldest_at = Some(oldest_at.map_or(*at, |oldest: Instant| oldest.min(*at)));
}
oldest_at.map(|captured_at| {
min_rank_pending.insert(url.clone(), min_pending);
(
url,
EngineReportedWorkerLoad {
@@ -543,9 +568,11 @@ impl EngineReportedLoadTable {
/// Captures one immutable view for all routing decisions in a request.
pub fn capture_snapshot(&self, now: Instant) -> EngineReportedLoadSnapshot {
let mut min_rank_pending = HashMap::new();
EngineReportedLoadSnapshot {
version: self.version.load(Ordering::Acquire),
workers: self.fresh_worker_loads(now),
workers: self.fresh_worker_loads(now, &mut min_rank_pending),
min_rank_pending,
native_cache_workers: self.fresh_native_cache_worker_loads(now),
}
}