From 2cbe9b737b9442ad56f1fa315dd704d14fffcccb Mon Sep 17 00:00:00 2001 From: Virgile Pourchet <222121099+Virgile-pct@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:26:53 +0100 Subject: [PATCH 1/7] feat(routing): estimate cache-hit and cold service cost for the current request A pure estimator in mesh-llm-routing: cost of serving this request warm (queue, restore, unshared suffix at the candidate's rate) or cold (queue, whole prompt), with the credited prefix capped by what the request provably shares. Any missing component makes the candidate incomparable instead of cheaper. Not wired into routing yet. --- mesh/crates/mesh-llm-routing/src/lib.rs | 1 + .../mesh-llm-routing/src/request_cost.rs | 402 ++++++++++++++++++ 2 files changed, 403 insertions(+) create mode 100644 mesh/crates/mesh-llm-routing/src/request_cost.rs diff --git a/mesh/crates/mesh-llm-routing/src/lib.rs b/mesh/crates/mesh-llm-routing/src/lib.rs index dd5956fe17..8e645ddd34 100644 --- a/mesh/crates/mesh-llm-routing/src/lib.rs +++ b/mesh/crates/mesh-llm-routing/src/lib.rs @@ -6,6 +6,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; pub mod affinity; pub mod cache_aware; pub mod cache_inventory; +pub mod request_cost; /// Calculate total model size, summing all split files if present. /// Split files follow the pattern: name-00001-of-00004.gguf. diff --git a/mesh/crates/mesh-llm-routing/src/request_cost.rs b/mesh/crates/mesh-llm-routing/src/request_cost.rs new file mode 100644 index 0000000000..d3067b28dd --- /dev/null +++ b/mesh/crates/mesh-llm-routing/src/request_cost.rs @@ -0,0 +1,402 @@ +//! Service-cost estimate for the request being routed, cache hits and cold +//! candidates compared on the same scale. +//! +//! Every component is optional. A missing value makes the candidate +//! incomparable; it never reads as zero, so absent evidence cannot make a +//! candidate look cheaper than one that reported its costs. + +use crate::InferenceTarget; + +/// How a token count was obtained. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TokenSource { + /// Counted by a tokenizer. + Measured, + /// Derived from request size with a conservative ratio. + Heuristic, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TokenEstimate { + pub tokens: u32, + pub source: TokenSource, +} + +/// What the router knows about the request itself. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RequestCostInput { + /// Prompt length of this request. + pub prompt_tokens: Option, + /// Lower bound of the prefix this request provably shares with the cached + /// one (the hashed scaffold). A cache hit is never credited beyond it. + pub reusable_prefix_tokens: Option, +} + +/// Positive cache evidence a candidate advertised for this prefix. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CachedPrefix { + pub matched_tokens: u32, + pub restore_micros: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CandidateCostInput { + pub target: InferenceTarget, + /// Current wait before this candidate could start, not a past sample. + pub queue_micros: Option, + pub prefill_micros_per_token: Option, + pub cached: Option, +} + +/// The first component that kept an estimate from being made. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MissingComponent { + PromptTokens, + ReusablePrefix, + QueueDelay, + PrefillRate, + RestoreCost, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ServiceCost { + pub micros: u64, + /// Prompt tokens this estimate does not have to prefill. + pub credited_tokens: u32, +} + +/// Cost of serving the request on `candidate` without its cache. +pub fn cold_cost( + request: RequestCostInput, + candidate: &CandidateCostInput, +) -> Result { + let prompt = request + .prompt_tokens + .ok_or(MissingComponent::PromptTokens)?; + let queue = candidate.queue_micros.ok_or(MissingComponent::QueueDelay)?; + let rate = candidate + .prefill_micros_per_token + .ok_or(MissingComponent::PrefillRate)?; + Ok(ServiceCost { + micros: queue.saturating_add(u64::from(prompt.tokens).saturating_mul(rate)), + credited_tokens: 0, + }) +} + +/// Cost of serving the request on `candidate` from its cached prefix, or +/// `None` when the candidate advertised no cache for it. +pub fn warm_cost( + request: RequestCostInput, + candidate: &CandidateCostInput, +) -> Option> { + let cached = candidate.cached?; + Some(cached_cost(request, candidate, cached)) +} + +fn cached_cost( + request: RequestCostInput, + candidate: &CandidateCostInput, + cached: CachedPrefix, +) -> Result { + let prompt = request + .prompt_tokens + .ok_or(MissingComponent::PromptTokens)?; + let reusable = request + .reusable_prefix_tokens + .ok_or(MissingComponent::ReusablePrefix)?; + let queue = candidate.queue_micros.ok_or(MissingComponent::QueueDelay)?; + let rate = candidate + .prefill_micros_per_token + .ok_or(MissingComponent::PrefillRate)?; + let restore = cached.restore_micros.ok_or(MissingComponent::RestoreCost)?; + let credited = cached.matched_tokens.min(reusable).min(prompt.tokens); + let suffix = prompt.tokens - credited; + Ok(ServiceCost { + micros: queue + .saturating_add(restore) + .saturating_add(u64::from(suffix).saturating_mul(rate)), + credited_tokens: credited, + }) +} + +/// Why cache affinity did or did not take over routing. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CacheRouteDecision { + /// The cheapest comparable cache hit beats every comparable cold + /// candidate by the configured margin. + CacheHitWins { + target: InferenceTarget, + cost: ServiceCost, + best_cold_micros: Option, + }, + /// A cold candidate is at least as cheap; keep the normal order. + ColdWins, + /// Cache evidence exists but no hit could be costed. + Incomparable(MissingComponent), + /// No candidate advertised a cache hit worth considering. + NoEvidence, +} + +/// Pick a cache target only when it is cheaper for this request than serving +/// it cold anywhere, including on the cached candidate itself. A hit must also +/// credit at least `min_saved_tokens`, and beat the best cold estimate by the +/// prefill time of those tokens at its own rate, so a marginal estimate never +/// overrides the established order. Candidate order breaks ties. +pub fn decide_cache_route( + request: RequestCostInput, + candidates: &[CandidateCostInput], + min_saved_tokens: u32, +) -> CacheRouteDecision { + let best_cold = candidates + .iter() + .filter_map(|candidate| cold_cost(request, candidate).ok()) + .map(|cost| cost.micros) + .min(); + + let mut best_warm: Option<(&CandidateCostInput, ServiceCost)> = None; + let mut first_missing = None; + for candidate in candidates { + match warm_cost(request, candidate) { + None => {} + Some(Err(missing)) => { + first_missing.get_or_insert(missing); + } + Some(Ok(cost)) + if cost.credited_tokens >= min_saved_tokens + && best_warm.is_none_or(|(_, best)| cost.micros < best.micros) => + { + best_warm = Some((candidate, cost)); + } + Some(Ok(_)) => {} + } + } + + let Some((winner, cost)) = best_warm else { + return match first_missing { + Some(missing) => CacheRouteDecision::Incomparable(missing), + None => CacheRouteDecision::NoEvidence, + }; + }; + let margin = winner.prefill_micros_per_token.map_or(u64::MAX, |rate| { + u64::from(min_saved_tokens).saturating_mul(rate) + }); + match best_cold { + Some(cold) if cost.micros.saturating_add(margin) > cold => CacheRouteDecision::ColdWins, + _ => CacheRouteDecision::CacheHitWins { + target: winner.target.clone(), + cost, + best_cold_micros: best_cold, + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use iroh::SecretKey; + + const MIN_SAVED: u32 = 256; + + fn remote(seed: u8) -> InferenceTarget { + let mut bytes = [0u8; 32]; + bytes[0] = seed; + InferenceTarget::Remote(SecretKey::from_bytes(&bytes).public()) + } + + fn request(prompt: u32, reusable: u32) -> RequestCostInput { + RequestCostInput { + prompt_tokens: Some(TokenEstimate { + tokens: prompt, + source: TokenSource::Heuristic, + }), + reusable_prefix_tokens: Some(reusable), + } + } + + fn cold(seed: u8, queue: u64, rate: u64) -> CandidateCostInput { + CandidateCostInput { + target: remote(seed), + queue_micros: Some(queue), + prefill_micros_per_token: Some(rate), + cached: None, + } + } + + fn warm(seed: u8, queue: u64, rate: u64, matched: u32, restore: u64) -> CandidateCostInput { + CandidateCostInput { + cached: Some(CachedPrefix { + matched_tokens: matched, + restore_micros: Some(restore), + }), + ..cold(seed, queue, rate) + } + } + + fn winner(decision: &CacheRouteDecision) -> Option { + match decision { + CacheRouteDecision::CacheHitWins { target, .. } => Some(target.clone()), + _ => None, + } + } + + #[test] + fn a_long_queue_on_the_hit_loses_to_an_idle_cold_node() { + // The issue's example: A holds the prefix but waits 6 s, B is idle. + let decision = decide_cache_route( + request(4_000, 3_000), + &[warm(1, 6_000_000, 250, 3_000, 0), cold(2, 0, 250)], + MIN_SAVED, + ); + assert_eq!(decision, CacheRouteDecision::ColdWins); + } + + #[test] + fn the_crossover_follows_the_current_request_length() { + // Same evidence, same nodes: a hit that saves 2 000 tokens wins while + // the suffix is short, and loses once the suffix dominates and the + // hit's slower rate costs more than the saved prefix. + let candidates = [warm(1, 0, 1_000, 2_000, 0), cold(2, 0, 400)]; + let short = decide_cache_route(request(2_200, 2_000), &candidates, MIN_SAVED); + assert_eq!(winner(&short), Some(remote(1))); + let long = decide_cache_route(request(20_000, 2_000), &candidates, MIN_SAVED); + assert_eq!(long, CacheRouteDecision::ColdWins); + } + + #[test] + fn credit_never_exceeds_the_reusable_prefix() { + // 8 000 cached tokens, but only a 300-token scaffold is provably shared. + let candidate = warm(1, 0, 1_000, 8_000, 0); + let cost = warm_cost(request(9_000, 300), &candidate).unwrap().unwrap(); + assert_eq!(cost.credited_tokens, 300); + assert_eq!(cost.micros, 8_700 * 1_000); + } + + #[test] + fn credit_never_exceeds_the_prompt() { + let candidate = warm(1, 0, 1_000, 8_000, 0); + let cost = warm_cost(request(500, 8_000), &candidate).unwrap().unwrap(); + assert_eq!(cost.credited_tokens, 500); + assert_eq!(cost.micros, 0); + } + + #[test] + fn small_hits_keep_the_normal_order() { + let decision = decide_cache_route( + request(1_000, 1_000), + &[warm(1, 0, 1_000, MIN_SAVED - 1, 0)], + MIN_SAVED, + ); + assert_eq!(decision, CacheRouteDecision::NoEvidence); + } + + #[test] + fn a_marginal_saving_does_not_override_the_order() { + // The hit saves 300 tokens of its own time but is barely cheaper than + // a faster cold node: less than the margin, so the order stands. + let decision = decide_cache_route( + request(1_300, 300), + &[warm(1, 0, 1_000, 300, 0), cold(2, 0, 790)], + MIN_SAVED, + ); + assert_eq!(decision, CacheRouteDecision::ColdWins); + } + + #[test] + fn restore_cost_counts_against_the_hit() { + let decision = decide_cache_route( + request(2_000, 1_000), + &[warm(1, 0, 1_000, 1_000, 1_500_000)], + MIN_SAVED, + ); + assert_eq!(decision, CacheRouteDecision::ColdWins); + } + + #[test] + fn missing_components_make_a_hit_incomparable_not_cheaper() { + let mut no_queue = warm(1, 0, 1_000, 2_000, 0); + no_queue.queue_micros = None; + let mut no_rate = warm(1, 0, 1_000, 2_000, 0); + no_rate.prefill_micros_per_token = None; + let mut no_restore = warm(1, 0, 1_000, 2_000, 0); + no_restore.cached.as_mut().unwrap().restore_micros = None; + let cases = [ + (no_queue, MissingComponent::QueueDelay), + (no_rate, MissingComponent::PrefillRate), + (no_restore, MissingComponent::RestoreCost), + ]; + for (candidate, missing) in cases { + assert_eq!( + decide_cache_route( + request(3_000, 2_000), + &[candidate, cold(2, 0, 1_000)], + MIN_SAVED + ), + CacheRouteDecision::Incomparable(missing) + ); + } + let unknown_prompt = RequestCostInput { + prompt_tokens: None, + reusable_prefix_tokens: Some(2_000), + }; + assert_eq!( + decide_cache_route(unknown_prompt, &[warm(1, 0, 1_000, 2_000, 0)], MIN_SAVED), + CacheRouteDecision::Incomparable(MissingComponent::PromptTokens) + ); + let unknown_prefix = RequestCostInput { + reusable_prefix_tokens: None, + ..request(3_000, 0) + }; + assert_eq!( + decide_cache_route(unknown_prefix, &[warm(1, 0, 1_000, 2_000, 0)], MIN_SAVED), + CacheRouteDecision::Incomparable(MissingComponent::ReusablePrefix) + ); + } + + #[test] + fn an_uncosted_cold_node_cannot_veto_a_costed_hit() { + let mut unknown = cold(2, 0, 1); + unknown.queue_micros = None; + let decision = decide_cache_route( + request(3_000, 2_000), + &[warm(1, 0, 1_000, 2_000, 0), unknown], + MIN_SAVED, + ); + assert_eq!(winner(&decision), Some(remote(1))); + } + + #[test] + fn the_cheaper_hit_wins_and_order_breaks_ties() { + let decision = decide_cache_route( + request(3_000, 2_000), + &[warm(1, 0, 1_000, 1_500, 0), warm(2, 0, 1_000, 2_000, 0)], + MIN_SAVED, + ); + assert_eq!(winner(&decision), Some(remote(2))); + let tie = decide_cache_route( + request(3_000, 2_000), + &[warm(2, 0, 1_000, 2_000, 0), warm(1, 0, 1_000, 2_000, 0)], + MIN_SAVED, + ); + assert_eq!(winner(&tie), Some(remote(2))); + } + + #[test] + fn saturating_inputs_do_not_overflow() { + // A saturated hit must still lose to a finite cold estimate. + let decision = decide_cache_route( + request(u32::MAX, u32::MAX), + &[ + warm(1, u64::MAX, u64::MAX, u32::MAX, u64::MAX), + cold(2, 0, 1), + ], + MIN_SAVED, + ); + assert_eq!(decision, CacheRouteDecision::ColdWins); + } + + #[test] + fn a_zero_token_prompt_costs_only_the_wait() { + let cost = cold_cost(request(0, 0), &cold(1, 5_000, 1_000)).unwrap(); + assert_eq!(cost.micros, 5_000); + } +} From 42ff72f1b199f77c6ed9b9514de43bc4d10829c0 Mon Sep 17 00:00:00 2001 From: Virgile Pourchet <222121099+Virgile-pct@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:28:49 +0100 Subject: [PATCH 2/7] feat(routing): size the current request and its shared scaffold from the body The scaffold walk now yields its byte size with the hash, so the credited prefix is exactly what was hashed. Prompt tokens use a typical 4 bytes per token; the shared prefix uses 8, so a heuristic credit errs low. An explicit cache key does not deepen the credit. --- mesh/crates/mesh-llm-routing/src/affinity.rs | 71 ++++++++++-- .../mesh-llm-routing/src/request_cost.rs | 103 ++++++++++++++++++ 2 files changed, 163 insertions(+), 11 deletions(-) diff --git a/mesh/crates/mesh-llm-routing/src/affinity.rs b/mesh/crates/mesh-llm-routing/src/affinity.rs index 5f85faaa97..e86659c63a 100644 --- a/mesh/crates/mesh-llm-routing/src/affinity.rs +++ b/mesh/crates/mesh-llm-routing/src/affinity.rs @@ -224,18 +224,30 @@ pub fn scaffold_prefix_hash_from_body( body: &Value, prefix_fallback_to_first_user: bool, ) -> Option { + scaffold_prefix_from_body(body, prefix_fallback_to_first_user).map(|scaffold| scaffold.hash) +} + +/// The hashed scaffold and how many request bytes it covers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ScaffoldPrefix { + pub hash: u64, + pub bytes: usize, +} + +/// One walk for the prefix hash and its size, so the size always describes +/// exactly the content that was hashed. +pub fn scaffold_prefix_from_body( + body: &Value, + prefix_fallback_to_first_user: bool, +) -> Option { let mut hash = 0u64; + let mut bytes = 0usize; let mut found = false; - for key in [ - "tools", - "functions", - "response_format", - "tool_choice", - "parallel_tool_calls", - ] { + for key in SCAFFOLD_FIELDS { if let Some(value) = body.get(key) { hash = hash_tagged_json(hash, key, value); + bytes = bytes.saturating_add(value.to_string().len()); found = true; } } @@ -247,6 +259,7 @@ pub fn scaffold_prefix_hash_from_body( "system" | "developer" => { if let Some(text) = message_text(msg) { hash = hash_tagged_text(hash, role, &text); + bytes = bytes.saturating_add(text.len()); found = true; } } @@ -258,27 +271,63 @@ pub fn scaffold_prefix_hash_from_body( if prefix_fallback_to_first_user && !found - && let Some(user_hash) = first_user_hash_from_body(body) + && let Some((user_hash, user_bytes)) = first_user_text_from_body(body) { hash = hash_combine(hash, user_hash); + bytes = bytes.saturating_add(user_bytes); found = true; } - found.then_some(hash) + found.then_some(ScaffoldPrefix { hash, bytes }) +} + +/// Request fields that belong to the reusable scaffold. +const SCAFFOLD_FIELDS: [&str; 5] = [ + "tools", + "functions", + "response_format", + "tool_choice", + "parallel_tool_calls", +]; + +/// Bytes of everything the backend will prefill for this request: the +/// scaffold fields, every message's text and a legacy `prompt`. +pub fn prompt_bytes_from_body(body: &Value) -> usize { + let scaffold = SCAFFOLD_FIELDS + .iter() + .filter_map(|key| body.get(*key)) + .map(|value| value.to_string().len()); + let messages = body + .get("messages") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(message_text) + .map(|text| text.len()); + let prompt = body.get("prompt").and_then(Value::as_str).map(str::len); + scaffold + .chain(messages) + .chain(prompt) + .fold(0usize, usize::saturating_add) } /// Compute the first user/prompt hash used as the sticky-routing fallback. pub fn first_user_hash_from_body(body: &Value) -> Option { + first_user_text_from_body(body).map(|(hash, _)| hash) +} + +fn first_user_text_from_body(body: &Value) -> Option<(u64, usize)> { if let Some(messages) = body.get("messages").and_then(Value::as_array) { for msg in messages { if msg.get("role").and_then(Value::as_str) == Some("user") { - return message_text(msg).map(|text| hash_tagged_text(0, "user", &text)); + return message_text(msg) + .map(|text| (hash_tagged_text(0, "user", &text), text.len())); } } } body.get("prompt") .and_then(Value::as_str) - .map(|prompt| hash_tagged_text(0, "prompt", prompt)) + .map(|prompt| (hash_tagged_text(0, "prompt", prompt), prompt.len())) } /// Select a model target after the consumer has applied any local eligibility diff --git a/mesh/crates/mesh-llm-routing/src/request_cost.rs b/mesh/crates/mesh-llm-routing/src/request_cost.rs index d3067b28dd..4ee68cc45d 100644 --- a/mesh/crates/mesh-llm-routing/src/request_cost.rs +++ b/mesh/crates/mesh-llm-routing/src/request_cost.rs @@ -6,6 +6,45 @@ //! candidate look cheaper than one that reported its costs. use crate::InferenceTarget; +use crate::affinity::{prompt_bytes_from_body, scaffold_prefix_from_body}; +use serde_json::Value; + +/// Typical bytes per token for prompt text, used to size the whole prompt. +pub const PROMPT_BYTES_PER_TOKEN: usize = 4; +/// Deliberately high bytes per token for the shared prefix: dividing by it +/// gives a count below what a tokenizer would report for ordinary text, so an +/// estimated credit errs toward too small, never toward too large. +pub const SHARED_PREFIX_BYTES_PER_TOKEN: usize = 8; + +/// Size this request from its parsed body. Without a body nothing is known; +/// with one, the provably shared prefix is the hashed scaffold, even when an +/// explicit cache key chose the prefix identity (a key says "same prefix", +/// not "this deep"). +pub fn request_cost_input_from_body( + body: Option<&Value>, + prefix_fallback_to_first_user: bool, +) -> RequestCostInput { + let Some(body) = body else { + return RequestCostInput { + prompt_tokens: None, + reusable_prefix_tokens: None, + }; + }; + let prompt_bytes = prompt_bytes_from_body(body); + let shared_bytes = scaffold_prefix_from_body(body, prefix_fallback_to_first_user) + .map_or(0, |scaffold| scaffold.bytes); + RequestCostInput { + prompt_tokens: Some(TokenEstimate { + tokens: u32::try_from(prompt_bytes.div_ceil(PROMPT_BYTES_PER_TOKEN)) + .unwrap_or(u32::MAX), + source: TokenSource::Heuristic, + }), + // Rounded down: a partial token is not credited. + reusable_prefix_tokens: Some( + u32::try_from(shared_bytes / SHARED_PREFIX_BYTES_PER_TOKEN).unwrap_or(u32::MAX), + ), + } +} /// How a token count was obtained. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -394,6 +433,70 @@ mod tests { assert_eq!(decision, CacheRouteDecision::ColdWins); } + fn chat_body(system: usize, user: usize) -> Value { + serde_json::json!({ + "messages": [ + {"role": "system", "content": "s".repeat(system)}, + {"role": "user", "content": "u".repeat(user)}, + ] + }) + } + + #[test] + fn the_request_is_sized_from_its_body() { + let input = request_cost_input_from_body(Some(&chat_body(800, 400)), true); + assert_eq!(input.prompt_tokens.map(|p| p.tokens), Some(300)); + assert_eq!(input.reusable_prefix_tokens, Some(100)); + } + + #[test] + fn later_turns_are_never_part_of_the_shared_prefix() { + let mut body = chat_body(800, 400); + let messages = body["messages"].as_array_mut().unwrap(); + messages.push(serde_json::json!({"role": "assistant", "content": "a".repeat(4_000)})); + messages.push(serde_json::json!({"role": "user", "content": "u".repeat(400)})); + let input = request_cost_input_from_body(Some(&body), true); + assert_eq!(input.prompt_tokens.map(|p| p.tokens), Some(1_400)); + assert_eq!(input.reusable_prefix_tokens, Some(100)); + } + + #[test] + fn an_explicit_cache_key_does_not_deepen_the_credit() { + let mut body = chat_body(800, 400); + body["prompt_cache_key"] = Value::from("k".repeat(4_000)); + let input = request_cost_input_from_body(Some(&body), true); + assert_eq!(input.reusable_prefix_tokens, Some(100)); + } + + #[test] + fn without_a_scaffold_only_the_fallback_policy_shares_the_first_user_turn() { + let body = serde_json::json!({"messages": [{"role": "user", "content": "u".repeat(800)}]}); + assert_eq!( + request_cost_input_from_body(Some(&body), true).reusable_prefix_tokens, + Some(100) + ); + assert_eq!( + request_cost_input_from_body(Some(&body), false).reusable_prefix_tokens, + Some(0) + ); + } + + #[test] + fn an_unparsed_body_leaves_the_request_unknown() { + let input = request_cost_input_from_body(None, true); + assert_eq!(input.prompt_tokens, None); + assert_eq!(input.reusable_prefix_tokens, None); + } + + #[test] + fn the_sized_scaffold_is_the_hashed_scaffold() { + let body = chat_body(800, 400); + assert_eq!( + crate::affinity::scaffold_prefix_from_body(&body, true).map(|s| s.hash), + crate::affinity::scaffold_prefix_hash_from_body(&body, true) + ); + } + #[test] fn a_zero_token_prompt_costs_only_the_wait() { let cost = cold_cost(request(0, 0), &cold(1, 5_000, 1_000)).unwrap(); From 66a48cfa0cd3e1096cdc9980fcc17c4f1239ca7b Mon Sep 17 00:00:00 2001 From: Virgile Pourchet <222121099+Virgile-pct@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:18:06 +0100 Subject: [PATCH 3/7] feat(routing): route cache hits on the current request's cost against cold candidates Both routing paths now go through Node::cache_target_with_lease, which sizes the current request and lets a hit override the order only when it beats the best cold estimate across candidates. Cold rates come from the local calibration and from the per-model rate peers already advertise on their cache entries, so the wire is unchanged. Unmeasured or incomparable evidence keeps the normal order. Refs #2773 --- .../src/network/affinity.rs | 170 ++++++++++++++---- .../src/network/openai/transport.rs | 21 +-- .../network/openai/transport_route_model.rs | 57 +++--- .../network/openai/transport_tests/routing.rs | 90 +++++++++- .../mesh-llm-routing/src/cache_inventory.rs | 63 +++++++ .../mesh-llm-routing/src/request_cost.rs | 111 ++++++++++++ 6 files changed, 438 insertions(+), 74 deletions(-) diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs b/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs index b146771e28..08d1018a59 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs @@ -5,6 +5,10 @@ use crate::network::reservations::{RoutingReservation, RoutingReservations}; use crate::network::target_health::{TargetHealth, TargetHealthOutcome, TargetReputationStats}; use iroh::EndpointId; use mesh_llm_routing::affinity as shared_affinity; +use mesh_llm_routing::request_cost; + +/// Smallest credited prefix that lets a cache hit override normal routing. +const MIN_SAVED_TOKENS: u32 = mesh_llm_routing::cache_aware::DEFAULT_MIN_SAVED_TOKENS; use serde::Serialize; use serde_json::Value; use std::collections::{HashMap, VecDeque}; @@ -435,6 +439,12 @@ pub(crate) fn cache_prefix_hash(parsed_body: Option<&Value>) -> Option { routing_keys(parsed_body).prefix_hash } +/// Size of this request and of the prefix it provably shares, with the same +/// scaffold rule as `routing_keys`, so the credited prefix is what was hashed. +pub(crate) fn request_cost_input(parsed_body: Option<&Value>) -> request_cost::RequestCostInput { + request_cost::request_cost_input_from_body(parsed_body, true) +} + impl crate::mesh::Node { /// Record only provider-confirmed local L1 reuse. A successful request with /// zero cached tokens is intentionally not evidence of residency. @@ -507,54 +517,100 @@ impl crate::mesh::Node { .invalidate(model, prefix_hash) } + /// Choose a cache target for this request, honouring a short lease only + /// for a request that could earn cache credit at all. Shared by the model + /// route and the remote-host ordering, so both apply the same estimate. + pub(crate) async fn cache_target_with_lease( + &self, + affinity: &AffinityRouter, + model: &str, + prefix_hash: u64, + candidates: &[election::InferenceTarget], + request: request_cost::RequestCostInput, + ) -> Option { + if !request_cost::can_earn_cache_credit(request, MIN_SAVED_TOKENS) { + return None; + } + if let Some(target) = affinity.lookup_cache_lease(model, prefix_hash, candidates) { + return Some(target); + } + let lease_epoch = affinity.cache_lease_epoch(); + let selected = self + .select_cache_target(model, prefix_hash, candidates, request) + .await; + if let Some(target) = selected.as_ref() { + affinity.remember_cache_lease_if_epoch(model, prefix_hash, target, lease_epoch); + } + selected + } + /// Probe bounded local and peer advertisements for the exact request - /// prefix. Missing, expired, or malformed evidence simply preserves normal - /// candidate order. + /// prefix, and route to a hit only when, for this request, it is cheaper + /// than serving it cold on any candidate, the hit's own included + /// (`request_cost::decide_cache_route`). Missing, expired, unmeasured or + /// incomparable evidence preserves normal candidate order. pub(crate) async fn select_cache_target( &self, model: &str, prefix_hash: u64, candidates: &[election::InferenceTarget], + request: request_cost::RequestCostInput, ) -> Option { - let local_evidence = self - .cache_affinity_inventory - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .probe_local(model, prefix_hash); + if !request_cost::can_earn_cache_credit(request, MIN_SAVED_TOKENS) { + return None; + } + let (local_evidence, local_rate) = { + let mut inventory = self + .cache_affinity_inventory + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + ( + inventory.probe_local(model, prefix_hash), + inventory.model_prefill_micros_per_token(model), + ) + }; + let mut spread_candidates = candidates.to_vec(); + if !spread_candidates.is_empty() { + let offset = prefix_hash as usize % spread_candidates.len(); + spread_candidates.rotate_left(offset); + } let now_unix_ms = crate::mesh::current_time_unix_ms(); let state = self.state.lock().await; - let evidence: Vec<_> = candidates + let inputs: Vec<_> = spread_candidates .iter() .filter_map(|target| { - let entry = match target { - election::InferenceTarget::Local(_) => local_evidence.clone(), - election::InferenceTarget::Remote(peer_id) => state - .peers - .get(peer_id) - .and_then(|peer| peer.cache_affinity.as_ref()) - .and_then(|advertisement| { - advertisement.probe(model, prefix_hash, now_unix_ms) - }), - election::InferenceTarget::None => None, - }?; - Some(mesh_llm_routing::cache_aware::TargetCacheEvidence { - target: target.clone(), - entry, - }) + let (entry, rate) = match target { + election::InferenceTarget::Local(_) => (local_evidence.clone(), local_rate), + election::InferenceTarget::Remote(peer_id) => { + let advertisement = state + .peers + .get(peer_id) + .and_then(|peer| peer.cache_affinity.as_ref()); + ( + advertisement.and_then(|advertisement| { + advertisement.probe(model, prefix_hash, now_unix_ms) + }), + advertisement.and_then(|advertisement| { + advertisement.model_prefill_micros_per_token(model, now_unix_ms) + }), + ) + } + election::InferenceTarget::None => return None, + }; + Some(request_cost::candidate_cost_input( + target.clone(), + entry.as_ref(), + rate, + )) }) .collect(); drop(state); - let mut spread_candidates = candidates.to_vec(); - if !spread_candidates.is_empty() { - let offset = prefix_hash as usize % spread_candidates.len(); - spread_candidates.rotate_left(offset); + let decision = request_cost::decide_cache_route(request, &inputs, MIN_SAVED_TOKENS); + tracing::debug!(model, ?decision, "cache route decision"); + match decision { + request_cost::CacheRouteDecision::CacheHitWins { target, .. } => Some(target), + _ => None, } - let selected = mesh_llm_routing::cache_aware::select_cache_target( - &spread_candidates, - &evidence, - mesh_llm_routing::cache_aware::CacheAwareConfig::default(), - ); - selected.map(|evidence| evidence.target) } } @@ -884,14 +940,48 @@ mod tests { let candidates = vec![remote(1), election::InferenceTarget::Local(9337)]; node.record_local_cache_hit("qwen", 0xfeed_beef, 512, 24, 0); + node.observe_local_prefill_cost("qwen", Some(1_000)); + // 512 of 1,024 tokens credited: 0.512 s warm plus the 256-token + // margin beats 1.024 s cold; the remote has no rate to compare. assert_eq!( - node.select_cache_target("qwen", 0xfeed_beef, &candidates) - .await, + node.select_cache_target( + "qwen", + 0xfeed_beef, + &candidates, + request_cost::RequestCostInput::heuristic(1_024, 512), + ) + .await, Some(election::InferenceTarget::Local(9337)) ); } + #[tokio::test] + async fn an_unmeasured_local_hit_does_not_override_routing() { + let node = + crate::mesh::Node::new_for_tests(crate::mesh::NodeRole::Host { http_port: 9337 }) + .await + .expect("test node"); + let candidates = vec![remote(1), election::InferenceTarget::Local(9337)]; + + // A hit with no prefill rate cannot be costed, so it is no evidence of + // an advantage, and a request sharing too little earns no credit. + node.record_local_cache_hit("qwen", 0xfeed_beef, 512, 24, 0); + let request = request_cost::RequestCostInput::heuristic(1_024, 512); + assert_eq!( + node.select_cache_target("qwen", 0xfeed_beef, &candidates, request) + .await, + None + ); + node.observe_local_prefill_cost("qwen", Some(1_000)); + let short_shared = request_cost::RequestCostInput::heuristic(1_024, MIN_SAVED_TOKENS - 1); + assert_eq!( + node.select_cache_target("qwen", 0xfeed_beef, &candidates, short_shared) + .await, + None + ); + } + #[tokio::test] async fn provider_confirmed_local_miss_invalidates_evidence() { let node = @@ -901,11 +991,17 @@ mod tests { let candidates = vec![remote(1), election::InferenceTarget::Local(9337)]; node.record_local_cache_hit("qwen", 0xfeed_beef, 512, 24, 0); + node.observe_local_prefill_cost("qwen", Some(1_000)); assert!(node.invalidate_local_cache_evidence("qwen", 0xfeed_beef)); assert_eq!( - node.select_cache_target("qwen", 0xfeed_beef, &candidates) - .await, + node.select_cache_target( + "qwen", + 0xfeed_beef, + &candidates, + request_cost::RequestCostInput::heuristic(1_024, 512), + ) + .await, None ); } diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport.rs index 6f90901136..a4d499c4eb 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport.rs @@ -601,12 +601,16 @@ async fn build_mesh_request_plan( &resolved_hosts, affinity, ); + let request_cost = crate::network::affinity::request_cost_input( + super::workload_routing::affinity_body(request), + ); let (target_hosts, equivalent_hosts) = order_mesh_target_hosts( node, effective_model.as_deref(), required_tokens, &mut prepared, affinity, + request_cost, ) .await; Ok(MeshRequestPlan { @@ -662,6 +666,7 @@ async fn order_mesh_target_hosts( required_tokens: Option, prepared: &mut PreparedTargets, affinity: &AffinityRouter, + request_cost: mesh_llm_routing::request_cost::RequestCostInput, ) -> (Vec, usize) { let target_hosts: Vec = prepared .ordered @@ -686,19 +691,9 @@ async fn order_mesh_target_hosts( .copied() .map(election::InferenceTarget::Remote) .collect(); - prepared.cache_target = match affinity.lookup_cache_lease(name, prefix_hash, &candidates) { - Some(target) => Some(target), - None => { - let lease_epoch = affinity.cache_lease_epoch(); - let selected = node - .select_cache_target(name, prefix_hash, &candidates) - .await; - if let Some(target) = selected.as_ref() { - affinity.remember_cache_lease_if_epoch(name, prefix_hash, target, lease_epoch); - } - selected - } - }; + prepared.cache_target = node + .cache_target_with_lease(affinity, name, prefix_hash, &candidates, request_cost) + .await; prepared.affinity_applied |= prepared.cache_target.is_some(); affinity.record_cache_probe(prepared.cache_target.is_some()); if let Some(election::InferenceTarget::Remote(cache_host)) = prepared.cache_target.as_ref() diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_route_model.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_route_model.rs index fb8b310726..246158db82 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_route_model.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_route_model.rs @@ -129,22 +129,13 @@ async fn cache_target_for_request( node: &mesh::Node, affinity: &AffinityRouter, model: &str, - prefix_hash: Option, + affinity_body: Option<&serde_json::Value>, candidates: &[election::InferenceTarget], ) -> Option { - let prefix_hash = prefix_hash?; - if let Some(target) = affinity.lookup_cache_lease(model, prefix_hash, candidates) { - return Some(target); - } - - let lease_epoch = affinity.cache_lease_epoch(); - let selected = node - .select_cache_target(model, prefix_hash, candidates) - .await; - if let Some(target) = selected.as_ref() { - affinity.remember_cache_lease_if_epoch(model, prefix_hash, target, lease_epoch); - } - selected + let prefix_hash = crate::network::affinity::cache_prefix_hash(affinity_body)?; + let request = crate::network::affinity::request_cost_input(affinity_body); + node.cache_target_with_lease(affinity, model, prefix_hash, candidates, request) + .await } async fn execution_candidates( @@ -268,9 +259,8 @@ async fn route_model_request_inner(args: RouteModelRequestArgs<'_>) -> RouteDisp route_observer.route_selected(Some(model)); let affinity_body = super::super::workload_routing::affinity_body(request); - let prefix_hash = crate::network::affinity::cache_prefix_hash(affinity_body); let cache_target = - cache_target_for_request(&node, affinity, model, prefix_hash, &ordered_candidates).await; + cache_target_for_request(&node, affinity, model, affinity_body, &ordered_candidates).await; let Some(ReservedModelRoute { selection, ordered, @@ -873,6 +863,11 @@ mod tests { assert_eq!(affinity.stats_snapshot().reservation_active, 0); } + /// A request whose shared scaffold covers the 512 cached tokens. + fn cached_request() -> mesh_llm_routing::request_cost::RequestCostInput { + mesh_llm_routing::request_cost::RequestCostInput::heuristic(1_024, 512) + } + async fn cache_context( prefix_hash: u64, target: election::InferenceTarget, @@ -908,6 +903,7 @@ mod tests { let (node, affinity, target, selection, state) = cache_context(prefix_hash, election::InferenceTarget::Local(9337)).await; node.record_local_cache_hit("qwen", prefix_hash, 512, 24, 0); + node.observe_local_prefill_cost("qwen", Some(1_000)); affinity.remember_cache_lease("qwen", prefix_hash, &target); let context = DeliveredRouteModelContext { node: &node, @@ -930,8 +926,13 @@ mod tests { ); assert_eq!( - node.select_cache_target("qwen", prefix_hash, std::slice::from_ref(&target)) - .await, + node.select_cache_target( + "qwen", + prefix_hash, + std::slice::from_ref(&target), + cached_request(), + ) + .await, None ); assert_eq!( @@ -949,6 +950,7 @@ mod tests { let (node, affinity, target, selection, state) = cache_context(prefix_hash, remote).await; let local = election::InferenceTarget::Local(9337); node.record_local_cache_hit("qwen", prefix_hash, 512, 24, 0); + node.observe_local_prefill_cost("qwen", Some(1_000)); affinity.remember_cache_lease("qwen", prefix_hash, &target); let context = DeliveredRouteModelContext { node: &node, @@ -975,8 +977,13 @@ mod tests { None ); assert_eq!( - node.select_cache_target("qwen", prefix_hash, std::slice::from_ref(&local)) - .await, + node.select_cache_target( + "qwen", + prefix_hash, + std::slice::from_ref(&local), + cached_request(), + ) + .await, Some(local) ); } @@ -987,6 +994,7 @@ mod tests { let (node, affinity, target, selection, state) = cache_context(prefix_hash, election::InferenceTarget::Local(9337)).await; node.record_local_cache_hit("qwen", prefix_hash, 512, 24, 0); + node.observe_local_prefill_cost("qwen", Some(1_000)); affinity.remember_cache_lease("qwen", prefix_hash, &target); let context = DeliveredRouteModelContext { node: &node, @@ -1009,8 +1017,13 @@ mod tests { ); assert_eq!( - node.select_cache_target("qwen", prefix_hash, std::slice::from_ref(&target)) - .await, + node.select_cache_target( + "qwen", + prefix_hash, + std::slice::from_ref(&target), + cached_request(), + ) + .await, Some(target.clone()) ); assert_eq!( diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_tests/routing.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_tests/routing.rs index 6b75d5ce23..99691897e6 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_tests/routing.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_tests/routing.rs @@ -474,8 +474,15 @@ async fn prefix_kill_switch_prevents_cache_evidence_reordering() -> Result<()> { }); node.insert_test_peer(peer).await; - let (ordered, _) = - order_mesh_target_hosts(&node, Some(model), None, &mut prepared, &affinity).await; + let (ordered, _) = order_mesh_target_hosts( + &node, + Some(model), + None, + &mut prepared, + &affinity, + mesh_llm_routing::request_cost::RequestCostInput::heuristic(1_024, 512), + ) + .await; assert_eq!(ordered, vec![peer_id]); assert!(prepared.cache_target.is_none()); @@ -483,6 +490,85 @@ async fn prefix_kill_switch_prevents_cache_evidence_reordering() -> Result<()> { Ok(()) } +/// The issue's fixture: 4,096 prompt tokens, 1,024 provably shared. A hit on a +/// peer prefilling at 2 ms/token costs 6.144 s (plus the 256-token margin), +/// while a peer that holds nothing for this prefix but prefills at 0.25 +/// ms/token serves it cold in 1.024 s. The hit only wins once the cold peer is +/// slower than the warm one's estimate. +#[tokio::test] +async fn a_slow_cache_hit_loses_to_a_faster_cold_peer() -> Result<()> { + use mesh_llm_routing::cache_inventory::{ + CACHE_AFFINITY_SALT_BYTES, CacheAffinityAdvertisement, CacheAffinityEntry, CacheTier, + prefix_digest, + }; + use mesh_llm_routing::request_cost::RequestCostInput; + + let model = "acme/code-model:Q4_K_M"; + let warm_peer = iroh::EndpointId::from(iroh::SecretKey::generate().public()); + let cold_peer = iroh::EndpointId::from(iroh::SecretKey::generate().public()); + let salt = [5; CACHE_AFFINITY_SALT_BYTES]; + let advertisement = + |prefix_hash: u64, matched_tokens: u32, rate: u64| CacheAffinityAdvertisement { + salt, + epoch: 1, + generated_at_unix_ms: crate::mesh::current_time_unix_ms(), + ttl_ms: 120_000, + entries: vec![CacheAffinityEntry { + model: model.to_string(), + prefix_digest: prefix_digest(&salt, model, prefix_hash), + matched_tokens, + suffix_prefill_tokens: 0, + tier: CacheTier::L1, + restore_micros: 0, + queue_delay_micros: 0, + prefill_micros_per_token: rate, + }], + }; + + for (cold_rate, expect_hit) in [(250, false), (4_000, true)] { + let node = test_node_with_remote_models(&[(model, warm_peer), (model, cold_peer)]).await; + let affinity = AffinityRouter::new(); + let mut request = unparsed_chat_request(model); + let mut prepared = prepare_mesh_targets( + &mut request, + Some(model), + &[warm_peer, cold_peer], + &affinity, + ); + let prefix_hash = prepared.prefix_hash.expect("derived prefix"); + let mut warm = test_peer_serving_model(warm_peer, model); + warm.cache_affinity = Some(advertisement(prefix_hash, 1_024, 2_000)); + node.insert_test_peer(warm).await; + // The cold peer's only entry is for another prefix: it carries its + // prefill rate, not a hit for this request. + let mut cold = test_peer_serving_model(cold_peer, model); + cold.cache_affinity = Some(advertisement(prefix_hash ^ 1, 1_024, cold_rate)); + node.insert_test_peer(cold).await; + + let (ordered, _) = order_mesh_target_hosts( + &node, + Some(model), + None, + &mut prepared, + &affinity, + RequestCostInput::heuristic(4_096, 1_024), + ) + .await; + + if expect_hit { + assert_eq!( + prepared.cache_target, + Some(election::InferenceTarget::Remote(warm_peer)) + ); + assert_eq!(ordered.first(), Some(&warm_peer)); + } else { + assert_eq!(prepared.cache_target, None, "cold rate {cold_rate}"); + assert!(!prepared.affinity_applied); + } + } + Ok(()) +} + #[tokio::test] async fn cached_auto_model_stays_sticky_when_no_ready_remote_model_exists() -> Result<()> { let cached_model = "cached-cooling-model-31B"; diff --git a/mesh/crates/mesh-llm-routing/src/cache_inventory.rs b/mesh/crates/mesh-llm-routing/src/cache_inventory.rs index 343e5be611..479a27bed2 100644 --- a/mesh/crates/mesh-llm-routing/src/cache_inventory.rs +++ b/mesh/crates/mesh-llm-routing/src/cache_inventory.rs @@ -66,6 +66,21 @@ impl CacheAffinityAdvertisement { && self.entries == other.entries } + /// The peer's prefill cost for `model` whatever the prefix, from the rate + /// carried by its fresh entries of that model, so a peer can be costed + /// cold for a prefix it does not hold. The slowest advertised rate is + /// taken; an unmeasured (`0`) rate or a stale advertisement gives `None`. + pub fn model_prefill_micros_per_token(&self, model: &str, now_unix_ms: u64) -> Option { + if !self.is_fresh_at(now_unix_ms) { + return None; + } + self.entries + .iter() + .filter(|entry| entry.model == model && entry.prefill_micros_per_token > 0) + .map(|entry| entry.prefill_micros_per_token) + .max() + } + pub fn probe( &self, model: &str, @@ -137,6 +152,15 @@ impl CacheInventory { /// Calibrate this node/model from provider-reported prefill timing. The /// bounded integer EWMA damps one-off scheduling and timer noise without /// putting floating-point values on the gossip wire. + /// This node's calibrated prefill cost for `model`, with or without a + /// cache hit, or `None` before the first measurement. + pub fn model_prefill_micros_per_token(&self, model: &str) -> Option { + self.model_prefill_micros_per_token + .get(model) + .copied() + .filter(|rate| *rate > 0) + } + pub fn observe_prefill_cost(&mut self, model: &str, prefill_micros_per_token: u64) { if prefill_micros_per_token == 0 { return; @@ -513,4 +537,43 @@ mod tests { rotating_salt(&node_id, CACHE_AFFINITY_SALT_ROTATION_MS) ); } + + #[test] + fn the_model_prefill_rate_is_known_with_or_without_a_hit() { + let mut inventory = CacheInventory::default(); + assert_eq!(inventory.model_prefill_micros_per_token("model"), None); + inventory.observe_prefill_cost("model", 800); + assert_eq!(inventory.model_prefill_micros_per_token("model"), Some(800)); + assert_eq!(inventory.model_prefill_micros_per_token("other"), None); + } + + #[test] + fn a_peer_is_costed_cold_from_any_fresh_entry_of_the_model() { + let mut inventory = CacheInventory::default(); + inventory.observe_prefill_cost("model", 400); + inventory.record_l1_hit("model", 1, 512, 32, 0); + inventory.observe_prefill_cost("model", 1_200); + inventory.record_l1_hit("model", 2, 512, 32, 0); + let advertisement = inventory.advertisement([3; CACHE_AFFINITY_SALT_BYTES], 1_000); + let rates: Vec<_> = advertisement + .entries + .iter() + .map(|entry| entry.prefill_micros_per_token) + .collect(); + let slowest = *rates.iter().max().expect("two entries"); + + assert_eq!( + advertisement.model_prefill_micros_per_token("model", 1_000), + Some(slowest) + ); + assert_eq!( + advertisement.model_prefill_micros_per_token("other", 1_000), + None + ); + let stale_at = 1_000 + u64::from(advertisement.ttl_ms) + 1; + assert_eq!( + advertisement.model_prefill_micros_per_token("model", stale_at), + None + ); + } } diff --git a/mesh/crates/mesh-llm-routing/src/request_cost.rs b/mesh/crates/mesh-llm-routing/src/request_cost.rs index 4ee68cc45d..a1a05568e2 100644 --- a/mesh/crates/mesh-llm-routing/src/request_cost.rs +++ b/mesh/crates/mesh-llm-routing/src/request_cost.rs @@ -7,6 +7,7 @@ use crate::InferenceTarget; use crate::affinity::{prompt_bytes_from_body, scaffold_prefix_from_body}; +use crate::cache_inventory::CacheAffinityEntry; use serde_json::Value; /// Typical bytes per token for prompt text, used to size the whole prompt. @@ -71,6 +72,20 @@ pub struct RequestCostInput { pub reusable_prefix_tokens: Option, } +impl RequestCostInput { + /// A request sized by the byte heuristic, for callers and tests that + /// already hold the counts. + pub fn heuristic(prompt_tokens: u32, reusable_prefix_tokens: u32) -> Self { + Self { + prompt_tokens: Some(TokenEstimate { + tokens: prompt_tokens, + source: TokenSource::Heuristic, + }), + reusable_prefix_tokens: Some(reusable_prefix_tokens), + } + } +} + /// Positive cache evidence a candidate advertised for this prefix. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct CachedPrefix { @@ -87,6 +102,45 @@ pub struct CandidateCostInput { pub cached: Option, } +/// The router has no current per-candidate queue estimate yet: the only queue +/// figure, an entry's `queue_delay_micros`, is the wait seen when that hit was +/// recorded. Every candidate gets this same term, so queueing does not change +/// the comparison either way, and reservation spreading still balances load. +/// A measured current wait replaces it. +pub const QUEUE_NOT_MODELED_MICROS: u64 = 0; + +/// Costing input for one candidate from what routing holds locally: its +/// positive cache entry for this prefix, if any, and its per-model prefill +/// rate. Without a model rate, a measured rate on the entry is used. +pub fn candidate_cost_input( + target: InferenceTarget, + entry: Option<&CacheAffinityEntry>, + model_prefill_micros_per_token: Option, +) -> CandidateCostInput { + let entry_rate = entry + .map(|entry| entry.prefill_micros_per_token) + .filter(|rate| *rate > 0); + CandidateCostInput { + target, + queue_micros: Some(QUEUE_NOT_MODELED_MICROS), + prefill_micros_per_token: model_prefill_micros_per_token.or(entry_rate), + cached: entry.map(|entry| CachedPrefix { + matched_tokens: entry.matched_tokens, + restore_micros: Some(entry.restore_micros), + }), + } +} + +/// Whether this request shares enough with any cached prefix for a hit to be +/// credited at all. A shorter or unknown shared prefix cannot earn the minimum +/// credit, so neither a cache lease nor cache evidence applies to it. +pub fn can_earn_cache_credit(request: RequestCostInput, min_saved_tokens: u32) -> bool { + request.prompt_tokens.is_some() + && request + .reusable_prefix_tokens + .is_some_and(|tokens| tokens >= min_saved_tokens) +} + /// The first component that kept an estimate from being made. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MissingComponent { @@ -502,4 +556,61 @@ mod tests { let cost = cold_cost(request(0, 0), &cold(1, 5_000, 1_000)).unwrap(); assert_eq!(cost.micros, 5_000); } + + fn entry(matched_tokens: u32, rate: u64) -> CacheAffinityEntry { + CacheAffinityEntry { + model: "m".into(), + prefix_digest: [0; crate::cache_inventory::CACHE_AFFINITY_DIGEST_BYTES], + matched_tokens, + suffix_prefill_tokens: 0, + tier: crate::cache_inventory::CacheTier::L1, + restore_micros: 7, + queue_delay_micros: 9_999, + prefill_micros_per_token: rate, + } + } + + #[test] + fn candidate_input_takes_the_model_rate_then_a_measured_entry_rate() { + let hit = entry(512, 300); + let input = candidate_cost_input(remote(1), Some(&hit), Some(200)); + assert_eq!(input.prefill_micros_per_token, Some(200)); + assert_eq!( + input.cached, + Some(CachedPrefix { + matched_tokens: 512, + restore_micros: Some(7), + }) + ); + // The hit-time queue sample is not a current wait. + assert_eq!(input.queue_micros, Some(QUEUE_NOT_MODELED_MICROS)); + assert_eq!( + candidate_cost_input(remote(1), Some(&hit), None).prefill_micros_per_token, + Some(300) + ); + // An unmeasured (0) entry rate is no rate. + assert_eq!( + candidate_cost_input(remote(1), Some(&entry(512, 0)), None).prefill_micros_per_token, + None + ); + let cold = candidate_cost_input(remote(2), None, Some(250)); + assert_eq!(cold.cached, None); + assert_eq!(cold.prefill_micros_per_token, Some(250)); + } + + #[test] + fn only_a_request_sharing_the_minimum_can_earn_credit() { + assert!(can_earn_cache_credit(request(4_096, 256), 256)); + assert!(!can_earn_cache_credit(request(4_096, 255), 256)); + let unknown = RequestCostInput { + prompt_tokens: None, + reusable_prefix_tokens: Some(1_024), + }; + assert!(!can_earn_cache_credit(unknown, 256)); + let unsized_prefix = RequestCostInput { + reusable_prefix_tokens: None, + ..request(4_096, 0) + }; + assert!(!can_earn_cache_credit(unsized_prefix, 256)); + } } From 34b2a7c99ac9a189b75e9801b46b150afd79d0f8 Mon Sep 17 00:00:00 2001 From: Virgile Pourchet <222121099+Virgile-pct@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:05:02 +0100 Subject: [PATCH 4/7] feat(mesh): advertise each model's prefill rate so cold peers can be costed A peer's prefill rate only travelled on its cache-affinity entries, which expire after 120 s, so a fast peer without a recent hit could not be costed cold and could not veto a slow hit. The throughput hint now carries the node's calibrated per-model rate and the time of its newest sample (optional fields 7 and 8, ignored by older peers). Routing reads it first, fresh for 15 minutes, and falls back to cache entries for peers that predate it. --- .../src/mesh/announcements.rs | 20 ++++- .../mesh/tests/gossip/merge_and_refresh.rs | 3 + .../src/network/affinity.rs | 26 +++++-- .../src/network/metrics.rs | 6 +- .../src/network/metrics/tests.rs | 6 ++ .../network/openai/transport_tests/routing.rs | 78 +++++++++++++++++++ .../src/protocol/convert.rs | 45 +++++++++++ .../src/protocol/tests/announcements.rs | 2 + .../src/runtime_data/mod.rs | 1 + .../src/advertised_throughput.rs | 51 ++++++++++++ .../crates/mesh-llm-protocol/proto/node.proto | 5 ++ .../mesh-llm-protocol/src/proto/node.rs | 7 ++ .../mesh-llm-routing/src/cache_inventory.rs | 18 +++++ mesh/docs/design/METRICS.md | 2 + 14 files changed, 260 insertions(+), 10 deletions(-) diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/announcements.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/announcements.rs index aa709ce9d9..5346b5df4b 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/announcements.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/announcements.rs @@ -88,10 +88,28 @@ impl Node { serving_models.clear(); hosted_models.clear(); } - let advertised_model_throughput = self + let mut advertised_model_throughput = self .routing_metrics .advertisable_model_throughput(&hosted_models); let now_unix_ms = current_time_unix_ms(); + // Each hinted model also carries this node's calibrated prefill rate, so + // a router can cost the node cold, not only when it holds a cache hit. + { + let inventory = self + .cache_affinity_inventory + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + for hint in &mut advertised_model_throughput { + hint.prefill = inventory.model_prefill_measurement(&hint.model_name).map( + |(micros_per_token, observed_at)| crate::network::metrics::PrefillMeasurement { + micros_per_token, + observed_at_unix_ms: now_unix_ms.saturating_sub( + u64::try_from(observed_at.elapsed().as_millis()).unwrap_or(u64::MAX), + ), + }, + ); + } + } let cache_affinity = mesh_llm_membership::local_advertisement( &self.cache_affinity_inventory, self.endpoint.id().as_bytes(), diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/gossip/merge_and_refresh.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/gossip/merge_and_refresh.rs index 9195125049..5afff31d19 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/gossip/merge_and_refresh.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/gossip/merge_and_refresh.rs @@ -487,6 +487,7 @@ pub(crate) fn test_apply_transitive_ann_refreshes_advertised_model_throughput() avg_tokens_per_second_milli: 35_000, throughput_samples: 4, measurement: None, + prefill: None, }]; apply_transitive_ann( @@ -582,6 +583,7 @@ pub(crate) async fn test_add_peer_refreshes_advertised_model_throughput() { avg_tokens_per_second_milli: 20_000, throughput_samples: 2, measurement: None, + prefill: None, }]; node.add_peer(peer_id, addr.clone(), &ann, None).await; @@ -614,6 +616,7 @@ pub(crate) async fn test_peer_throughput_hint_counts_only_while_fresh() { avg_tokens_per_second_milli: 30_000, throughput_samples: 5, measurement, + prefill: None, }; let measured = |age_ms: u64| { Some(ThroughputMeasurement { diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs b/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs index 08d1018a59..278ec372ce 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs @@ -582,17 +582,29 @@ impl crate::mesh::Node { let (entry, rate) = match target { election::InferenceTarget::Local(_) => (local_evidence.clone(), local_rate), election::InferenceTarget::Remote(peer_id) => { - let advertisement = state - .peers - .get(peer_id) - .and_then(|peer| peer.cache_affinity.as_ref()); + let peer = state.peers.get(peer_id); + let advertisement = peer.and_then(|peer| peer.cache_affinity.as_ref()); + // The peer's dedicated per-model rate first; a node + // that predates it still carries one on its cache + // entries while they last. + let rate = peer + .and_then(|peer| { + peer.advertised_model_throughput + .iter() + .find(|hint| hint.model_name == model) + }) + .and_then(|hint| hint.prefill) + .and_then(|prefill| prefill.fresh_micros_per_token(now_unix_ms)) + .or_else(|| { + advertisement.and_then(|advertisement| { + advertisement.model_prefill_micros_per_token(model, now_unix_ms) + }) + }); ( advertisement.and_then(|advertisement| { advertisement.probe(model, prefix_hash, now_unix_ms) }), - advertisement.and_then(|advertisement| { - advertisement.model_prefill_micros_per_token(model, now_unix_ms) - }), + rate, ) } election::InferenceTarget::None => return None, diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/metrics.rs b/mesh/crates/mesh-llm-host-runtime/src/network/metrics.rs index 71203c27c3..7c8811c013 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/metrics.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/metrics.rs @@ -14,8 +14,8 @@ use mesh_llm_membership::advertised_throughput::MAX_ADVERTISED_MODEL_NAME_BYTES; pub(crate) use mesh_llm_membership::advertised_throughput::{ MAX_ADVERTISED_MODEL_THROUGHPUT_HINTS, MAX_ADVERTISED_THROUGHPUT_SAMPLES, - MAX_ADVERTISED_TPS_MILLI, ModelThroughputHint, THROUGHPUT_SCALE_MILLI, ThroughputMeasurement, - ThroughputMeasurementKind, sanitize_model_throughput_hints, + MAX_ADVERTISED_TPS_MILLI, ModelThroughputHint, PrefillMeasurement, THROUGHPUT_SCALE_MILLI, + ThroughputMeasurement, ThroughputMeasurementKind, sanitize_model_throughput_hints, }; #[path = "metrics/throughput_window.rs"] @@ -570,6 +570,7 @@ impl RoutingMetrics { .min(MAX_ADVERTISED_TPS_MILLI), throughput_samples: recent.samples.min(MAX_ADVERTISED_THROUGHPUT_SAMPLES), measurement, + prefill: None, }); if hints.len() >= MAX_ADVERTISED_MODEL_THROUGHPUT_HINTS { break; @@ -608,6 +609,7 @@ impl RoutingMetrics { throughput_samples: recent.samples, // Local observation, read straight from the window: no wire age. measurement: None, + prefill: None, }) } diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/metrics/tests.rs b/mesh/crates/mesh-llm-host-runtime/src/network/metrics/tests.rs index f03bca18f1..c65fd9373c 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/metrics/tests.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/metrics/tests.rs @@ -717,36 +717,42 @@ fn sanitize_model_throughput_hints_drops_invalid_and_clamps_values() { avg_tokens_per_second_milli: MAX_ADVERTISED_TPS_MILLI + 1, throughput_samples: MAX_ADVERTISED_THROUGHPUT_SAMPLES + 1, measurement: None, + prefill: None, }, ModelThroughputHint { model_name: "qwen".to_string(), avg_tokens_per_second_milli: 42_000, throughput_samples: 7, measurement: None, + prefill: None, }, ModelThroughputHint { model_name: "".to_string(), avg_tokens_per_second_milli: 42_000, throughput_samples: 7, measurement: None, + prefill: None, }, ModelThroughputHint { model_name: "x".repeat(MAX_ADVERTISED_MODEL_NAME_BYTES + 1), avg_tokens_per_second_milli: 42_000, throughput_samples: 7, measurement: None, + prefill: None, }, ModelThroughputHint { model_name: "empty-speed".to_string(), avg_tokens_per_second_milli: 0, throughput_samples: 7, measurement: None, + prefill: None, }, ModelThroughputHint { model_name: "empty-samples".to_string(), avg_tokens_per_second_milli: 42_000, throughput_samples: 0, measurement: None, + prefill: None, }, ]); diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_tests/routing.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_tests/routing.rs index 99691897e6..c7b147f9b1 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_tests/routing.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_tests/routing.rs @@ -569,6 +569,84 @@ async fn a_slow_cache_hit_loses_to_a_faster_cold_peer() -> Result<()> { Ok(()) } +/// A peer holding no cache entry is costed cold from the prefill rate on its +/// throughput hint, so a fast idle peer vetoes a slow hit; once that rate is +/// stale it is uncosted again and cannot. +#[tokio::test] +async fn a_cold_peer_with_only_its_advertised_rate_can_veto_a_slow_hit() -> Result<()> { + use crate::network::metrics::{ModelThroughputHint, PrefillMeasurement}; + use mesh_llm_routing::cache_inventory::{ + CACHE_AFFINITY_SALT_BYTES, CacheAffinityAdvertisement, CacheAffinityEntry, CacheTier, + prefix_digest, + }; + use mesh_llm_routing::request_cost::RequestCostInput; + + let model = "acme/code-model:Q4_K_M"; + let warm_peer = iroh::EndpointId::from(iroh::SecretKey::generate().public()); + let cold_peer = iroh::EndpointId::from(iroh::SecretKey::generate().public()); + let salt = [6; CACHE_AFFINITY_SALT_BYTES]; + let now = crate::mesh::current_time_unix_ms(); + let fifteen_minutes = 15 * 60 * 1000; + + for (rate_age_ms, expect_hit) in [(1_000, false), (fifteen_minutes + 1_000, true)] { + let node = test_node_with_remote_models(&[(model, warm_peer), (model, cold_peer)]).await; + let affinity = AffinityRouter::new(); + let mut request = unparsed_chat_request(model); + let mut prepared = prepare_mesh_targets( + &mut request, + Some(model), + &[warm_peer, cold_peer], + &affinity, + ); + let prefix_hash = prepared.prefix_hash.expect("derived prefix"); + let mut warm = test_peer_serving_model(warm_peer, model); + warm.cache_affinity = Some(CacheAffinityAdvertisement { + salt, + epoch: 1, + generated_at_unix_ms: now, + ttl_ms: 120_000, + entries: vec![CacheAffinityEntry { + model: model.to_string(), + prefix_digest: prefix_digest(&salt, model, prefix_hash), + matched_tokens: 1_024, + suffix_prefill_tokens: 0, + tier: CacheTier::L1, + restore_micros: 0, + queue_delay_micros: 0, + prefill_micros_per_token: 2_000, + }], + }); + node.insert_test_peer(warm).await; + let mut cold = test_peer_serving_model(cold_peer, model); + cold.cache_affinity = None; + cold.advertised_model_throughput = vec![ModelThroughputHint { + model_name: model.to_string(), + avg_tokens_per_second_milli: 40_000, + throughput_samples: 8, + measurement: None, + prefill: Some(PrefillMeasurement { + micros_per_token: 250, + observed_at_unix_ms: now - rate_age_ms, + }), + }]; + node.insert_test_peer(cold).await; + + order_mesh_target_hosts( + &node, + Some(model), + None, + &mut prepared, + &affinity, + RequestCostInput::heuristic(4_096, 1_024), + ) + .await; + + let expected = expect_hit.then_some(election::InferenceTarget::Remote(warm_peer)); + assert_eq!(prepared.cache_target, expected, "rate age {rate_age_ms} ms"); + } + Ok(()) +} + #[tokio::test] async fn cached_auto_model_stays_sticky_when_no_ready_remote_model_exists() -> Result<()> { let cached_model = "cached-cooling-model-31B"; diff --git a/mesh/crates/mesh-llm-host-runtime/src/protocol/convert.rs b/mesh/crates/mesh-llm-host-runtime/src/protocol/convert.rs index 5686e850d4..46c7008286 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/protocol/convert.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/protocol/convert.rs @@ -720,6 +720,8 @@ fn local_throughput_hint_to_proto( Kind::EndToEndAttempt => WireKind::EndToEndAttempt as i32, Kind::Unknown => WireKind::Unspecified as i32, }), + prefill_micros_per_token: hint.prefill.map(|prefill| prefill.micros_per_token), + prefill_observed_at_unix_ms: hint.prefill.map(|prefill| prefill.observed_at_unix_ms), } } @@ -747,6 +749,17 @@ fn proto_throughput_hint_to_local( avg_tokens_per_second_milli: hint.avg_tokens_per_second_milli, throughput_samples: hint.throughput_samples, measurement, + // Only a dated, measured rate is kept; an older sender sends neither. + prefill: hint + .prefill_micros_per_token + .zip(hint.prefill_observed_at_unix_ms) + .filter(|(micros_per_token, _)| *micros_per_token > 0) + .map(|(micros_per_token, observed_at_unix_ms)| { + crate::network::metrics::PrefillMeasurement { + micros_per_token, + observed_at_unix_ms, + } + }), } } @@ -1580,6 +1593,38 @@ mod tests { } } + /// The prefill rate travels as two optional fields; it exists only when + /// both are present and the rate is measured. + #[test] + fn prefill_rate_needs_its_rate_and_time_from_the_wire() { + use crate::network::metrics::{ModelThroughputHint, PrefillMeasurement}; + let prefill = PrefillMeasurement { + micros_per_token: 250, + observed_at_unix_ms: 1_800_000_000_000, + }; + let local = ModelThroughputHint { + model_name: "qwen".to_string(), + avg_tokens_per_second_milli: 42_000, + throughput_samples: 7, + measurement: None, + prefill: Some(prefill), + }; + let wire = local_throughput_hint_to_proto(&local); + assert_eq!(wire.prefill_micros_per_token, Some(250)); + assert_eq!(proto_throughput_hint_to_local(&wire).prefill, Some(prefill)); + + let rate_only = crate::proto::node::AdvertisedModelThroughput { + prefill_observed_at_unix_ms: None, + ..wire.clone() + }; + assert_eq!(proto_throughput_hint_to_local(&rate_only).prefill, None); + let unmeasured = crate::proto::node::AdvertisedModelThroughput { + prefill_micros_per_token: Some(0), + ..wire + }; + assert_eq!(proto_throughput_hint_to_local(&unmeasured).prefill, None); + } + #[test] /// Preserve every supported workload class across protobuf announcement conversion. fn workload_class_round_trips_through_additive_proto_metadata() { diff --git a/mesh/crates/mesh-llm-host-runtime/src/protocol/tests/announcements.rs b/mesh/crates/mesh-llm-host-runtime/src/protocol/tests/announcements.rs index a7864768ad..f8580339d8 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/protocol/tests/announcements.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/protocol/tests/announcements.rs @@ -190,6 +190,7 @@ fn advertised_model_throughput_roundtrips_through_proto_announcement() { window_ms: 900_000, kind: crate::network::metrics::ThroughputMeasurementKind::EndToEndAttempt, }), + prefill: None, }]; let salt = [0xC3; mesh_llm_routing::cache_inventory::CACHE_AFFINITY_SALT_BYTES]; let prefix_hash = 0xfeed_beef; @@ -244,6 +245,7 @@ fn advertised_model_throughput_roundtrips_through_proto_announcement() { avg_tokens_per_second_milli: 250_000, throughput_samples: 99, measurement: None, + prefill: None, }, ], cache_affinity: Some( diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/mod.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/mod.rs index 54c6f6a8be..acdafcd066 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/mod.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/mod.rs @@ -853,6 +853,7 @@ pub(crate) mod tests { avg_tokens_per_second_milli: 13_400, throughput_samples: 27, measurement: None, + prefill: None, }], cache_affinity: None, display_rtt: None, diff --git a/mesh/crates/mesh-llm-membership/src/advertised_throughput.rs b/mesh/crates/mesh-llm-membership/src/advertised_throughput.rs index 2074a9ea99..217b796476 100644 --- a/mesh/crates/mesh-llm-membership/src/advertised_throughput.rs +++ b/mesh/crates/mesh-llm-membership/src/advertised_throughput.rs @@ -37,6 +37,33 @@ pub struct ModelThroughputHint { /// be filtered through `is_fresh_at`. #[serde(skip_serializing_if = "Option::is_none")] pub measurement: Option, + /// The node's prompt-processing cost for this model, measured on its own + /// requests whether or not they hit a cache, so a router can cost the + /// node cold. `None` from a node that predates it or has not measured one. + #[serde(skip_serializing_if = "Option::is_none")] + pub prefill: Option, +} + +/// A node's measured prefill cost for one model. Relays forward it unchanged. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct PrefillMeasurement { + pub micros_per_token: u64, + /// Wall-clock time of the newest sample behind the rate. + pub observed_at_unix_ms: u64, +} + +impl PrefillMeasurement { + /// The rate when it is usable at `now_unix_ms`: measured, dated no later + /// than the allowed clock skew, and no older than + /// [`MAX_ADVERTISED_THROUGHPUT_WINDOW_MS`]. + pub fn fresh_micros_per_token(&self, now_unix_ms: u64) -> Option { + (self.micros_per_token > 0 + && self.observed_at_unix_ms + <= now_unix_ms.saturating_add(MAX_THROUGHPUT_FUTURE_SKEW_MS) + && now_unix_ms.saturating_sub(self.observed_at_unix_ms) + <= MAX_ADVERTISED_THROUGHPUT_WINDOW_MS) + .then_some(self.micros_per_token) + } } /// The measuring node's account of the samples behind a hint. Relays forward @@ -179,6 +206,7 @@ mod tests { avg_tokens_per_second_milli: 40_000, throughput_samples: 3, measurement, + prefill: None, } } @@ -322,4 +350,27 @@ mod tests { "the freshness guard only protects a still-usable held hint" ); } + + #[test] + fn a_prefill_rate_is_usable_only_while_fresh_and_measured() { + let now = 1_800_000_000_000; + let at = |observed_at_unix_ms, micros_per_token| PrefillMeasurement { + micros_per_token, + observed_at_unix_ms, + }; + assert_eq!(at(now - 1_000, 250).fresh_micros_per_token(now), Some(250)); + assert_eq!( + at(now - MAX_ADVERTISED_THROUGHPUT_WINDOW_MS, 250).fresh_micros_per_token(now), + Some(250) + ); + assert_eq!( + at(now - MAX_ADVERTISED_THROUGHPUT_WINDOW_MS - 1, 250).fresh_micros_per_token(now), + None + ); + assert_eq!( + at(now + MAX_THROUGHPUT_FUTURE_SKEW_MS + 1, 250).fresh_micros_per_token(now), + None + ); + assert_eq!(at(now, 0).fresh_micros_per_token(now), None); + } } diff --git a/mesh/crates/mesh-llm-protocol/proto/node.proto b/mesh/crates/mesh-llm-protocol/proto/node.proto index 31c55792b4..92fe009257 100644 --- a/mesh/crates/mesh-llm-protocol/proto/node.proto +++ b/mesh/crates/mesh-llm-protocol/proto/node.proto @@ -386,6 +386,11 @@ message AdvertisedModelThroughput { optional uint32 window_ms = 5; // What the average measures. optional ThroughputMeasurementKind kind = 6; + // The node's prompt-processing cost for this model in microseconds per + // token, measured on its own requests with or without a cache hit, and the + // wall-clock time of its newest sample. Both or neither. + optional uint64 prefill_micros_per_token = 7; + optional uint64 prefill_observed_at_unix_ms = 8; } enum ThroughputMeasurementKind { diff --git a/mesh/crates/mesh-llm-protocol/src/proto/node.rs b/mesh/crates/mesh-llm-protocol/src/proto/node.rs index fea7f2d2bc..b8dd303e54 100644 --- a/mesh/crates/mesh-llm-protocol/src/proto/node.rs +++ b/mesh/crates/mesh-llm-protocol/src/proto/node.rs @@ -578,6 +578,13 @@ pub struct AdvertisedModelThroughput { /// What the average measures. #[prost(enumeration = "ThroughputMeasurementKind", optional, tag = "6")] pub kind: ::core::option::Option, + /// The node's prompt-processing cost for this model in microseconds per + /// token, measured on its own requests with or without a cache hit, and the + /// wall-clock time of its newest sample. Both or neither. + #[prost(uint64, optional, tag = "7")] + pub prefill_micros_per_token: ::core::option::Option, + #[prost(uint64, optional, tag = "8")] + pub prefill_observed_at_unix_ms: ::core::option::Option, } #[derive(Clone, PartialEq, ::prost::Message)] pub struct CacheAffinityAdvertisement { diff --git a/mesh/crates/mesh-llm-routing/src/cache_inventory.rs b/mesh/crates/mesh-llm-routing/src/cache_inventory.rs index 479a27bed2..e5624f407c 100644 --- a/mesh/crates/mesh-llm-routing/src/cache_inventory.rs +++ b/mesh/crates/mesh-llm-routing/src/cache_inventory.rs @@ -125,6 +125,8 @@ pub struct CacheInventory { max_entries: usize, ttl: Duration, model_prefill_micros_per_token: HashMap, + /// When each model's rate last took a sample. + model_prefill_observed_at: HashMap, } impl CacheInventory { @@ -183,6 +185,15 @@ impl CacheInventory { / 4; }) .or_insert(prefill_micros_per_token); + self.model_prefill_observed_at + .insert(model.to_string(), Instant::now()); + } + + /// This node's calibrated rate for `model` and when it last took a + /// sample, for gossip; `None` before the first measurement. + pub fn model_prefill_measurement(&self, model: &str) -> Option<(u64, Instant)> { + let rate = self.model_prefill_micros_per_token(model)?; + Some((rate, *self.model_prefill_observed_at.get(model)?)) } pub fn record_l1_hit( @@ -364,6 +375,7 @@ impl Default for CacheInventory { max_entries: CACHE_AFFINITY_MAX_ENTRIES, ttl: CACHE_AFFINITY_TTL, model_prefill_micros_per_token: HashMap::new(), + model_prefill_observed_at: HashMap::new(), } } } @@ -544,6 +556,12 @@ mod tests { assert_eq!(inventory.model_prefill_micros_per_token("model"), None); inventory.observe_prefill_cost("model", 800); assert_eq!(inventory.model_prefill_micros_per_token("model"), Some(800)); + let (rate, observed_at) = inventory + .model_prefill_measurement("model") + .expect("a measured rate is dated for gossip"); + assert_eq!(rate, 800); + assert!(observed_at.elapsed() < Duration::from_secs(60)); + assert_eq!(inventory.model_prefill_measurement("other"), None); assert_eq!(inventory.model_prefill_micros_per_token("other"), None); } diff --git a/mesh/docs/design/METRICS.md b/mesh/docs/design/METRICS.md index 5375dde54f..2ca36ed140 100644 --- a/mesh/docs/design/METRICS.md +++ b/mesh/docs/design/METRICS.md @@ -50,6 +50,8 @@ Any attempt keeps an entry alive, failures included, so activity says nothing ab Advertised hints (`AdvertisedModelThroughput` in `node.proto`, in both the peer announcement and the signed node record) also say when and how they were measured: `observed_at_unix_ms` is the wall-clock time of the newest sample, `window_ms` how much longer the average stays evidence (what remains of the oldest sample's 15 minutes, so a receiver never credits a sample past its age limit), and `kind` the measurement (`END_TO_END_ATTEMPT`, completion tokens over the whole routed attempt). The measuring node sets them and relays forward them unchanged, so receiving a hint again never makes it younger. Merging a relayed announcement keeps a held hint that is dated later than the relayed one, or dated where the relayed one is not (an older relay drops the fields); only the peer's own direct gossip replaces its hints outright. A receiver ranks on a peer's hint only while it is fresh: a known kind, measured no more than 2 minutes in the future (clock skew), and no older than the shorter of the sender's window and 15 minutes. A zero time or window is dropped as malformed without dropping the hint. A hint from a node that predates these fields has no measurement, so its age is unknown and it ranks as unmeasured; the peer itself stays discoverable and routable. +A hint can also carry the node's prompt-processing cost for that model: `prefill_micros_per_token`, the node's own calibrated rate (an EWMA of `prompt_ms` minus `cache_restore_ms` over `suffix_prefill_n` from its local replies, with or without a cache hit), and `prefill_observed_at_unix_ms`, the wall-clock time of its newest sample. Cache-aware routing reads it to cost the node cold for a prefix the node does not hold. Both fields come together or the rate is ignored, as is a zero rate. A receiver uses it only while it is measured no more than 2 minutes in the future and is no more than 15 minutes old. A node that predates the fields still carries a rate on its cache-affinity entries, which routing falls back to while those last. + All currently implemented metrics are `local-only`. None of them are new gossip or protocol fields. ### `/api/runtime/llama` From 714457b94c1d0f5fdfa9d43ab21471682ad8265a Mon Sep 17 00:00:00 2001 From: Virgile Pourchet <222121099+Virgile-pct@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:33:42 +0100 Subject: [PATCH 5/7] fix(routing): size requests at each model's learned bytes per token and keep short samples out of the prefill rate Calibration on three local nodes showed both inputs biased toward cold: the fixed 4 bytes/token overestimated a 1,019-token prompt at 1,623 while the 8 bytes/token credit gave 760 of 946 cached tokens, and 48-token suffix samples measured 29 ms/token against 13 ms/token on long prompts. Routers now learn bytes per token per model from usage.prompt_tokens on delivered replies (prompts of 64 tokens or more, clamped to 1-32 bytes) and size the prompt at that ratio, the shared prefix at 1.25 times it. The prefill rate only learns from replies that prefilled at least 256 tokens. --- .../src/network/affinity.rs | 87 ++++++++++++++++++- .../src/network/openai/response/cache_cost.rs | 23 ++++- .../openai/response/stream_translation.rs | 2 +- .../src/network/openai/transport.rs | 16 ++++ .../openai/transport_route_exhaustion.rs | 1 + .../network/openai/transport_route_model.rs | 17 +++- .../mesh-llm-routing/src/request_cost.rs | 69 +++++++++++++++ mesh/docs/design/METRICS.md | 2 +- 8 files changed, 209 insertions(+), 8 deletions(-) diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs b/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs index 278ec372ce..2d1a7c2fe2 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs @@ -7,6 +7,11 @@ use iroh::EndpointId; use mesh_llm_routing::affinity as shared_affinity; use mesh_llm_routing::request_cost; +/// Fewest prompt tokens a reply needs before it teaches the bytes-per-token +/// ratio, and how many models the ratio is kept for. +const MIN_PROMPT_SIZE_SAMPLE_TOKENS: u64 = 64; +const PROMPT_SIZE_MAX_MODELS: usize = 1_024; + /// Smallest credited prefix that lets a cache hit override normal routing. const MIN_SAVED_TOKENS: u32 = mesh_llm_routing::cache_aware::DEFAULT_MIN_SAVED_TOKENS; use serde::Serialize; @@ -77,6 +82,9 @@ struct AffinityState { cache_leases: HashMap, cache_lease_lru: VecDeque, cache_lease_epoch: u64, + /// Prompt bytes per token learned per model from completed replies, in + /// thousandths. + prompt_bytes_per_token_milli: HashMap, } #[derive(Clone)] @@ -118,6 +126,46 @@ impl AffinityRouter { } } + /// Learn how many prompt bytes `model` spends per token from a reply's + /// `usage.prompt_tokens`, so the next request is sized from its body at a + /// measured ratio rather than a fixed guess. Small prompts are skipped: + /// the chat template's own tokens would dominate them. + pub(crate) fn observe_prompt_size(&self, model: &str, prompt_bytes: usize, prompt_tokens: u64) { + if prompt_tokens < MIN_PROMPT_SIZE_SAMPLE_TOKENS || prompt_bytes == 0 { + return; + } + let ratio = u64::try_from(prompt_bytes) + .unwrap_or(u64::MAX) + .saturating_mul(1_000) + / prompt_tokens; + let ratio = u32::try_from(ratio).unwrap_or(u32::MAX).clamp( + request_cost::MIN_BYTES_PER_TOKEN_MILLI, + request_cost::MAX_BYTES_PER_TOKEN_MILLI, + ); + let mut state = self + .inner + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let known = state.prompt_bytes_per_token_milli.contains_key(model); + if !known && state.prompt_bytes_per_token_milli.len() >= PROMPT_SIZE_MAX_MODELS { + return; + } + state + .prompt_bytes_per_token_milli + .entry(model.to_string()) + .and_modify(|previous| *previous = (previous.saturating_mul(3) + ratio) / 4) + .or_insert(ratio); + } + + pub(crate) fn prompt_bytes_per_token_milli(&self, model: &str) -> Option { + self.inner + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .prompt_bytes_per_token_milli + .get(model) + .copied() + } + pub fn stats_snapshot(&self) -> AffinityStatsSnapshot { let mut stats = AffinityStatsSnapshot::from_affinity_stats( self.prefix.stats_snapshot(), @@ -440,9 +488,23 @@ pub(crate) fn cache_prefix_hash(parsed_body: Option<&Value>) -> Option { } /// Size of this request and of the prefix it provably shares, with the same -/// scaffold rule as `routing_keys`, so the credited prefix is what was hashed. -pub(crate) fn request_cost_input(parsed_body: Option<&Value>) -> request_cost::RequestCostInput { - request_cost::request_cost_input_from_body(parsed_body, true) +/// scaffold rule as `routing_keys`, so the credited prefix is what was hashed, +/// at the model's learned bytes per token when one is known. +pub(crate) fn request_cost_input( + parsed_body: Option<&Value>, + affinity: &AffinityRouter, + model: &str, +) -> request_cost::RequestCostInput { + request_cost::request_cost_input_from_body_calibrated( + parsed_body, + true, + affinity.prompt_bytes_per_token_milli(model), + ) +} + +/// Prompt bytes of a request body, as `request_cost_input` measures them. +pub(crate) fn prompt_bytes(parsed_body: Option<&Value>) -> Option { + parsed_body.map(shared_affinity::prompt_bytes_from_body) } impl crate::mesh::Node { @@ -943,6 +1005,25 @@ mod tests { assert_eq!(prepared.cache_target, None); } + #[test] + fn the_prompt_ratio_is_learned_from_large_enough_replies() { + let affinity = AffinityRouter::new(); + assert_eq!(affinity.prompt_bytes_per_token_milli("qwen"), None); + // The chat template dominates a tiny prompt, so it teaches nothing. + affinity.observe_prompt_size("qwen", 400, MIN_PROMPT_SIZE_SAMPLE_TOKENS - 1); + assert_eq!(affinity.prompt_bytes_per_token_milli("qwen"), None); + affinity.observe_prompt_size("qwen", 6_300, 1_000); + assert_eq!(affinity.prompt_bytes_per_token_milli("qwen"), Some(6_300)); + affinity.observe_prompt_size("qwen", 4_000, 1_000); + assert_eq!(affinity.prompt_bytes_per_token_milli("qwen"), Some(5_725)); + // Absurd ratios are clamped before they enter the average. + affinity.observe_prompt_size("other", 10, 1_000); + assert_eq!( + affinity.prompt_bytes_per_token_milli("other"), + Some(request_cost::MIN_BYTES_PER_TOKEN_MILLI) + ); + } + #[tokio::test] async fn provider_confirmed_local_hit_is_selectable() { let node = diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/cache_cost.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/cache_cost.rs index 5278a9f3c3..9d538f4228 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/cache_cost.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/cache_cost.rs @@ -5,6 +5,12 @@ pub(in crate::network::openai) struct CacheCostObservation { pub(in crate::network::openai) prefill_micros_per_token: Option, } +/// Fewest prefilled tokens a sample needs before it calibrates the rate. A +/// short suffix is dominated by per-request overhead and by attention over the +/// restored prefix: on a CPU node, a 48-token suffix after a 946-token hit +/// measured 29 ms/token where a 1,256-token cold prompt measured 13 ms/token. +const MIN_PREFILL_RATE_SAMPLE_TOKENS: u64 = 256; + fn timing_micros(timings: &serde_json::Value, name: &str) -> Option { let millis = timings.get(name)?.as_f64()?; if !millis.is_finite() || millis < 0.0 || millis > u64::MAX as f64 / 1_000.0 { @@ -28,7 +34,7 @@ pub(in crate::network::openai) fn parse_cache_cost_from_json_body( .get("suffix_prefill_n") .and_then(serde_json::Value::as_u64); let prefill_micros_per_token = match (prompt_micros, suffix_prefill_tokens) { - (Some(prompt), Some(tokens)) if tokens > 0 => Some( + (Some(prompt), Some(tokens)) if tokens >= MIN_PREFILL_RATE_SAMPLE_TOKENS => Some( prompt .saturating_sub(restore_micros) .div_ceil(tokens) @@ -58,14 +64,27 @@ mod tests { } }); + // Too short a suffix to calibrate the rate; the other costs stand. assert_eq!( parse_cache_cost_from_json_body(response.to_string().as_bytes()), Some(CacheCostObservation { queue_delay_micros: 1_250, restore_micros: 2_500, - prefill_micros_per_token: Some(2_000), + prefill_micros_per_token: None, }) ); + let response = serde_json::json!({ + "timings": { + "prompt_ms": 514.5, + "cache_restore_ms": 2.5, + "suffix_prefill_n": MIN_PREFILL_RATE_SAMPLE_TOKENS + } + }); + assert_eq!( + parse_cache_cost_from_json_body(response.to_string().as_bytes()) + .and_then(|cost| cost.prefill_micros_per_token), + Some(2_000) + ); assert_eq!(parse_cache_cost_from_json_body(br#"{}"#), None); } } diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/stream_translation.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/stream_translation.rs index 7008b96202..c32fae5ae2 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/stream_translation.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/stream_translation.rs @@ -959,7 +959,7 @@ mod tests { .expect("relay") }); - let usage_chunk = r#"{"id":"chatcmpl-y","object":"chat.completion.chunk","created":1,"model":"qwen","choices":[{"index":0,"delta":{"content":"hello"},"finish_reason":null}],"usage":{"prompt_tokens":2,"completion_tokens":7,"total_tokens":9},"timings":{"prompt_ms":6.0,"queue_wait_ms":1.0,"cache_restore_ms":2.0,"suffix_prefill_n":2}}"#; + let usage_chunk = r#"{"id":"chatcmpl-y","object":"chat.completion.chunk","created":1,"model":"qwen","choices":[{"index":0,"delta":{"content":"hello"},"finish_reason":null}],"usage":{"prompt_tokens":2,"completion_tokens":7,"total_tokens":9},"timings":{"prompt_ms":514.0,"queue_wait_ms":1.0,"cache_restore_ms":2.0,"suffix_prefill_n":256}}"#; upstream_writer .write_all(format!("data: {usage_chunk}\n\n").as_bytes()) .await diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport.rs index a4d499c4eb..cf6465cdf1 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport.rs @@ -317,6 +317,9 @@ struct MeshAttemptState { attempts: usize, last_retryable: bool, refreshed: bool, + /// Prompt bytes of the request body, to learn the model's bytes per token + /// from the reply's `usage.prompt_tokens`. + prompt_bytes: Option, } enum MeshAttemptDisposition { @@ -603,6 +606,8 @@ async fn build_mesh_request_plan( ); let request_cost = crate::network::affinity::request_cost_input( super::workload_routing::affinity_body(request), + affinity, + effective_model.as_deref().unwrap_or_default(), ); let (target_hosts, equivalent_hosts) = order_mesh_target_hosts( node, @@ -786,6 +791,9 @@ async fn route_mesh_request_attempts( attempts: 0, last_retryable: false, refreshed: false, + prompt_bytes: crate::network::affinity::prompt_bytes( + super::workload_routing::affinity_body(request), + ), }; for (idx, target_host) in target_hosts.iter().enumerate() { transfer_mesh_reservation(reservation.as_mut(), *target_host); @@ -1010,6 +1018,14 @@ fn handle_mesh_attempt_result( usage.completion_tokens, outcome, ); + if (200..300).contains(&status_code) + && let Some(((model, bytes), tokens)) = context + .effective_model + .zip(context.state.prompt_bytes) + .zip(usage.prompt_tokens) + { + context.affinity.observe_prompt_size(model, bytes, tokens); + } } handle_delivered_mesh_attempt(context, status_code); MeshAttemptDisposition::Return(RouteAttemptResult::Delivered { diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_route_exhaustion.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_route_exhaustion.rs index d5b9717486..20c67b9ac6 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_route_exhaustion.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_route_exhaustion.rs @@ -53,6 +53,7 @@ mod tests { attempts, timeout_attempts, refreshed: false, + prompt_bytes: None, }; let status = state.exhausted_status(); assert_eq!(status, expected); diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_route_model.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_route_model.rs index 246158db82..81cd824042 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_route_model.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_route_model.rs @@ -109,6 +109,9 @@ struct RouteModelState { attempts: usize, timeout_attempts: usize, refreshed: bool, + /// Prompt bytes of the request body, to learn the model's bytes per token + /// from the reply's `usage.prompt_tokens`. + prompt_bytes: Option, } enum RouteModelDisposition { @@ -133,7 +136,7 @@ async fn cache_target_for_request( candidates: &[election::InferenceTarget], ) -> Option { let prefix_hash = crate::network::affinity::cache_prefix_hash(affinity_body)?; - let request = crate::network::affinity::request_cost_input(affinity_body); + let request = crate::network::affinity::request_cost_input(affinity_body, affinity, model); node.cache_target_with_lease(affinity, model, prefix_hash, candidates, request) .await } @@ -282,6 +285,7 @@ async fn route_model_request_inner(args: RouteModelRequestArgs<'_>) -> RouteDisp attempts: 0, timeout_attempts: 0, refreshed: false, + prompt_bytes: crate::network::affinity::prompt_bytes(affinity_body), }; // `request.raw` was already stabilized at ingress (finalize_forwarded_request // resolves the capsule client nonce once, before target selection), so every @@ -547,6 +551,16 @@ fn handle_delivered_route_model_attempt( output_digests: crate::plugin::openai_exchange::ExchangeOutputDigests, ) -> RouteModelDisposition { update_local_cache_evidence(&context, status_code, usage.as_ref(), cache_cost); + if (200..300).contains(&status_code) + && let Some((bytes, tokens)) = context + .state + .prompt_bytes + .zip(usage.as_ref().and_then(|usage| usage.prompt_tokens)) + { + context + .affinity + .observe_prompt_size(context.model, bytes, tokens); + } context.node.record_routed_request( Some(context.model), context.state.attempts, @@ -893,6 +907,7 @@ mod tests { attempts: 1, timeout_attempts: 0, refreshed: false, + prompt_bytes: None, }; (node, affinity, target, selection, state) } diff --git a/mesh/crates/mesh-llm-routing/src/request_cost.rs b/mesh/crates/mesh-llm-routing/src/request_cost.rs index a1a05568e2..9d24acf9f4 100644 --- a/mesh/crates/mesh-llm-routing/src/request_cost.rs +++ b/mesh/crates/mesh-llm-routing/src/request_cost.rs @@ -24,6 +24,22 @@ pub const SHARED_PREFIX_BYTES_PER_TOKEN: usize = 8; pub fn request_cost_input_from_body( body: Option<&Value>, prefix_fallback_to_first_user: bool, +) -> RequestCostInput { + request_cost_input_from_body_calibrated(body, prefix_fallback_to_first_user, None) +} + +/// Bounds on a learned bytes-per-token ratio, in thousandths. +pub const MIN_BYTES_PER_TOKEN_MILLI: u32 = 1_000; +pub const MAX_BYTES_PER_TOKEN_MILLI: u32 = 32_000; + +/// Like [`request_cost_input_from_body`], with the model's bytes per token +/// learned from its own replies when known (`usage.prompt_tokens` against the +/// prompt bytes). The prompt is sized at that ratio; the shared prefix at 1.25 +/// times it, so a credit still errs toward too small. +pub fn request_cost_input_from_body_calibrated( + body: Option<&Value>, + prefix_fallback_to_first_user: bool, + bytes_per_token_milli: Option, ) -> RequestCostInput { let Some(body) = body else { return RequestCostInput { @@ -34,6 +50,27 @@ pub fn request_cost_input_from_body( let prompt_bytes = prompt_bytes_from_body(body); let shared_bytes = scaffold_prefix_from_body(body, prefix_fallback_to_first_user) .map_or(0, |scaffold| scaffold.bytes); + if let Some(ratio) = bytes_per_token_milli + .map(|ratio| ratio.clamp(MIN_BYTES_PER_TOKEN_MILLI, MAX_BYTES_PER_TOKEN_MILLI)) + { + let ratio = u64::from(ratio); + let tokens = |bytes: usize, ratio: u64| { + u64::try_from(bytes) + .unwrap_or(u64::MAX) + .saturating_mul(1_000) + / ratio + }; + return RequestCostInput { + prompt_tokens: Some(TokenEstimate { + tokens: u32::try_from(tokens(prompt_bytes, ratio)).unwrap_or(u32::MAX), + source: TokenSource::Calibrated, + }), + reusable_prefix_tokens: Some( + u32::try_from(tokens(shared_bytes, ratio.saturating_mul(5) / 4)) + .unwrap_or(u32::MAX), + ), + }; + } RequestCostInput { prompt_tokens: Some(TokenEstimate { tokens: u32::try_from(prompt_bytes.div_ceil(PROMPT_BYTES_PER_TOKEN)) @@ -54,6 +91,9 @@ pub enum TokenSource { Measured, /// Derived from request size with a conservative ratio. Heuristic, + /// Derived from request size with the ratio learned from this model's + /// replies. + Calibrated, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -613,4 +653,33 @@ mod tests { }; assert!(!can_earn_cache_credit(unsized_prefix, 256)); } + + #[test] + fn a_learned_ratio_sizes_the_prompt_and_still_credits_low() { + let body = chat_body(8_000, 2_000); + let prompt_bytes = prompt_bytes_from_body(&body); + let shared_bytes = scaffold_prefix_from_body(&body, true) + .expect("system scaffold") + .bytes; + let sized = request_cost_input_from_body_calibrated(Some(&body), true, Some(6_300)); + let prompt = sized.prompt_tokens.expect("sized"); + assert_eq!(prompt.source, TokenSource::Calibrated); + assert_eq!(prompt.tokens as usize, prompt_bytes * 1_000 / 6_300); + // The shared prefix at 1.25 times the ratio: below its own estimate. + assert_eq!( + sized.reusable_prefix_tokens, + Some((shared_bytes * 1_000 / 7_875) as u32) + ); + assert!(sized.reusable_prefix_tokens.unwrap() < (shared_bytes * 1_000 / 6_300) as u32); + // Out-of-range ratios are clamped, and no ratio keeps the fixed guess. + let tiny = request_cost_input_from_body_calibrated(Some(&body), true, Some(10)); + assert_eq!( + tiny.prompt_tokens.map(|p| p.tokens as usize), + Some(prompt_bytes * 1_000 / MIN_BYTES_PER_TOKEN_MILLI as usize) + ); + assert_eq!( + request_cost_input_from_body_calibrated(Some(&body), true, None), + request_cost_input_from_body(Some(&body), true) + ); + } } diff --git a/mesh/docs/design/METRICS.md b/mesh/docs/design/METRICS.md index 2ca36ed140..3ca0cf5a75 100644 --- a/mesh/docs/design/METRICS.md +++ b/mesh/docs/design/METRICS.md @@ -50,7 +50,7 @@ Any attempt keeps an entry alive, failures included, so activity says nothing ab Advertised hints (`AdvertisedModelThroughput` in `node.proto`, in both the peer announcement and the signed node record) also say when and how they were measured: `observed_at_unix_ms` is the wall-clock time of the newest sample, `window_ms` how much longer the average stays evidence (what remains of the oldest sample's 15 minutes, so a receiver never credits a sample past its age limit), and `kind` the measurement (`END_TO_END_ATTEMPT`, completion tokens over the whole routed attempt). The measuring node sets them and relays forward them unchanged, so receiving a hint again never makes it younger. Merging a relayed announcement keeps a held hint that is dated later than the relayed one, or dated where the relayed one is not (an older relay drops the fields); only the peer's own direct gossip replaces its hints outright. A receiver ranks on a peer's hint only while it is fresh: a known kind, measured no more than 2 minutes in the future (clock skew), and no older than the shorter of the sender's window and 15 minutes. A zero time or window is dropped as malformed without dropping the hint. A hint from a node that predates these fields has no measurement, so its age is unknown and it ranks as unmeasured; the peer itself stays discoverable and routable. -A hint can also carry the node's prompt-processing cost for that model: `prefill_micros_per_token`, the node's own calibrated rate (an EWMA of `prompt_ms` minus `cache_restore_ms` over `suffix_prefill_n` from its local replies, with or without a cache hit), and `prefill_observed_at_unix_ms`, the wall-clock time of its newest sample. Cache-aware routing reads it to cost the node cold for a prefix the node does not hold. Both fields come together or the rate is ignored, as is a zero rate. A receiver uses it only while it is measured no more than 2 minutes in the future and is no more than 15 minutes old. A node that predates the fields still carries a rate on its cache-affinity entries, which routing falls back to while those last. +A hint can also carry the node's prompt-processing cost for that model: `prefill_micros_per_token`, the node's own calibrated rate (an EWMA of `prompt_ms` minus `cache_restore_ms` over `suffix_prefill_n` from its local replies, with or without a cache hit, skipping replies that prefilled fewer than 256 tokens, where per-request overhead dominates), and `prefill_observed_at_unix_ms`, the wall-clock time of its newest sample. Cache-aware routing reads it to cost the node cold for a prefix the node does not hold. Both fields come together or the rate is ignored, as is a zero rate. A receiver uses it only while it is measured no more than 2 minutes in the future and is no more than 15 minutes old. A node that predates the fields still carries a rate on its cache-affinity entries, which routing falls back to while those last. All currently implemented metrics are `local-only`. None of them are new gossip or protocol fields. From 65c205730d71dbf0272ee98128ac4b0888973a34 Mon Sep 17 00:00:00 2001 From: Virgile Pourchet <222121099+Virgile-pct@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:51:05 +0100 Subject: [PATCH 6/7] fix(routing): route to the cheapest cold candidate when it beats the hit, and let the estimate override a lease When the best hit lost, routing fell back to the ordinary order, which knows neither costs nor caches: in calibration it picked the slow warm node anyway (16.2 s where the fast node served cold in 9.7 s). The decision now names the cheapest cold candidate and routing leads with it, as the issue's acceptance criterion asks. A hit that wins by less than the margin is reported as Marginal and keeps the ordinary order. The estimate now runs before the cache lease: the lease only stands in when nothing can be costed yet, so a previous decision never bypasses a costed comparison. --- .../src/network/affinity.rs | 62 +++++++++++------ .../network/openai/transport_tests/routing.rs | 42 +++++++----- .../mesh-llm-routing/src/request_cost.rs | 66 ++++++++++++++----- 3 files changed, 117 insertions(+), 53 deletions(-) diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs b/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs index 2d1a7c2fe2..fc42f0cd3e 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs @@ -579,9 +579,11 @@ impl crate::mesh::Node { .invalidate(model, prefix_hash) } - /// Choose a cache target for this request, honouring a short lease only - /// for a request that could earn cache credit at all. Shared by the model - /// route and the remote-host ordering, so both apply the same estimate. + /// Choose a target for this request from cache evidence, shared by the + /// model route and the remote-host ordering so both apply the same + /// estimate. The estimate comes first: a short lease, the memory of a + /// recent decision, only stands in when nothing can be costed yet (a hit + /// not advertised so far), so it never overrides a costed comparison. pub(crate) async fn cache_target_with_lease( &self, affinity: &AffinityRouter, @@ -593,24 +595,30 @@ impl crate::mesh::Node { if !request_cost::can_earn_cache_credit(request, MIN_SAVED_TOKENS) { return None; } - if let Some(target) = affinity.lookup_cache_lease(model, prefix_hash, candidates) { - return Some(target); - } let lease_epoch = affinity.cache_lease_epoch(); - let selected = self - .select_cache_target(model, prefix_hash, candidates, request) - .await; - if let Some(target) = selected.as_ref() { - affinity.remember_cache_lease_if_epoch(model, prefix_hash, target, lease_epoch); + match self + .cache_route_decision(model, prefix_hash, candidates, request) + .await + { + request_cost::CacheRouteDecision::CacheHitWins { target, .. } + | request_cost::CacheRouteDecision::ColdWins { target, .. } => { + affinity.remember_cache_lease_if_epoch(model, prefix_hash, &target, lease_epoch); + Some(target) + } + request_cost::CacheRouteDecision::Marginal => None, + request_cost::CacheRouteDecision::Incomparable(_) + | request_cost::CacheRouteDecision::NoEvidence => { + affinity.lookup_cache_lease(model, prefix_hash, candidates) + } } - selected } /// Probe bounded local and peer advertisements for the exact request - /// prefix, and route to a hit only when, for this request, it is cheaper - /// than serving it cold on any candidate, the hit's own included - /// (`request_cost::decide_cache_route`). Missing, expired, unmeasured or - /// incomparable evidence preserves normal candidate order. + /// prefix and compare the best hit with serving the request cold on every + /// costed candidate (`request_cost::decide_cache_route`): the target is the + /// hit when it wins clearly, the cheapest cold candidate when that is + /// estimated cheaper. A marginal difference, or missing, expired, + /// unmeasured or incomparable evidence, preserves normal candidate order. pub(crate) async fn select_cache_target( &self, model: &str, @@ -621,6 +629,23 @@ impl crate::mesh::Node { if !request_cost::can_earn_cache_credit(request, MIN_SAVED_TOKENS) { return None; } + match self + .cache_route_decision(model, prefix_hash, candidates, request) + .await + { + request_cost::CacheRouteDecision::CacheHitWins { target, .. } + | request_cost::CacheRouteDecision::ColdWins { target, .. } => Some(target), + _ => None, + } + } + + async fn cache_route_decision( + &self, + model: &str, + prefix_hash: u64, + candidates: &[election::InferenceTarget], + request: request_cost::RequestCostInput, + ) -> request_cost::CacheRouteDecision { let (local_evidence, local_rate) = { let mut inventory = self .cache_affinity_inventory @@ -681,10 +706,7 @@ impl crate::mesh::Node { drop(state); let decision = request_cost::decide_cache_route(request, &inputs, MIN_SAVED_TOKENS); tracing::debug!(model, ?decision, "cache route decision"); - match decision { - request_cost::CacheRouteDecision::CacheHitWins { target, .. } => Some(target), - _ => None, - } + decision } } diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_tests/routing.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_tests/routing.rs index c7b147f9b1..e6f81e5e72 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_tests/routing.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/transport_tests/routing.rs @@ -493,8 +493,8 @@ async fn prefix_kill_switch_prevents_cache_evidence_reordering() -> Result<()> { /// The issue's fixture: 4,096 prompt tokens, 1,024 provably shared. A hit on a /// peer prefilling at 2 ms/token costs 6.144 s (plus the 256-token margin), /// while a peer that holds nothing for this prefix but prefills at 0.25 -/// ms/token serves it cold in 1.024 s. The hit only wins once the cold peer is -/// slower than the warm one's estimate. +/// ms/token serves it cold in 1.024 s, so the cold peer is chosen. The hit +/// only wins once the cold peer is slower than the warm one's estimate. #[tokio::test] async fn a_slow_cache_hit_loses_to_a_faster_cold_peer() -> Result<()> { use mesh_llm_routing::cache_inventory::{ @@ -544,6 +544,12 @@ async fn a_slow_cache_hit_loses_to_a_faster_cold_peer() -> Result<()> { let mut cold = test_peer_serving_model(cold_peer, model); cold.cache_affinity = Some(advertisement(prefix_hash ^ 1, 1_024, cold_rate)); node.insert_test_peer(cold).await; + // A lease from an earlier decision does not override a costed one. + affinity.remember_cache_lease( + model, + prefix_hash, + &election::InferenceTarget::Remote(warm_peer), + ); let (ordered, _) = order_mesh_target_hosts( &node, @@ -555,23 +561,21 @@ async fn a_slow_cache_hit_loses_to_a_faster_cold_peer() -> Result<()> { ) .await; - if expect_hit { - assert_eq!( - prepared.cache_target, - Some(election::InferenceTarget::Remote(warm_peer)) - ); - assert_eq!(ordered.first(), Some(&warm_peer)); - } else { - assert_eq!(prepared.cache_target, None, "cold rate {cold_rate}"); - assert!(!prepared.affinity_applied); - } + // The cheaper option leads: the hit, or the faster peer served cold. + let expected = if expect_hit { warm_peer } else { cold_peer }; + assert_eq!( + prepared.cache_target, + Some(election::InferenceTarget::Remote(expected)), + "cold rate {cold_rate}" + ); + assert_eq!(ordered.first(), Some(&expected)); } Ok(()) } /// A peer holding no cache entry is costed cold from the prefill rate on its -/// throughput hint, so a fast idle peer vetoes a slow hit; once that rate is -/// stale it is uncosted again and cannot. +/// throughput hint, so a fast idle peer is chosen over a slow hit; once that +/// rate is stale it is uncosted again and the hit wins. #[tokio::test] async fn a_cold_peer_with_only_its_advertised_rate_can_veto_a_slow_hit() -> Result<()> { use crate::network::metrics::{ModelThroughputHint, PrefillMeasurement}; @@ -641,8 +645,14 @@ async fn a_cold_peer_with_only_its_advertised_rate_can_veto_a_slow_hit() -> Resu ) .await; - let expected = expect_hit.then_some(election::InferenceTarget::Remote(warm_peer)); - assert_eq!(prepared.cache_target, expected, "rate age {rate_age_ms} ms"); + // A fresh rate makes the idle peer the cheaper target; a stale one + // leaves it uncosted, and the hit wins against its own cold cost. + let expected = if expect_hit { warm_peer } else { cold_peer }; + assert_eq!( + prepared.cache_target, + Some(election::InferenceTarget::Remote(expected)), + "rate age {rate_age_ms} ms" + ); } Ok(()) } diff --git a/mesh/crates/mesh-llm-routing/src/request_cost.rs b/mesh/crates/mesh-llm-routing/src/request_cost.rs index 9d24acf9f4..fe009b5fd7 100644 --- a/mesh/crates/mesh-llm-routing/src/request_cost.rs +++ b/mesh/crates/mesh-llm-routing/src/request_cost.rs @@ -262,19 +262,28 @@ pub enum CacheRouteDecision { cost: ServiceCost, best_cold_micros: Option, }, - /// A cold candidate is at least as cheap; keep the normal order. - ColdWins, + /// Serving the request cold on `target` is estimated cheaper than the + /// best hit: route there. Candidate order breaks ties between cold + /// candidates. + ColdWins { + target: InferenceTarget, + micros: u64, + }, + /// The best hit is cheaper, but by less than the margin: too close to + /// act on, so the normal order stands. + Marginal, /// Cache evidence exists but no hit could be costed. Incomparable(MissingComponent), /// No candidate advertised a cache hit worth considering. NoEvidence, } -/// Pick a cache target only when it is cheaper for this request than serving -/// it cold anywhere, including on the cached candidate itself. A hit must also -/// credit at least `min_saved_tokens`, and beat the best cold estimate by the -/// prefill time of those tokens at its own rate, so a marginal estimate never -/// overrides the established order. Candidate order breaks ties. +/// Compare the best cache hit for this request with serving it cold on every +/// costed candidate, the hit's own included. A hit must credit at least +/// `min_saved_tokens` and beat the best cold estimate by the prefill time of +/// those tokens at its own rate; a cold candidate estimated cheaper than the +/// hit is chosen instead; anything in between is too close to act on and +/// keeps the established order. Candidate order breaks ties. pub fn decide_cache_route( request: RequestCostInput, candidates: &[CandidateCostInput], @@ -282,9 +291,18 @@ pub fn decide_cache_route( ) -> CacheRouteDecision { let best_cold = candidates .iter() - .filter_map(|candidate| cold_cost(request, candidate).ok()) - .map(|cost| cost.micros) - .min(); + .filter_map(|candidate| { + cold_cost(request, candidate) + .ok() + .map(|cost| (candidate, cost.micros)) + }) + .fold( + None, + |best: Option<(&CandidateCostInput, u64)>, (candidate, micros)| match best { + Some((_, best_micros)) if best_micros <= micros => best, + _ => Some((candidate, micros)), + }, + ); let mut best_warm: Option<(&CandidateCostInput, ServiceCost)> = None; let mut first_missing = None; @@ -314,11 +332,17 @@ pub fn decide_cache_route( u64::from(min_saved_tokens).saturating_mul(rate) }); match best_cold { - Some(cold) if cost.micros.saturating_add(margin) > cold => CacheRouteDecision::ColdWins, + Some((cold, micros)) if micros < cost.micros => CacheRouteDecision::ColdWins { + target: cold.target.clone(), + micros, + }, + Some((_, micros)) if cost.micros.saturating_add(margin) > micros => { + CacheRouteDecision::Marginal + } _ => CacheRouteDecision::CacheHitWins { target: winner.target.clone(), cost, - best_cold_micros: best_cold, + best_cold_micros: best_cold.map(|(_, micros)| micros), }, } } @@ -365,6 +389,13 @@ mod tests { } } + fn cold_winner(decision: &CacheRouteDecision) -> Option { + match decision { + CacheRouteDecision::ColdWins { target, .. } => Some(target.clone()), + _ => None, + } + } + fn winner(decision: &CacheRouteDecision) -> Option { match decision { CacheRouteDecision::CacheHitWins { target, .. } => Some(target.clone()), @@ -380,7 +411,7 @@ mod tests { &[warm(1, 6_000_000, 250, 3_000, 0), cold(2, 0, 250)], MIN_SAVED, ); - assert_eq!(decision, CacheRouteDecision::ColdWins); + assert_eq!(cold_winner(&decision), Some(remote(2))); } #[test] @@ -392,7 +423,7 @@ mod tests { let short = decide_cache_route(request(2_200, 2_000), &candidates, MIN_SAVED); assert_eq!(winner(&short), Some(remote(1))); let long = decide_cache_route(request(20_000, 2_000), &candidates, MIN_SAVED); - assert_eq!(long, CacheRouteDecision::ColdWins); + assert_eq!(cold_winner(&long), Some(remote(2))); } #[test] @@ -431,7 +462,7 @@ mod tests { &[warm(1, 0, 1_000, 300, 0), cold(2, 0, 790)], MIN_SAVED, ); - assert_eq!(decision, CacheRouteDecision::ColdWins); + assert_eq!(decision, CacheRouteDecision::Marginal); } #[test] @@ -441,7 +472,8 @@ mod tests { &[warm(1, 0, 1_000, 1_000, 1_500_000)], MIN_SAVED, ); - assert_eq!(decision, CacheRouteDecision::ColdWins); + // Serving the request cold on the same node beats restoring it. + assert_eq!(cold_winner(&decision), Some(remote(1))); } #[test] @@ -524,7 +556,7 @@ mod tests { ], MIN_SAVED, ); - assert_eq!(decision, CacheRouteDecision::ColdWins); + assert_eq!(cold_winner(&decision), Some(remote(2))); } fn chat_body(system: usize, user: usize) -> Value { From df59c352ba43e80133efd49a519cd247fbc4e589 Mon Sep 17 00:00:00 2001 From: Virgile Pourchet <222121099+Virgile-pct@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:54:39 +0100 Subject: [PATCH 7/7] fix(routing): keep the lease-free cache target selector to tests Routing now goes through cache_target_with_lease, so the lease-free select_cache_target only served tests and failed Clippy's dead-code check once rebased on main. --- mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs b/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs index fc42f0cd3e..7707e660a6 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/affinity.rs @@ -619,6 +619,9 @@ impl crate::mesh::Node { /// hit when it wins clearly, the cheapest cold candidate when that is /// estimated cheaper. A marginal difference, or missing, expired, /// unmeasured or incomparable evidence, preserves normal candidate order. + /// Routing goes through `cache_target_with_lease`; this lease-free form + /// lets the tests check the decision on its own. + #[cfg(test)] pub(crate) async fn select_cache_target( &self, model: &str,