From 743c22152cd644d97462c1d2471f6406d900cc01 Mon Sep 17 00:00:00 2001 From: benthecarman Date: Fri, 20 Nov 2026 15:09:32 -0600 Subject: [PATCH] Prioritize local requests over mesh requests A node served every request the same way, whoever sent it, so a busy mesh could queue the owner's own requests behind strangers', fill the waiting room ahead of them and evict their warm prompt cache. Every request also shared one prompt cache, so one requester could reuse prefixes another had computed, across the private-routing line too. Each request now gets a tier where it enters the node: local (this machine, private nodes, nodes certified by this node's owner), trusted (nodes certified by a trusted owner) or mesh. A forwarding node names its client's tier; the receiver serves the lower of that claim and its own tier for the sender, so a peer can lower its requests but never raise them. The tier follows the request's work on the node, including peer consultations, virtual-model turns, realtime relays and the plugins that see it. Skippy admits higher tiers first. A lower-tier request moves up one tier for every 16 higher-tier admissions ahead of it, so one that fits the KV budget higher tiers leave free is not starved. Lower-tier waiters cannot fill the waiting queue against a higher tier. Each tier has its own prompt-cache partition, private requests have their own partition within their tier, and the lowest tier is evicted first. An optional local_kv_reserve_percent keeps part of each model's KV budget for local requests. Private requests start no hook consultations, which would pick peers outside their private scope. Split stages carry each request's tier and private flag, and a stage serves its coordinator no higher than the tier its host gives that coordinator. This moves the stage protocol to generation 17; older stages fail negotiation. Owner overrides ([request_tiers.owners]) and the private-node list take effect on a running node without a restart. --- mesh/crates/mesh-llm-config/src/lib.rs | 3 + mesh/crates/mesh-llm-config/src/model.rs | 8 + .../src/model/built_in_schema/declarations.rs | 2 + .../src/model/built_in_schema/presentation.rs | 15 + .../model/built_in_schema/setting_schema.rs | 16 + .../src/model/request_tiers.rs | 126 ++++ mesh/crates/mesh-llm-config/src/validate.rs | 33 + .../mesh-llm-config/src/wiring_status.rs | 14 + .../src/inference/consult.rs | 22 +- .../src/inference/skippy/deployment.rs | 2 + .../src/inference/skippy/hooks.rs | 113 ++- .../src/inference/skippy/materialization.rs | 2 + .../src/inference/skippy/stage/mod.rs | 1 + .../src/inference/skippy/stage/tests.rs | 1 + .../src/inference/skippy/stage/types.rs | 4 + .../src/mesh/config_reload.rs | 540 +++++++++++++ .../mesh-llm-host-runtime/src/mesh/mod.rs | 2 + .../src/mesh/native_inference.rs | 32 +- .../src/mesh/native_inference/streaming.rs | 17 +- .../mesh-llm-host-runtime/src/mesh/node.rs | 3 + .../src/mesh/node/construction.rs | 9 +- .../src/mesh/node/membership.rs | 1 + .../src/mesh/owner_control/mod.rs | 10 +- .../src/mesh/private_nodes.rs | 257 +------ .../src/mesh/request_tier.rs | 379 ++++++++++ .../src/mesh/stage_artifacts.rs | 18 +- .../src/mesh/stage_proto.rs | 1 + .../src/mesh/tests/connections.rs | 2 + .../src/mesh/tests/owner_control.rs | 33 + .../src/mesh/tests/stage_control.rs | 22 + .../src/mesh/tests/stage_control_identity.rs | 1 + .../src/network/openai/forwarded_request.rs | 31 +- .../src/network/openai/ingress.rs | 58 +- .../network/openai/ingress/realtime_relay.rs | 16 +- .../openai/ingress/request_tier_tests.rs | 155 ++++ .../src/network/openai/request_parse.rs | 37 +- .../openai/request_parse/plugin_transform.rs | 86 +++ .../src/network/openai/response/common.rs | 5 + .../src/network/openai/response/routing.rs | 7 +- .../src/network/openai/transport.rs | 27 +- .../src/network/openai/virtual_model/mod.rs | 31 +- .../src/plugin/exchange_lifecycle.rs | 54 +- .../src/plugin/exchange_policy.rs | 27 +- .../mesh-llm-host-runtime/src/plugin/mod.rs | 23 + .../src/plugin/request_transform.rs | 48 +- .../src/plugin/tiered_invocations.rs | 262 +++++++ .../src/protocol/config_tests.rs | 1 + .../src/protocol/convert.rs | 5 +- .../src/protocol/tests/announcements.rs | 8 +- .../src/protocol/tests/config.rs | 4 + .../runtime/config_state_tests/persistence.rs | 1 + .../src/runtime/config_state_tests/support.rs | 1 + .../src/runtime/config_state_tests/sync.rs | 2 + .../src/runtime/local_split/coordinator.rs | 2 +- .../src/runtime/local_split/loading.rs | 27 + .../src/runtime/local_split/test_support.rs | 1 + .../src/runtime/local_split/tests.rs | 19 + mesh/crates/mesh-llm-host-runtime/src/sdk.rs | 2 + .../src/config/resolution.rs | 6 + .../src/config/translation.rs | 1 + .../src/config/types.rs | 2 + mesh/crates/mesh-llm/src/commands/runtime.rs | 1 + mesh/docs/CONFIGURATION_PR8_CLOSEOUT_AUDIT.md | 3 +- mesh/docs/README.md | 1 + mesh/docs/design/TESTING.md | 4 +- mesh/docs/specs/private-routing.md | 6 +- mesh/docs/specs/request-tiers.md | 154 ++++ .../src/docs/pages/config-reference.md | 2 + mesh/website/src/docs/pages/config-toml.md | 25 + skippy/crates/skippy-api/src/serving.rs | 4 + skippy/crates/skippy-api/src/stage.rs | 1 + skippy/crates/skippy-api/src/stage_load.rs | 4 + skippy/crates/skippy-cache/README.md | 6 + skippy/crates/skippy-cache/src/identity.rs | 2 + skippy/crates/skippy-cache/src/radix.rs | 91 ++- skippy/crates/skippy-commands/src/split.rs | 1 + skippy/crates/skippy-inference-api/README.md | 16 + .../src/anthropic/routes.rs | 28 +- .../src/anthropic/translate.rs | 1 + .../skippy-inference-api/src/backend.rs | 24 + .../src/chat/generation.rs | 2 + .../src/chat/request_view.rs | 2 + .../src/generation/request.rs | 5 + .../src/guardrails/compact.rs | 8 + .../src/guardrails/mod.rs | 8 + .../crates/skippy-inference-api/src/hooks.rs | 10 + skippy/crates/skippy-inference-api/src/lib.rs | 5 + .../skippy-inference-api/src/request_tier.rs | 306 ++++++++ .../crates/skippy-inference-api/src/router.rs | 64 +- .../src/router/generation.rs | 18 +- skippy/crates/skippy-protocol/README.md | 13 +- .../skippy-protocol/src/binary/types.rs | 39 +- skippy/crates/skippy-protocol/src/config.rs | 6 + skippy/crates/skippy-protocol/src/lib.rs | 6 +- .../crates/skippy-protocol/src/validation.rs | 6 +- skippy/crates/skippy-scheduler/README.md | 11 + .../skippy-scheduler/src/cache_policy.rs | 171 ++++- .../crates/skippy-scheduler/src/capacity.rs | 36 +- skippy/crates/skippy-scheduler/src/engine.rs | 54 +- skippy/crates/skippy-scheduler/src/lib.rs | 5 +- .../crates/skippy-scheduler/src/sequence.rs | 3 + skippy/crates/skippy-serving/README.md | 6 +- .../binary_messaging/public_frontend.rs | 1 + .../src/binary_transport/stage_execution.rs | 2 +- .../skippy-serving/src/frontend/admission.rs | 88 ++- .../skippy-serving/src/frontend/backend.rs | 16 +- .../src/frontend/backend/inference.rs | 18 +- .../src/frontend/backend/tests/admission.rs | 10 +- .../frontend/backend/tier_admission_tests.rs | 434 +++++++++++ .../src/frontend/embedded_generation.rs | 4 + .../frontend/embedded_generation/lifecycle.rs | 51 +- .../skippy-serving/src/frontend/generation.rs | 2 + .../src/frontend/generation/cache_hints.rs | 95 ++- .../src/frontend/generation/execution.rs | 1 + .../src/frontend/generation/queue.rs | 710 +++++++++--------- .../src/frontend/generation/server.rs | 8 +- .../frontend/generation/service_estimate.rs | 350 +++++++++ .../src/frontend/generation_flow.rs | 6 +- .../src/frontend/iteration_scheduler.rs | 8 +- .../iteration_scheduler/cache_runtime.rs | 17 +- .../direct_batch/coalescing_tests.rs | 1 + .../src/frontend/iteration_scheduler/tests.rs | 4 + .../tests/recurrent_fixture.rs | 4 +- .../local_generation/token_generation.rs | 2 + .../token_generation/cache_prefill.rs | 2 +- .../src/frontend/native_mtp/verify_window.rs | 1 + .../src/frontend/prefix_cache.rs | 10 +- .../frontend/prefix_cache/split_restore.rs | 1 + .../src/frontend/system_one/causal.rs | 12 +- .../src/frontend/system_one/causal/cache.rs | 4 +- .../frontend/system_one/causal/preparation.rs | 7 +- .../frontend/system_one/causal/sequence.rs | 16 +- .../frontend/tests/enc_dec_lane_admission.rs | 1 + .../src/frontend/tests/support.rs | 1 + .../src/frontend/tests/wire_messages.rs | 99 +++ .../src/frontend/wire_messages.rs | 30 + .../src/kv_integration/cache_affinity.rs | 1 + .../src/kv_integration/config.rs | 470 +----------- .../config/tests/reserved_admission.rs | 490 ++++++++++++ .../src/kv_integration/exact_state.rs | 68 +- .../exact_state/resident_preference/tests.rs | 1 + .../exact_state_record_queue_tests.rs | 516 +++++++++++++ .../src/kv_integration/l2_serving.rs | 1 + .../skippy-serving/src/kv_integration/mod.rs | 539 +------------ .../src/kv_integration/records.rs | 11 + .../src/kv_integration/resident_prefix.rs | 36 +- .../resident_prefix/recording.rs | 122 ++- .../src/kv_integration/tier_metrics.rs | 1 + skippy/crates/skippy-serving/src/lib.rs | 1 + .../skippy-serving/src/stage_request_class.rs | 161 ++++ skippy/docs/CAUSAL_DECISIONS.md | 4 +- skippy/docs/DATA_FLOW.md | 4 +- 152 files changed, 6402 insertions(+), 1836 deletions(-) create mode 100644 mesh/crates/mesh-llm-config/src/model/request_tiers.rs create mode 100644 mesh/crates/mesh-llm-host-runtime/src/mesh/config_reload.rs create mode 100644 mesh/crates/mesh-llm-host-runtime/src/mesh/request_tier.rs create mode 100644 mesh/crates/mesh-llm-host-runtime/src/network/openai/ingress/request_tier_tests.rs create mode 100644 mesh/crates/mesh-llm-host-runtime/src/plugin/tiered_invocations.rs create mode 100644 mesh/docs/specs/request-tiers.md create mode 100644 skippy/crates/skippy-inference-api/src/request_tier.rs create mode 100644 skippy/crates/skippy-serving/src/frontend/backend/tier_admission_tests.rs create mode 100644 skippy/crates/skippy-serving/src/frontend/generation/service_estimate.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/config/tests/reserved_admission.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/exact_state_record_queue_tests.rs create mode 100644 skippy/crates/skippy-serving/src/stage_request_class.rs diff --git a/mesh/crates/mesh-llm-config/src/lib.rs b/mesh/crates/mesh-llm-config/src/lib.rs index fdd403df1f..d27a041e96 100644 --- a/mesh/crates/mesh-llm-config/src/lib.rs +++ b/mesh/crates/mesh-llm-config/src/lib.rs @@ -1110,6 +1110,7 @@ gpu_id = "pci:0000:65:00.0" source_runtime, include_str!("managed_models.rs"), include_str!("openai_exchange.rs"), + include_str!("model/request_tiers.rs"), ]; let occurrences = [ ("MeshConfig", 1usize), @@ -1142,8 +1143,10 @@ gpu_id = "pci:0000:65:00.0" ("LoggingConfig", 1), ("LoggingArtifactConfig", 1), ("LoggingWebhookConfig", 1), + ("RequestTiersConfig", 1), ]; let nested = [ + "RequestTiersConfig", "GpuConfig", "MeshRequirementsConfig", "OwnerControlConfig", diff --git a/mesh/crates/mesh-llm-config/src/model.rs b/mesh/crates/mesh-llm-config/src/model.rs index 22c79e4389..459c552f43 100644 --- a/mesh/crates/mesh-llm-config/src/model.rs +++ b/mesh/crates/mesh-llm-config/src/model.rs @@ -2,6 +2,7 @@ mod built_in_schema; mod multimodal; mod private; mod profile; +mod request_tiers; mod runtime; mod schema_types; mod updates; @@ -14,6 +15,7 @@ pub use built_in_schema::{ pub use multimodal::MultimodalConfig; pub(crate) use multimodal::merge_multimodal; pub use private::{PrivateConfig, is_node_id}; +pub use request_tiers::{RequestTierName, RequestTiersConfig}; pub use runtime::{ ActivityAdvertisement, ActivityResponse, DEFAULT_DRAIN_TIMEOUT_MAX_SECS, DEFAULT_DRAIN_TIMEOUT_SECS, RuntimeActivityConfig, RuntimeMode, StartupFailurePolicy, @@ -46,6 +48,9 @@ pub struct MeshConfig { /// `[private]`: the other nodes this node's private requests may reach. #[serde(default, skip_serializing_if = "PrivateConfig::is_empty")] pub private: PrivateConfig, + /// `[request_tiers]`: whose requests this node serves first. + #[serde(default, skip_serializing_if = "RequestTiersConfig::is_empty")] + pub request_tiers: RequestTiersConfig, #[serde(default)] pub telemetry: TelemetryConfig, #[serde(default)] @@ -1231,6 +1236,8 @@ struct RawMeshConfig { #[serde(default)] private: PrivateConfig, #[serde(default)] + request_tiers: RequestTiersConfig, + #[serde(default)] telemetry: TelemetryConfig, #[serde(default)] analytics: AnalyticsConfig, @@ -1359,6 +1366,7 @@ impl<'de> Deserialize<'de> for MeshConfig { mesh_requirements: raw.mesh_requirements, owner_control: raw.owner_control, private: raw.private, + request_tiers: raw.request_tiers, telemetry: raw.telemetry, analytics: raw.analytics, updates: raw.updates, diff --git a/mesh/crates/mesh-llm-config/src/model/built_in_schema/declarations.rs b/mesh/crates/mesh-llm-config/src/model/built_in_schema/declarations.rs index 26cd0600da..1f33e31dd3 100644 --- a/mesh/crates/mesh-llm-config/src/model/built_in_schema/declarations.rs +++ b/mesh/crates/mesh-llm-config/src/model/built_in_schema/declarations.rs @@ -40,6 +40,8 @@ fn build_built_in_config_schema() -> ConfigSchema { ConfigValueSchema::SocketAddr, ), private_nodes_setting(), + request_tier_owners_setting(), + local_kv_reserve_setting(), telemetry_setting("telemetry.enabled", ConfigValueSchema::Boolean), telemetry_setting("telemetry.service_name", ConfigValueSchema::String), telemetry_setting("telemetry.endpoint", ConfigValueSchema::Url), diff --git a/mesh/crates/mesh-llm-config/src/model/built_in_schema/presentation.rs b/mesh/crates/mesh-llm-config/src/model/built_in_schema/presentation.rs index 84d6f932bb..cd48b66b92 100644 --- a/mesh/crates/mesh-llm-config/src/model/built_in_schema/presentation.rs +++ b/mesh/crates/mesh-llm-config/src/model/built_in_schema/presentation.rs @@ -328,6 +328,21 @@ fn process_setting_presentation(rendered: &str) -> Option { ) .placeholder("<64 hex characters>") .hint("text")), + "request_tiers.owners" => Some(sp( + "Request tier overrides", + "Owner id (64 hex characters) to the tier this node serves that owner's nodes at: local, trusted or mesh. By default this node's own owner is local, owners in the trust store are trusted, and everyone else is mesh.", + NETWORK_CATEGORY, + 6, + ) + .placeholder("{\"<64 hex characters>\":\"trusted\"}") + .hint("text")), + "request_tiers.local_kv_reserve_percent" => Some(sp( + "Local KV reserve", + "Percent of each model's KV budget that only local requests may use. 0 reserves nothing. Applies when a model loads.", + NETWORK_CATEGORY, + 7, + ) + .hint("number")), "owner_control.bind" => Some(sp( "Owner-control bind", "Local address used by the owner-control listener. Set this to the same port as the advertised control address when overriding owner-control discovery.", diff --git a/mesh/crates/mesh-llm-config/src/model/built_in_schema/setting_schema.rs b/mesh/crates/mesh-llm-config/src/model/built_in_schema/setting_schema.rs index d5e442ca0d..c7f91e4b4f 100644 --- a/mesh/crates/mesh-llm-config/src/model/built_in_schema/setting_schema.rs +++ b/mesh/crates/mesh-llm-config/src/model/built_in_schema/setting_schema.rs @@ -34,6 +34,22 @@ fn private_nodes_setting() -> ConfigSettingSchema { setting } +/// Read again whenever the config file changes, like `private.nodes`. +fn request_tier_owners_setting() -> ConfigSettingSchema { + let mut setting = basic_setting("request_tiers.owners", ConfigValueSchema::object()); + setting.apply_mode = ConfigApplyMode::DynamicApply; + setting.restart_scope = ConfigRestartScope::None; + setting +} + +/// Sizes each model's admission budget when the model loads. +fn local_kv_reserve_setting() -> ConfigSettingSchema { + basic_setting( + "request_tiers.local_kv_reserve_percent", + ConfigValueSchema::Integer, + ) +} + fn telemetry_setting(path: &str, value_schema: ConfigValueSchema) -> ConfigSettingSchema { let mut setting = basic_setting(path, value_schema); setting.control_surfaces = vec![ConfigControlSurface::ConfigFile, ConfigControlSurface::Api]; diff --git a/mesh/crates/mesh-llm-config/src/model/request_tiers.rs b/mesh/crates/mesh-llm-config/src/model/request_tiers.rs new file mode 100644 index 0000000000..9009c9d37f --- /dev/null +++ b/mesh/crates/mesh-llm-config/src/model/request_tiers.rs @@ -0,0 +1,126 @@ +/// `[request_tiers]`: whose requests this node serves first. +/// +/// A request is served at one of three tiers: `local` (this machine, its +/// private nodes and nodes signed by its own owner key), `trusted` (nodes +/// signed by an owner in the trust store) and `mesh` (everyone else). +/// `owners` overrides the tier for nodes signed by a given owner, and +/// `local_kv_reserve_percent` holds back a share of each model's KV budget +/// for `local` requests. +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct RequestTiersConfig { + /// Owner id (64 hex characters, as `mesh-llm auth status` prints it) to + /// the tier this node serves that owner's nodes at. + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub owners: std::collections::BTreeMap, + /// Percent (0-100) of each model's KV token budget that only `local` + /// requests may reserve. 0, the default, reserves nothing. + #[serde(default, skip_serializing_if = "is_zero")] + pub local_kv_reserve_percent: u8, +} + +/// A request tier, as config names it. +#[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum RequestTierName { + Local, + Trusted, + Mesh, +} + +impl RequestTiersConfig { + pub fn is_empty(&self) -> bool { + self.owners.is_empty() && self.local_kv_reserve_percent == 0 + } + + /// The first owner key that is not an owner id, if any. + pub fn invalid_owner(&self) -> Option<&str> { + self.owners + .keys() + .map(String::as_str) + .find(|owner| !super::is_node_id(owner)) + } + + /// An owner named twice, as keys that differ only in letter case, if + /// any: the two entries would contradict each other. + pub fn repeated_owner(&self) -> Option<&str> { + let mut seen = std::collections::BTreeSet::new(); + self.owners + .keys() + .map(String::as_str) + .find(|owner| !seen.insert(owner.to_ascii_lowercase())) + } +} + +fn is_zero(value: &u8) -> bool { + *value == 0 +} + +#[cfg(test)] +mod tests { + use super::RequestTierName; + use crate::{config_to_toml, parse_config_toml}; + + const OWNER: &str = "0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0"; + + #[test] + fn overrides_and_reserve_survive_a_save_and_reload() { + let config = parse_config_toml(&format!( + "[request_tiers]\nlocal_kv_reserve_percent = 25\n\n[request_tiers.owners]\n\"{OWNER}\" = \"trusted\"\n" + )) + .unwrap(); + assert_eq!( + config.request_tiers.owners.get(OWNER), + Some(&RequestTierName::Trusted) + ); + assert_eq!(config.request_tiers.local_kv_reserve_percent, 25); + let saved = config_to_toml(&config).unwrap(); + assert_eq!( + parse_config_toml(&saved).unwrap().request_tiers, + config.request_tiers + ); + } + + #[test] + fn an_empty_section_is_not_written() { + let saved = config_to_toml(&parse_config_toml("").unwrap()).unwrap(); + assert!(!saved.contains("request_tiers"), "{saved}"); + } + + #[test] + fn an_owner_that_is_not_an_owner_id_is_rejected() { + let error = parse_config_toml("[request_tiers.owners]\nstudio = \"local\"\n") + .unwrap_err() + .to_string(); + assert!(error.contains("request_tiers.owners"), "{error}"); + } + + #[test] + fn an_owner_named_twice_in_different_case_is_rejected() { + let error = parse_config_toml(&format!( + "[request_tiers.owners]\n\"{OWNER}\" = \"mesh\"\n\"{}\" = \"local\"\n", + OWNER.to_ascii_uppercase() + )) + .unwrap_err() + .to_string(); + assert!(error.contains("more than once"), "{error}"); + } + + #[test] + fn an_unknown_tier_is_rejected() { + assert!( + parse_config_toml(&format!( + "[request_tiers.owners]\n\"{OWNER}\" = \"owner\"\n" + )) + .is_err() + ); + } + + #[test] + fn a_reserve_above_one_hundred_percent_is_rejected() { + let error = parse_config_toml("[request_tiers]\nlocal_kv_reserve_percent = 101\n") + .unwrap_err() + .to_string(); + assert!(error.contains("local_kv_reserve_percent"), "{error}"); + } +} diff --git a/mesh/crates/mesh-llm-config/src/validate.rs b/mesh/crates/mesh-llm-config/src/validate.rs index 0eb4c73337..0e0f043d84 100644 --- a/mesh/crates/mesh-llm-config/src/validate.rs +++ b/mesh/crates/mesh-llm-config/src/validate.rs @@ -24,6 +24,38 @@ use crate::*; use anyhow::Result; use skippy_native_runtime::{NativeRuntimeBackendKind, RuntimeSelection}; +/// `[request_tiers]`: owner keys must be owner ids, each named once, and the +/// reserve a percentage. +fn validate_request_tiers_config(request_tiers: &RequestTiersConfig) -> Vec { + let mut diagnostics = Vec::new(); + if let Some(owner) = request_tiers.invalid_owner() { + diagnostics.push(validation_diagnostic( + "request_tiers.owners", + format!( + "request_tiers.owners key {owner:?} is not an owner id (64 hex characters, as `mesh-llm auth status` prints it)" + ), + )); + } + if let Some(owner) = request_tiers.repeated_owner() { + diagnostics.push(validation_diagnostic( + "request_tiers.owners", + format!( + "request_tiers.owners names owner {owner:?} more than once (owner ids are not case-sensitive)" + ), + )); + } + if request_tiers.local_kv_reserve_percent > 100 { + diagnostics.push(validation_diagnostic( + "request_tiers.local_kv_reserve_percent", + format!( + "request_tiers.local_kv_reserve_percent must be between 0 and 100, got {}", + request_tiers.local_kv_reserve_percent + ), + )); + } + diagnostics +} + pub fn validate_config_diagnostics(config: &MeshConfig) -> Vec { let mut diagnostics = Vec::new(); @@ -98,6 +130,7 @@ pub fn validate_config_diagnostics(config: &MeshConfig) -> Vec ), )); } + diagnostics.extend(validate_request_tiers_config(&config.request_tiers)); if let Err(diagnostic) = validate_telemetry_config(&config.telemetry) { diagnostics.push(diagnostic); } diff --git a/mesh/crates/mesh-llm-config/src/wiring_status.rs b/mesh/crates/mesh-llm-config/src/wiring_status.rs index d52f426832..834ca7649f 100644 --- a/mesh/crates/mesh-llm-config/src/wiring_status.rs +++ b/mesh/crates/mesh-llm-config/src/wiring_status.rs @@ -170,6 +170,20 @@ pub const WIRING_MANIFEST: &[WiringEntry] = &[ reason: "", behavior: WiringBehavior::None, }, + WiringEntry { + path: "request_tiers.owners", + status: WiringStatus::Wired, + owner: "n/a", + reason: "", + behavior: WiringBehavior::None, + }, + WiringEntry { + path: "request_tiers.local_kv_reserve_percent", + status: WiringStatus::Wired, + owner: "n/a", + reason: "", + behavior: WiringBehavior::None, + }, WiringEntry { path: "owner_control.bind", status: WiringStatus::Wired, diff --git a/mesh/crates/mesh-llm-host-runtime/src/inference/consult.rs b/mesh/crates/mesh-llm-host-runtime/src/inference/consult.rs index 27ccbedd87..28dbcb8331 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/inference/consult.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/inference/consult.rs @@ -150,6 +150,11 @@ async fn chat_completion_inner( let mut raw = http_request.into_bytes(); raw.extend_from_slice(&body_bytes); + // The peer serves a consultation no higher than the request it is for. + mesh::request_tier::insert_request_tier_header( + &mut raw, + mesh::request_tier::current_request_tier(), + ); let (mut send, mut recv) = node.open_http_tunnel(peer_id).await?; send.write_all(&raw).await?; @@ -429,13 +434,18 @@ fn spawn_second_opinion_call( let msgs = messages.to_vec(); let id = peer.0; let model = peer.1.clone(); - // A spawned task does not inherit the request's private scope; carry it. + // A spawned task does not inherit the request's private scope or tier; + // carry them. let scope = mesh::current_private_scope(); - set.spawn(mesh::with_private_scope(scope, async move { - second_opinion(&node, id, &model, &msgs, timeout) - .await - .map(|text| (text, id, model)) - })); + let tier = mesh::request_tier::current_request_tier(); + set.spawn(mesh::with_private_scope( + scope, + mesh::request_tier::with_request_tier(tier, async move { + second_opinion(&node, id, &model, &msgs, timeout) + .await + .map(|text| (text, id, model)) + }), + )); } async fn await_first_second_opinion( diff --git a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/deployment.rs b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/deployment.rs index ceaf9e1c1b..a13469e4d6 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/deployment.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/deployment.rs @@ -99,6 +99,7 @@ pub(crate) fn remote_stage_load_request( load_mode: LoadMode::LayerPackage, upstream: None, downstream, + max_request_tier: None, } } @@ -192,6 +193,7 @@ pub(crate) fn stage0_config( load_mode: LoadMode::LayerPackage, bind_addr: "127.0.0.1:0".to_string(), upstream: None, + max_request_tier: None, downstream: Some(PeerConfig { persistent_lane_marker: false, stage_id: downstream_stage.stage_id.clone(), diff --git a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/hooks.rs b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/hooks.rs index 4877189a27..4b2dcdb54a 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/hooks.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/hooks.rs @@ -9,6 +9,7 @@ use skippy_inference_api::{ PrefillHookSignals, chat_skippy_hooks_enabled, first_chat_media, generation::GenerationRequest, }; +use crate::mesh::request_tier::with_request_tier; use crate::{inference::virtual_llm, mesh}; const PREFILL_ENTROPY_THRESHOLD: f64 = 3.0; @@ -39,13 +40,21 @@ impl MeshAutoHookPolicy { } } +/// Whether a request may start hook consultations. A private request never +/// does: the server runs outside the request's private scope, so a +/// consultation would pick peers unscoped. Its class comes from a header +/// only the node sets, so a body cannot turn hooks back on. +fn mesh_hooks_allowed(request: &GenerationRequest) -> bool { + chat_skippy_hooks_enabled(request) && !request.request_class.is_private() +} + #[async_trait] impl InferenceHookPolicy for MeshAutoHookPolicy { async fn before_chat_completion( &self, request: &mut GenerationRequest, ) -> InferenceResult { - if !chat_skippy_hooks_enabled(request) { + if !mesh_hooks_allowed(request) { return Ok(ChatHookOutcome::none()); } @@ -58,10 +67,12 @@ impl InferenceHookPolicy for MeshAutoHookPolicy { }; let trigger = media_trigger(media.kind); - let response = self - .executor - .handle_image(trigger, &request.model, &media.url, &media.user_text) - .await; + let response = with_request_tier( + request.request_class.tier(), + self.executor + .handle_image(trigger, &request.model, &media.url, &media.user_text), + ) + .await; Ok(virtual_media_hook_response_to_outcome(&response, media)) } @@ -70,7 +81,7 @@ impl InferenceHookPolicy for MeshAutoHookPolicy { request: &mut GenerationRequest, signals: PrefillHookSignals, ) -> InferenceResult { - if !chat_skippy_hooks_enabled(request) { + if !mesh_hooks_allowed(request) { return Ok(ChatHookOutcome::none()); } @@ -85,15 +96,16 @@ impl InferenceHookPolicy for MeshAutoHookPolicy { } let messages = chat_messages_as_values(&request.messages); - let response = self - .executor - .handle_uncertain( + let response = with_request_tier( + request.request_class.tier(), + self.executor.handle_uncertain( &request.model, &messages, signals.first_token_entropy, signals.first_token_margin, - ) - .await; + ), + ) + .await; Ok(virtual_hook_response_to_outcome(&response)) } @@ -102,7 +114,7 @@ impl InferenceHookPolicy for MeshAutoHookPolicy { request: &mut GenerationRequest, signals: GenerationHookSignals, ) -> InferenceResult { - if !chat_skippy_hooks_enabled(request) { + if !mesh_hooks_allowed(request) { return Ok(ChatHookOutcome::none()); } @@ -117,10 +129,12 @@ impl InferenceHookPolicy for MeshAutoHookPolicy { } let messages = chat_messages_as_values(&request.messages); - let response = self - .executor - .handle_drift(&request.model, &messages, signals.n_decoded) - .await; + let response = with_request_tier( + request.request_class.tier(), + self.executor + .handle_drift(&request.model, &messages, signals.n_decoded), + ) + .await; Ok(virtual_hook_response_to_outcome(&response)) } @@ -371,12 +385,21 @@ mod tests { #[derive(Default)] struct RecordingHookExecutor { calls: Mutex>, + /// The tier each call ran at. + tiers: Mutex>, } impl RecordingHookExecutor { fn calls(&self) -> Vec { self.calls.lock().unwrap().clone() } + + fn record_tier(&self) { + self.tiers + .lock() + .unwrap() + .push(crate::mesh::request_tier::current_request_tier()); + } } #[async_trait] @@ -388,6 +411,7 @@ mod tests { media_url: &str, user_text: &str, ) -> Value { + self.record_tier(); self.calls.lock().unwrap().push(RecordedHookCall::Image { trigger: trigger.to_string(), model: model.to_string(), @@ -404,6 +428,7 @@ mod tests { entropy: f64, margin: f64, ) -> Value { + self.record_tier(); self.calls .lock() .unwrap() @@ -417,6 +442,7 @@ mod tests { } async fn handle_drift(&self, model: &str, messages: &[Value], n_decoded: i64) -> Value { + self.record_tier(); self.calls.lock().unwrap().push(RecordedHookCall::Drift { model: model.to_string(), n_decoded, @@ -818,4 +844,59 @@ mod tests { } )); } + + /// Hooks run on the local server's task, not the ingress task, so the + /// tier of the consultations they start comes from the request itself. + #[tokio::test] + async fn hook_consultations_run_at_the_request_tier() { + use skippy_inference_api::{InferenceRequestClass, InferenceRequestTier}; + let (policy, executor) = policy_with_recorder(HookDebugConfig::default()); + + let mut mesh_request = text_request(true); + mesh_request.request_class = InferenceRequestClass::new(InferenceRequestTier::Mesh, false); + policy + .after_prefill(&mut mesh_request, uncertain_signals()) + .await + .unwrap(); + let mut image = image_request(true); + image.request_class = InferenceRequestClass::new(InferenceRequestTier::Trusted, false); + policy.before_chat_completion(&mut image).await.unwrap(); + let mut local_request = text_request(true); + policy + .after_prefill(&mut local_request, uncertain_signals()) + .await + .unwrap(); + + assert_eq!( + *executor.tiers.lock().unwrap(), + [ + InferenceRequestTier::Mesh, + InferenceRequestTier::Trusted, + InferenceRequestTier::Local + ] + ); + } + + #[tokio::test] + async fn a_private_request_starts_no_hook_consultation() { + use skippy_inference_api::{InferenceRequestClass, InferenceRequestTier}; + let (policy, executor) = policy_with_recorder(HookDebugConfig::default()); + let private = InferenceRequestClass::new(InferenceRequestTier::Local, true); + + let mut text = text_request(true); + text.request_class = private; + policy + .after_prefill(&mut text, uncertain_signals()) + .await + .unwrap(); + policy + .mid_generation(&mut text, drift_signals()) + .await + .unwrap(); + let mut image = image_request(true); + image.request_class = private; + policy.before_chat_completion(&mut image).await.unwrap(); + + assert!(executor.calls().is_empty()); + } } diff --git a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/materialization.rs b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/materialization.rs index 3eed2c7c44..9863107369 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/materialization.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/materialization.rs @@ -229,6 +229,7 @@ mod tests { load_mode: LoadMode::LayerPackage, upstream: None, downstream: None, + max_request_tier: None, } } @@ -393,6 +394,7 @@ mod tests { load_mode: LoadMode::LayerPackage, upstream: None, downstream: None, + max_request_tier: None, }; let error = resolve_stage_load_package(&load, StageSourceFetch::Allowed) diff --git a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/stage/mod.rs b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/stage/mod.rs index 32f8655908..fdad72a11d 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/stage/mod.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/stage/mod.rs @@ -728,6 +728,7 @@ fn stage_config( upstream: load.upstream.as_ref().map(peer_config), downstream: load.downstream.as_ref().map(peer_config), admission: load.admission.clone(), + max_request_tier: load.max_request_tier.clone(), }; options.validate()?; let resident_tensor_names = admitted_resident_tensor_names(load, package)?; diff --git a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/stage/tests.rs b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/stage/tests.rs index bcbdbfedf3..018f42823d 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/stage/tests.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/stage/tests.rs @@ -135,6 +135,7 @@ fn load_request() -> StageLoadRequest { endpoint: "127.0.0.1:9001".to_string(), node_id: None, }), + max_request_tier: None, } } diff --git a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/stage/types.rs b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/stage/types.rs index 2bda3f6054..33e00e4541 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/stage/types.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/stage/types.rs @@ -116,6 +116,10 @@ pub(crate) struct StageLoadRequest { pub(crate) load_mode: LoadMode, pub(crate) upstream: Option, pub(crate) downstream: Option, + /// Highest request tier the loaded stage serves. Never read from the + /// wire: the receiving host sets it from its own classification of the + /// node that sent the load. `None` (a local load) serves the stamped tier. + pub(crate) max_request_tier: Option, } #[derive(Clone, Debug, Eq, PartialEq)] diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/config_reload.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/config_reload.rs new file mode 100644 index 0000000000..a7f276cf26 --- /dev/null +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/config_reload.rs @@ -0,0 +1,540 @@ +//! Settings a running node keeps current from its config file. +//! +//! `mesh-llm` commands, a hand edit or a config apply can change the file +//! while the node runs. The node notices the change and reads the setting +//! again, so no restart is needed. When the file is missing, cannot be read or +//! does not validate, a setting that only grants is empty until the file is +//! back, and one that can also take away keeps its last value (see +//! [`WhenUnloadable`]). The check stops once the node drops the setting. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, RwLock, Weak}; +use std::time::{Duration, SystemTime}; + +/// How often a running node checks its config file for a change. +const RELOAD_INTERVAL: Duration = Duration::from_secs(2); + +/// What a setting is while its config file is missing or does not load. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum WhenUnloadable { + /// Its empty value, for a setting that only grants: a missing or broken + /// file grants nothing. + Empty, + /// Its last value that loaded, for a setting that can also take away: a + /// missing or broken file (an editor saving it, say) must not lift a + /// restriction. Removing one takes an edit of the file, or a restart. + KeepLast, +} + +/// Which setting to read and how it fails. +pub(crate) struct SettingSpec { + /// What log lines call the setting. + pub(crate) name: &'static str, + /// Reads the setting from a config that validated. + pub(crate) read: fn(&mesh_llm_config::MeshConfig) -> T, + pub(crate) when_unloadable: WhenUnloadable, +} + +impl Clone for SettingSpec { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for SettingSpec {} + +/// One setting read from the config file, kept current while the node runs. +pub(crate) struct ReloadedSetting { + value: Arc>>, + /// The config file the setting is kept current from, when there is one. + file: Option>, + /// Held across each read of the file and the swap that follows, so an + /// older read cannot replace a newer one. + reload: Arc>, + spec: SettingSpec, +} + +impl Clone for ReloadedSetting { + fn clone(&self) -> Self { + Self { + value: self.value.clone(), + file: self.file.clone(), + reload: self.reload.clone(), + spec: self.spec, + } + } +} + +impl std::fmt::Debug for ReloadedSetting { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ReloadedSetting") + .field("name", &self.spec.name) + .field("file", &self.file) + .finish_non_exhaustive() + } +} + +impl ReloadedSetting { + /// A fixed `value` that no file change replaces. + pub(crate) fn fixed(spec: SettingSpec, value: T) -> Self { + Self { + value: Arc::new(RwLock::new(Arc::new(value))), + file: None, + reload: Arc::default(), + spec, + } + } + + /// The setting in `config`, kept current from the config file it came + /// from when `reload` (a node with its own config file, not a scoped + /// shared-serving membership). + pub(crate) fn kept_current( + spec: SettingSpec, + config: &mesh_llm_config::MeshConfig, + config_path: Option<&Path>, + reload: bool, + ) -> Self { + let mut setting = Self::fixed(spec, (spec.read)(config)); + if reload && let Ok(path) = crate::plugin::config_path(config_path) { + setting.file = Some(Arc::new(path.clone())); + spawn_reload(setting.clone(), path); + } + setting + } + + /// Read the setting from the config file now, rather than at the next + /// check: a config apply does this before it reports the new value as + /// live. + pub(crate) fn reload_now(&self) { + if let Some(path) = &self.file { + self.reload_from(path, true); + } + } + + pub(crate) fn current(&self) -> Arc { + self.value + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } + + /// Read the setting from `path` and install it. `warn` logs a file that + /// does not load as a warning rather than at debug level. + fn reload_from(&self, path: &Path, warn: bool) -> Reload { + let _reload = self + .reload + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let read = self.read(path, warn); + Reload { + changed: read.value.is_some_and(|value| self.replace(value)), + loaded: read.loaded, + } + } + + /// The setting in the config file at `path`; when there is no file or it + /// does not load, empty or `None` (keep the current value) as the + /// setting's [`WhenUnloadable`] says. + #[cfg(test)] + fn load(&self, path: &Path) -> Option { + self.read(path, true).value + } + + fn read(&self, path: &Path, warn: bool) -> Read { + let exists = match path.try_exists() { + Ok(exists) => exists, + // An unreadable directory is not a missing file. + Err(error) => { + return Read { + value: self.unloadable( + path, + &format!("config file cannot be checked: {error}"), + warn, + ), + loaded: false, + }; + } + }; + if !exists { + // Running without a config file is normal: no warning. + tracing::debug!( + path = %path.display(), + setting = self.spec.name, + "no config file" + ); + return Read { + value: self.when_unloadable(), + loaded: true, + }; + } + match mesh_llm_config::load_config(Some(path)) { + Ok(config) => Read { + value: Some((self.spec.read)(&config)), + loaded: true, + }, + Err(error) => Read { + value: self.unloadable(path, &format!("config file does not load: {error}"), warn), + loaded: false, + }, + } + } + + /// The setting while the file at `path` does not load, for `reason`. + fn unloadable(&self, path: &Path, reason: &str, warn: bool) -> Option { + let state = if self.when_unloadable().is_none() { + "unchanged" + } else { + "empty" + }; + if warn { + tracing::warn!( + path = %path.display(), + setting = self.spec.name, + "{reason}; the setting is {state} until it is fixed", + ); + } else { + tracing::debug!( + path = %path.display(), + setting = self.spec.name, + "{reason}; the setting is {state} until it is fixed", + ); + } + self.when_unloadable() + } + + /// Empty, or `None` to keep the current value. + fn when_unloadable(&self) -> Option { + (self.spec.when_unloadable == WhenUnloadable::Empty).then(T::default) + } + + /// Replace the value; true when it changed. + fn replace(&self, value: T) -> bool { + let mut current = self + .value + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if **current == value { + return false; + } + *current = Arc::new(value); + true + } +} + +/// One read of the config file for a setting. +struct Read { + /// The value to install, or `None` to keep the current one. + value: Option, + /// Whether the file loaded (or is absent, which is as stable). + loaded: bool, +} + +/// What one reload did. +struct Reload { + changed: bool, + loaded: bool, +} + +/// What identifies one version of the file: its modification time and size. +type FileVersion = Option<(SystemTime, u64)>; + +fn file_version(path: &Path) -> FileVersion { + let metadata = std::fs::metadata(path).ok()?; + Some((metadata.modified().ok()?, metadata.len())) +} + +/// What the background check has read from the config file. +#[derive(Default)] +struct FileWatch { + /// The version that last loaded: an unchanged file is not read again. + /// Nothing yet, so the first check reads the file, even a missing one. + loaded: Option, + /// The version that last failed to load. It is read again at every + /// check, since a fix such as a permission change can leave its + /// modification time and size unchanged, but warned about only once. + failed: Option, +} + +impl FileWatch { + /// Read the setting again unless the file is the version that last + /// loaded; true when the value changed. + fn check( + &mut self, + setting: &ReloadedSetting, + path: &Path, + ) -> bool { + let version = file_version(path); + if self.loaded == Some(version) { + return false; + } + let reload = setting.reload_from(path, self.failed != Some(version)); + if reload.loaded { + (self.loaded, self.failed) = (Some(version), None); + } else { + (self.loaded, self.failed) = (None, Some(version)); + } + reload.changed + } +} + +/// Read the setting again whenever the config file at `path` changes, until +/// every copy of `setting` is dropped. +fn spawn_reload( + setting: ReloadedSetting, + path: PathBuf, +) { + let ReloadedSetting { + value, + reload, + spec, + .. + } = setting; + let value: Weak>> = Arc::downgrade(&value); + tokio::spawn(async move { + // An edit or removal made between the node's first read and this + // task starting counts: the first check reads the file again. + let mut watch = FileWatch::default(); + loop { + tokio::time::sleep(RELOAD_INTERVAL).await; + let Some(value) = value.upgrade() else { + return; + }; + let setting = ReloadedSetting { + value, + file: None, + reload: reload.clone(), + spec, + }; + let reload_path = path.clone(); + let mut checking = std::mem::take(&mut watch); + let Ok((checked, changed)) = tokio::task::spawn_blocking(move || { + let changed = checking.check(&setting, &reload_path); + (checking, changed) + }) + .await + else { + continue; + }; + watch = checked; + if changed { + tracing::info!(setting = spec.name, "setting reloaded from the config file"); + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn read_nodes(config: &mesh_llm_config::MeshConfig) -> Vec { + config.private.nodes.clone() + } + + const NODES: SettingSpec> = SettingSpec { + name: "nodes", + read: read_nodes, + when_unloadable: WhenUnloadable::Empty, + }; + + fn node(seed: u8) -> String { + hex::encode([seed; 32]) + } + + fn write_config(path: &Path, nodes: &[String]) { + let nodes: Vec = nodes.iter().map(|id| format!("\"{id}\"")).collect(); + std::fs::write(path, format!("[private]\nnodes = [{}]\n", nodes.join(", "))).unwrap(); + } + + fn watched(path: &Path) -> ReloadedSetting> { + let config = mesh_llm_config::load_config(Some(path)).unwrap(); + ReloadedSetting::kept_current(NODES, &config, Some(path), true) + } + + async fn wait_for(setting: &ReloadedSetting>, expected: &[String]) { + for _ in 0..300 { + if *setting.current() == expected { + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + assert_eq!(*setting.current(), expected); + } + + #[test] + fn a_missing_or_broken_file_follows_the_setting() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + let granting = ReloadedSetting::fixed(NODES, vec![node(1)]); + let restricting = ReloadedSetting::fixed( + SettingSpec { + when_unloadable: WhenUnloadable::KeepLast, + ..NODES + }, + vec![node(1)], + ); + assert_eq!(granting.load(&path), Some(vec![])); + assert_eq!(restricting.load(&path), None); + + std::fs::write(&path, "[private]\nnodes = [\"studio\"]\n").unwrap(); + assert_eq!(granting.load(&path), Some(vec![])); + assert_eq!(restricting.load(&path), None); + assert!(!restricting.reload_from(&path, true).changed); + assert_eq!(*restricting.current(), [node(1)]); + } + + #[tokio::test] + async fn a_running_node_picks_up_an_edit_and_a_removal() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + write_config(&path, &[node(1)]); + let setting = watched(&path); + + write_config(&path, &[node(1), node(2), node(3)]); + wait_for(&setting, &[node(1), node(2), node(3)]).await; + + std::fs::remove_file(&path).unwrap(); + wait_for(&setting, &[]).await; + } + + #[tokio::test] + async fn a_file_removed_before_the_first_check_empties_the_setting() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + write_config(&path, &[node(1)]); + let setting = watched(&path); + std::fs::remove_file(&path).unwrap(); + wait_for(&setting, &[]).await; + } + + #[tokio::test] + async fn the_check_does_not_keep_a_dropped_setting_alive() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + write_config(&path, &[node(1)]); + let setting = watched(&path); + let value = Arc::downgrade(&setting.value); + drop(setting); + assert!(value.upgrade().is_none()); + } + + #[tokio::test] + async fn reload_now_reads_the_file_at_once() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + write_config(&path, &[node(1), node(2)]); + let setting = watched(&path); + assert_eq!(*setting.current(), [node(1), node(2)]); + + write_config(&path, &[node(2)]); + setting.reload_now(); + assert_eq!(*setting.current(), [node(2)]); + + let config = mesh_llm_config::load_config(Some(&path)).unwrap(); + let unwatched = ReloadedSetting::kept_current(NODES, &config, Some(&path), false); + write_config(&path, &[node(3)]); + unwatched.reload_now(); + assert_eq!(*unwatched.current(), [node(2)]); + } + + #[test] + fn an_older_background_read_cannot_win_over_reload_now() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + write_config(&path, &[node(1), node(2)]); + let mut setting = ReloadedSetting::fixed(NODES, vec![node(1), node(2)]); + setting.file = Some(Arc::new(path.clone())); + + // The background check has read the old value and not yet swapped it in. + let background = setting.reload.lock().unwrap(); + let old_read = setting.load(&path); + + // An apply removes node 1 and reloads before reporting it live. + write_config(&path, &[node(2)]); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let applying = setting.clone(); + let apply = std::thread::spawn(move || { + applying.reload_now(); + done_tx.send(()).unwrap(); + }); + assert!( + done_rx.recv_timeout(Duration::from_millis(300)).is_err(), + "reload_now must wait for the read in progress" + ); + + setting.replace(old_read.unwrap()); + drop(background); + apply.join().unwrap(); + assert_eq!(*setting.current(), [node(2)]); + } + + /// A file that failed to load is read again even when the fix leaves + /// its modification time and size unchanged. + #[test] + fn a_file_that_failed_to_load_is_read_again_unchanged() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + let setting = ReloadedSetting::fixed( + SettingSpec { + when_unloadable: WhenUnloadable::KeepLast, + ..NODES + }, + vec![], + ); + let set_mtime = |seconds: u64| { + std::fs::File::options() + .write(true) + .open(&path) + .unwrap() + .set_modified(SystemTime::UNIX_EPOCH + Duration::from_secs(seconds)) + .unwrap(); + }; + let mut watch = FileWatch::default(); + write_config(&path, &[node(1)]); + set_mtime(1_000); + assert!(watch.check(&setting, &path)); + + // The same length, but not a node id. + let broken = std::fs::read_to_string(&path) + .unwrap() + .replacen('1', "g", 1); + std::fs::write(&path, broken).unwrap(); + set_mtime(2_000); + assert!(!watch.check(&setting, &path)); + assert_eq!(*setting.current(), [node(1)]); + + write_config(&path, &[node(2)]); + set_mtime(2_000); + assert!(watch.check(&setting, &path)); + assert_eq!(*setting.current(), [node(2)]); + assert!(!watch.check(&setting, &path)); + } + + /// A config file that cannot be checked is a failed load, not an absent + /// file: it keeps a setting that can take away, and is read again. + /// (Windows reports a path through a file as not found.) + #[cfg(unix)] + #[test] + fn an_uncheckable_file_is_not_a_missing_one() { + let dir = tempfile::tempdir().unwrap(); + let not_a_directory = dir.path().join("file"); + std::fs::write(¬_a_directory, "").unwrap(); + let path = not_a_directory.join("config.toml"); + let restricting = ReloadedSetting::fixed( + SettingSpec { + when_unloadable: WhenUnloadable::KeepLast, + ..NODES + }, + vec![node(1)], + ); + let read = restricting.read(&path, true); + assert!(!read.loaded); + assert_eq!(read.value, None); + assert!( + restricting + .read(&dir.path().join("missing.toml"), true) + .loaded + ); + } +} diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/mod.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/mod.rs index dba99664c2..4ca63f55ca 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/mod.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/mod.rs @@ -80,6 +80,7 @@ mod advertisement; mod announcements; mod artifact_transfer_io; mod capacity; +mod config_reload; mod connections; mod connectivity; mod direct_path; @@ -105,6 +106,7 @@ mod plugin_streams; mod pre_admission; pub(crate) mod private_nodes; mod private_scope; +pub(crate) mod request_tier; pub mod requirements; mod signed_records; mod stage_artifacts; diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference.rs index b1d8ac73a1..568e209af0 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference.rs @@ -170,7 +170,7 @@ impl Node { .context("invalid native inference provider ID")?; tokio::time::timeout(NATIVE_CHAT_TIMEOUT, async { if provider == self.endpoint.id() { - return self.execute_native_chat(call, false).await; + return self.execute_native_chat(call).await; } let (mut send, mut recv) = self.open_native_chat(provider, &call).await?; let response = read_native_frame(&mut recv).await?; @@ -209,17 +209,18 @@ impl Node { Ok((send, recv)) } + /// `requester` is the peer that asked, `None` for a call made on this node. async fn prepare_native_chat( &self, mut call: NativeChatRequest, - remote: bool, + requester: Option, ) -> Result { normalize_target(&mut call)?; anyhow::ensure!( call.target.provider_node_id == self.endpoint.id().to_string(), "native inference target names a different provider" ); - let ingress = if remote { + let ingress = if requester.is_some() { IngressType::RemoteQuicHttp } else { IngressType::LocalOpenAi @@ -264,7 +265,14 @@ impl Node { continue; } drop(current); - let context = InferenceRequestContext::new(); + let tier = match requester { + Some(peer) => self.peer_request_tier(peer).await, + None => super::request_tier::current_request_tier(), + }; + let private = super::current_private_scope().is_some(); + let context = InferenceRequestContext::new().with_request_class( + skippy_inference_api::InferenceRequestClass::new(tier, private), + ); return Ok(PreparedNativeChat { backend: candidate.backend.clone(), request: call.request.into(), @@ -280,12 +288,8 @@ impl Node { ) } - async fn execute_native_chat( - &self, - call: NativeChatRequest, - remote: bool, - ) -> Result { - let mut prepared = self.prepare_native_chat(call, remote).await?; + async fn execute_native_chat(&self, call: NativeChatRequest) -> Result { + let mut prepared = self.prepare_native_chat(call, None).await?; let request = std::mem::take(&mut prepared.request); let response = prepared .backend @@ -329,7 +333,13 @@ impl Node { // an unary response has no progress signal of its own, so it // keeps the whole-request bound. let streaming = call.request.stream; - let serving = node.serve_native_chat(call, &mut send); + // Hooks and plugin calls made while serving read the tier + // from the task, so serve the peer at its own tier. + let tier = node.peer_request_tier(remote).await; + let serving = super::request_tier::with_request_tier( + tier, + node.serve_native_chat(call, remote, &mut send), + ); if streaming { serving.await } else { diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference/streaming.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference/streaming.rs index f597d9ab17..c955683876 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference/streaming.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference/streaming.rs @@ -33,7 +33,11 @@ impl Node { let (tx, rx) = mpsc::channel(16); let node = self.clone(); let idle = self.native_inference.stream_idle(); - let task = tokio::spawn(async move { + // The caller's tier and private scope are task-local, so they are + // carried onto the producing task. + let tier = super::request_tier::current_request_tier(); + let scope = super::current_private_scope(); + let produce = async move { let result = tokio::select! { _ = tx.closed() => return, result = async { @@ -47,7 +51,11 @@ impl Node { if let Err(error) = result { let _ = tx.send(Err(error)).await; } - }); + }; + let task = tokio::spawn(super::with_private_scope( + scope, + super::request_tier::with_request_tier(tier, produce), + )); Ok(ChatCompletionStream::new(rx, task)) } @@ -57,7 +65,7 @@ impl Node { tx: &ChunkSender, idle: Duration, ) -> Result<()> { - let mut prepared = self.prepare_native_chat(call, false).await?; + let mut prepared = self.prepare_native_chat(call, None).await?; let request = std::mem::take(&mut prepared.request); let mut chunks = tokio::select! { _ = tx.closed() => return Ok(()), @@ -120,11 +128,12 @@ impl Node { pub(super) async fn serve_native_chat( &self, call: NativeChatRequest, + requester: EndpointId, send: &mut iroh::endpoint::SendStream, ) -> Result<()> { let idle = self.native_inference.stream_idle(); let stream = call.request.stream; - let mut prepared = self.prepare_native_chat(call, true).await?; + let mut prepared = self.prepare_native_chat(call, Some(requester)).await?; let request = std::mem::take(&mut prepared.request); if stream { let mut chunks = tokio::select! { diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/node.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/node.rs index c6710948e8..cdcf117352 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/node.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/node.rs @@ -204,6 +204,8 @@ pub struct Node { pub(crate) trust_policy: TrustPolicy, /// Nodes besides this one that may serve its private requests. pub(crate) private_nodes: super::private_nodes::PrivateNodes, + /// Per-owner overrides of the tier this node serves requests at. + pub(crate) request_tier_owners: super::request_tier::RequestTierOwners, pub enumerate_host: bool, pub gpu_name: Option, pub hostname: Option, @@ -822,6 +824,7 @@ impl Node { trust_store: Arc::new(Mutex::new(TrustStore::default())), trust_policy: TrustPolicy::Off, private_nodes: Default::default(), + request_tier_owners: Default::default(), enumerate_host: false, gpu_name: None, hostname: None, diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/node/construction.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/node/construction.rs index 114387409a..0f9854e52b 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/node/construction.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/node/construction.rs @@ -3,6 +3,7 @@ use super::startup::*; use super::*; use crate::mesh::private_nodes::PrivateNodes; +use crate::mesh::request_tier::RequestTierOwners; pub(crate) struct ScopedNodeIdentity { pub key: SecretKey, @@ -99,6 +100,7 @@ impl Node { super::startup::end_if_stopping(&endpoint).await?; let config_state_init = super::startup::load_config_state(config_path)?; let config = config_state_init.config(); + let reload = identity.is_none(); let hardware = hardware_for_identity(config, &role, max_vram_gb, identity.as_ref()); let owner_runtime = init_owner_runtime( owner_config.as_ref(), @@ -205,14 +207,13 @@ impl Node { model_requirements: Default::default(), unmatched_model_requirements: Default::default(), release_attestation: Arc::new(Mutex::new(None)), - release_attestation_summary: Arc::new(Mutex::new( - crate::ReleaseAttestationSummary::default(), - )), + release_attestation_summary: Arc::default(), owner_summary: Arc::new(Mutex::new(owner_summary)), control_listener: Arc::new(Mutex::new(None)), trust_store: Arc::new(Mutex::new(owner_runtime.trust_store)), trust_policy: owner_runtime.trust_policy, - private_nodes: PrivateNodes::kept_current(config, config_path, identity.is_none()), + private_nodes: PrivateNodes::kept_current(config, config_path, reload), + request_tier_owners: RequestTierOwners::kept_current(config, config_path, reload), enumerate_host, gpu_name: hardware.gpu_name, hostname: hardware.hostname, diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/node/membership.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/node/membership.rs index a1ea6e52a1..465ae7f6b0 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/node/membership.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/node/membership.rs @@ -391,6 +391,7 @@ impl Node { trust_store: Arc::new(Mutex::new(trust_store)), trust_policy: TrustPolicy::Allowlist, private_nodes: self.private_nodes.clone(), + request_tier_owners: self.request_tier_owners.clone(), enumerate_host: config.enumerate_host, public_mesh: false, // The serving state it shares with this node. diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/owner_control/mod.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/owner_control/mod.rs index 101a4f11e7..c0299766d0 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/owner_control/mod.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/owner_control/mod.rs @@ -173,8 +173,9 @@ where impl Node { /// Put back what an applied snapshot does not carry: redacted telemetry - /// headers, and the `[private]` list a legacy snapshot has no field for. - async fn restore_unsent_settings( + /// headers, and the `[private]` list and `[request_tiers]` a legacy + /// snapshot has no field for. + pub(super) async fn restore_unsent_settings( &self, mesh_config: &mut crate::plugin::MeshConfig, snapshot: &crate::proto::node::NodeConfigSnapshot, @@ -186,6 +187,7 @@ impl Node { ); if snapshot.config_toml.is_none() { mesh_config.private = state.config().private.clone(); + mesh_config.request_tiers = state.config().request_tiers.clone(); } } } @@ -858,8 +860,10 @@ impl Node { || runtime.block_on(node.plugin_manager()), runtime.clone(), ); - // The written `[private]` list is live before the reply says so. + // The written `[private]` list and tier overrides are live before the + // reply says so. node.private_nodes.reload_now(); + node.request_tier_owners.reload_now(); Ok(applied) }) .await diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/private_nodes.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/private_nodes.rs index bd6a7134ad..a100f27ec6 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/private_nodes.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/private_nodes.rs @@ -1,39 +1,38 @@ //! This node's private node list: `[private] nodes` in its config file. //! //! `mesh-llm private add` and `remove` edit that list, and so can a hand edit -//! or a config apply. A running node notices the file change and reads the -//! list again, so no restart is needed. When the file cannot be read or does -//! not validate, the list is empty: private requests stay on this node until -//! the file is fixed. +//! or a config apply. A running node reads the list again when the file +//! changes (see [`super::config_reload`]). When the file cannot be read or +//! does not validate, the list is empty: private requests stay on this node +//! until the file is fixed. +use super::config_reload::{ReloadedSetting, SettingSpec, WhenUnloadable}; use super::plugin_streams::endpoint_id_from_hex; use iroh::EndpointId; use std::collections::HashSet; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, RwLock}; -use std::time::{Duration, SystemTime}; - -/// How often a running node checks its config file for a changed list. -const RELOAD_INTERVAL: Duration = Duration::from_secs(2); +use std::path::Path; +use std::sync::Arc; /// The nodes besides this one that may serve its private requests. -#[derive(Clone, Debug, Default)] -pub(crate) struct PrivateNodes { - ids: Arc>>>, - /// The config file the list is kept current from, when there is one. - file: Option>, - /// Held across each read of the file and the swap that follows, so an - /// older read cannot replace a newer one. - reload: Arc>, +#[derive(Clone, Debug)] +pub(crate) struct PrivateNodes(ReloadedSetting>); + +impl Default for PrivateNodes { + fn default() -> Self { + Self::of([]) + } } +// The list only grants, so a broken file grants nothing. +const SETTING: SettingSpec> = SettingSpec { + name: "private.nodes", + read: private_nodes_in, + when_unloadable: WhenUnloadable::Empty, +}; + impl PrivateNodes { pub(crate) fn of(ids: impl IntoIterator) -> Self { - Self { - ids: Arc::new(RwLock::new(Arc::new(ids.into_iter().collect()))), - file: None, - reload: Arc::default(), - } + Self(ReloadedSetting::fixed(SETTING, ids.into_iter().collect())) } /// The list in `config`, kept current from the config file it came from @@ -44,29 +43,18 @@ impl PrivateNodes { config_path: Option<&Path>, reload: bool, ) -> Self { - let mut nodes = Self::of(private_nodes_in(config)); - if reload && let Ok(path) = crate::plugin::config_path(config_path) { - nodes.file = Some(Arc::new(path.clone())); - spawn_private_nodes_reload(nodes.clone(), path); - } - nodes + Self(ReloadedSetting::kept_current( + SETTING, + config, + config_path, + reload, + )) } /// Read the list from the config file now, rather than at the next check: /// a config apply does this before it reports the new list as live. pub(crate) fn reload_now(&self) { - if let Some(path) = &self.file { - self.reload_from(path); - } - } - - /// Read the list from `path` and install it; true when it changed. - fn reload_from(&self, path: &Path) -> bool { - let _reload = self - .reload - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - self.replace(load_private_nodes(path)) + self.0.reload_now(); } pub(crate) fn contains(&self, id: &EndpointId) -> bool { @@ -74,23 +62,7 @@ impl PrivateNodes { } pub(crate) fn current(&self) -> Arc> { - self.ids - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone() - } - - /// Replace the list; true when it changed. - fn replace(&self, ids: HashSet) -> bool { - let mut current = self - .ids - .write() - .unwrap_or_else(std::sync::PoisonError::into_inner); - if **current == ids { - return false; - } - *current = Arc::new(ids); - true + self.0.current() } } @@ -105,58 +77,6 @@ pub(crate) fn private_nodes_in(config: &mesh_llm_config::MeshConfig) -> HashSet< .collect() } -/// The list in the config file at `path`; empty when it cannot be loaded. -fn load_private_nodes(path: &Path) -> HashSet { - if !path.exists() { - return HashSet::new(); - } - match mesh_llm_config::load_config(Some(path)) { - Ok(config) => private_nodes_in(&config), - Err(error) => { - tracing::warn!( - path = %path.display(), - %error, - "config file does not load; private requests stay on this node until it is fixed" - ); - HashSet::new() - } - } -} - -/// What identifies one version of the file: its modification time and size. -fn file_version(path: &Path) -> Option<(SystemTime, u64)> { - let metadata = std::fs::metadata(path).ok()?; - Some((metadata.modified().ok()?, metadata.len())) -} - -/// Read the list again whenever the config file at `path` changes. -pub(crate) fn spawn_private_nodes_reload(nodes: PrivateNodes, path: PathBuf) { - tokio::spawn(async move { - // Nothing seen yet, so the first check reads the file again, even a - // missing one: an edit or removal made between the node's first read - // and this task starting counts. - let mut seen: Option> = None; - loop { - tokio::time::sleep(RELOAD_INTERVAL).await; - let version = file_version(&path); - if seen == Some(version) { - continue; - } - seen = Some(version); - let (reloading, reload_path) = (nodes.clone(), path.clone()); - let Ok(changed) = - tokio::task::spawn_blocking(move || reloading.reload_from(&reload_path)).await - else { - continue; - }; - if changed { - let count = nodes.current().len(); - tracing::info!(count, "private node list reloaded from the config file"); - } - } - }); -} - #[cfg(test)] mod tests { use super::*; @@ -165,120 +85,19 @@ mod tests { iroh::SecretKey::from_bytes(&[seed; 32]).public() } - fn write_config(path: &Path, ids: &[EndpointId]) { - let nodes: Vec = ids.iter().map(|id| format!("\"{id}\"")).collect(); - std::fs::write(path, format!("[private]\nnodes = [{}]\n", nodes.join(", "))).unwrap(); - } - #[test] fn the_list_comes_from_the_config_file() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("config.toml"); - assert!(load_private_nodes(&path).is_empty()); - write_config(&path, &[id(1), id(2)]); - assert_eq!(load_private_nodes(&path), [id(1), id(2)].into()); - } - - #[test] - fn a_config_file_that_does_not_load_lists_no_node() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.toml"); - std::fs::write(&path, "[private]\nnodes = [\"studio\"]\n").unwrap(); - assert!(load_private_nodes(&path).is_empty()); - } - - #[tokio::test] - async fn a_running_node_picks_up_an_edit() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.toml"); - write_config(&path, &[id(1)]); - let nodes = PrivateNodes::of(load_private_nodes(&path)); - spawn_private_nodes_reload(nodes.clone(), path.clone()); - - write_config(&path, &[id(1), id(2), id(3)]); - for _ in 0..300 { - if nodes.current().len() == 3 { - break; - } - tokio::time::sleep(Duration::from_millis(100)).await; - } - assert_eq!(*nodes.current(), [id(1), id(2), id(3)].into()); - - std::fs::remove_file(&path).unwrap(); - for _ in 0..300 { - if nodes.current().is_empty() { - break; - } - tokio::time::sleep(Duration::from_millis(100)).await; - } - assert!(nodes.current().is_empty()); - } - - #[tokio::test] - async fn a_file_removed_before_the_first_check_empties_the_list() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.toml"); - write_config(&path, &[id(1)]); - let nodes = PrivateNodes::of(load_private_nodes(&path)); - std::fs::remove_file(&path).unwrap(); - spawn_private_nodes_reload(nodes.clone(), path.clone()); - - for _ in 0..300 { - if nodes.current().is_empty() { - break; - } - tokio::time::sleep(Duration::from_millis(100)).await; - } - assert!(nodes.current().is_empty()); - } - - #[tokio::test] - async fn reload_now_reads_the_file_at_once() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.toml"); - write_config(&path, &[id(1), id(2)]); + std::fs::write( + &path, + format!("[private]\nnodes = [\"{}\", \"{}\"]\n", id(1), id(2)), + ) + .unwrap(); let config = mesh_llm_config::load_config(Some(&path)).unwrap(); - let nodes = PrivateNodes::kept_current(&config, Some(&path), true); + let nodes = PrivateNodes::kept_current(&config, Some(&path), false); assert_eq!(*nodes.current(), [id(1), id(2)].into()); - - write_config(&path, &[id(2)]); - nodes.reload_now(); - assert_eq!(*nodes.current(), [id(2)].into()); - - let unwatched = PrivateNodes::kept_current(&config, Some(&path), false); - unwatched.reload_now(); - assert_eq!(*unwatched.current(), [id(1), id(2)].into()); - } - - #[test] - fn an_older_background_read_cannot_win_over_reload_now() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.toml"); - write_config(&path, &[id(1), id(2)]); - let config = mesh_llm_config::load_config(Some(&path)).unwrap(); - let mut nodes = PrivateNodes::kept_current(&config, Some(&path), false); - nodes.file = Some(Arc::new(path.clone())); - - // The background check has read the old list and not yet swapped it in. - let background = nodes.reload.lock().unwrap(); - let old_read = load_private_nodes(&path); - - // An apply removes node 1 and reloads before reporting it live. - write_config(&path, &[id(2)]); - let (done_tx, done_rx) = std::sync::mpsc::channel(); - let applying = nodes.clone(); - let apply = std::thread::spawn(move || { - applying.reload_now(); - done_tx.send(()).unwrap(); - }); - assert!( - done_rx.recv_timeout(Duration::from_millis(300)).is_err(), - "reload_now must wait for the read in progress" - ); - - nodes.replace(old_read); - drop(background); - apply.join().unwrap(); - assert_eq!(*nodes.current(), [id(2)].into()); + assert!(nodes.contains(&id(1))); + assert!(!nodes.contains(&id(3))); } } diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/request_tier.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/request_tier.rs new file mode 100644 index 0000000000..abcdae56d6 --- /dev/null +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/request_tier.rs @@ -0,0 +1,379 @@ +//! Request tiers: whom a request this node serves is for. +//! +//! The node a request enters decides its tier once and runs the rest of that +//! request inside [`with_request_tier`]: +//! +//! - `local`: this machine, a node on its `[private] nodes` list, or a node +//! with a verified certificate from this node's own owner; +//! - `trusted`: a node with a verified certificate from an owner in this +//! node's trust store; +//! - `mesh`: everyone else. +//! +//! `[request_tiers] owners` in the config file replaces the tier of one +//! owner's verified nodes. A node that forwards a request names its client's +//! tier in [`REQUEST_TIER_HEADER`]; the receiving node keeps the lower of +//! that claim and its own classification of the sender, so no peer can raise +//! its own requests. Skippy orders admission and eviction by the tier and +//! keeps a separate cache for each one. + +use super::config_reload::{ReloadedSetting, SettingSpec, WhenUnloadable}; +use crate::crypto::{OwnershipStatus, OwnershipSummary}; +use iroh::EndpointId; +use skippy_inference_api::InferenceRequestTier; +use std::collections::BTreeMap; +use std::path::Path; + +/// The header a forwarding node names its client's tier in. +pub(crate) const REQUEST_TIER_HEADER: &str = "x-mesh-request-tier"; + +tokio::task_local! { + static CURRENT_REQUEST_TIER: InferenceRequestTier; +} + +/// Run `future` with `tier` as the tier of the request this task serves. +pub(crate) async fn with_request_tier( + tier: InferenceRequestTier, + future: F, +) -> F::Output { + CURRENT_REQUEST_TIER.scope(tier, future).await +} + +/// The tier of the request this task is serving. Work that no ingress +/// classified started on this machine, so it is `local`. +pub(crate) fn current_request_tier() -> InferenceRequestTier { + CURRENT_REQUEST_TIER + .try_with(|tier| *tier) + .unwrap_or(InferenceRequestTier::Local) +} + +/// The tier the raw HTTP request `raw` claims in [`REQUEST_TIER_HEADER`]: +/// the lowest of its values, `local` (no limit) when it has none. A value +/// that is not a tier, or a head that cannot be read, claims `mesh`. +pub(crate) fn claimed_request_tier(raw: &[u8]) -> InferenceRequestTier { + match crate::network::openai::request_parse::header_values_from_parsed_raw( + raw, + REQUEST_TIER_HEADER, + ) { + Ok(values) => values + .iter() + .flat_map(|value| value.split(',')) + .map(|value| InferenceRequestTier::parse(value).unwrap_or(InferenceRequestTier::Mesh)) + .fold(InferenceRequestTier::Local, InferenceRequestTier::min), + Err(()) => InferenceRequestTier::Mesh, + } +} + +/// Insert `x-mesh-request-tier: ` as the first header of the raw HTTP +/// request `raw`. +pub(crate) fn insert_request_tier_header(raw: &mut Vec, tier: InferenceRequestTier) { + insert_header_lines(raw, &format!("{REQUEST_TIER_HEADER}: {tier}\r\n")); +} + +/// The raw request `raw` with the current request's class named for this +/// node's own Skippy server, which is reached over loopback outside this +/// task. `None` for a `local` request outside the private partition: Skippy +/// serves a request without the headers as that. +pub(crate) fn mark_class_for_local_server(raw: &[u8], private: bool) -> Option> { + let tier = current_request_tier(); + if tier == InferenceRequestTier::Local && !private { + return None; + } + let mut lines = format!("{}: {tier}\r\n", skippy_inference_api::REQUEST_TIER_HEADER); + if private { + lines.push_str(&format!( + "{}: {}\r\n", + skippy_inference_api::CACHE_PARTITION_HEADER, + skippy_inference_api::PRIVATE_CACHE_PARTITION + )); + } + let mut raw = raw.to_vec(); + insert_header_lines(&mut raw, &lines); + Some(raw) +} + +/// Insert header `lines` right after the request line of `raw`. +fn insert_header_lines(raw: &mut Vec, lines: &str) { + let request_line_end = raw + .windows(2) + .position(|pair| pair == b"\r\n") + .map_or(0, |at| at + 2); + raw.splice(request_line_end..request_line_end, lines.bytes()); +} + +/// Per-owner tier overrides: `[request_tiers] owners` in the config file, +/// kept current while the node runs. +#[derive(Clone, Debug)] +pub(crate) struct RequestTierOwners(ReloadedSetting>); + +impl Default for RequestTierOwners { + fn default() -> Self { + Self::of(BTreeMap::new()) + } +} + +// An override can lower an owner, so a broken file keeps the last overrides +// that loaded rather than lifting them. +const SETTING: SettingSpec> = SettingSpec { + name: "request_tiers.owners", + read: owner_tiers_in, + when_unloadable: WhenUnloadable::KeepLast, +}; + +impl RequestTierOwners { + pub(crate) fn of(owners: BTreeMap) -> Self { + Self(ReloadedSetting::fixed(SETTING, owners)) + } + + /// The overrides in `config`, kept current from the config file it came + /// from when `reload`. + pub(crate) fn kept_current( + config: &mesh_llm_config::MeshConfig, + config_path: Option<&Path>, + reload: bool, + ) -> Self { + Self(ReloadedSetting::kept_current( + SETTING, + config, + config_path, + reload, + )) + } + + /// Read the overrides from the config file now. + pub(crate) fn reload_now(&self) { + self.0.reload_now(); + } + + fn tier_of(&self, owner_id: &str) -> Option { + self.0 + .current() + .get(&owner_id.to_ascii_lowercase()) + .copied() + } +} + +/// The overrides in `config`, by lowercase owner id. +fn owner_tiers_in(config: &mesh_llm_config::MeshConfig) -> BTreeMap { + config + .request_tiers + .owners + .iter() + .map(|(owner, tier)| (owner.trim().to_ascii_lowercase(), request_tier(*tier))) + .collect() +} + +fn request_tier(tier: mesh_llm_config::RequestTierName) -> InferenceRequestTier { + match tier { + mesh_llm_config::RequestTierName::Local => InferenceRequestTier::Local, + mesh_llm_config::RequestTierName::Trusted => InferenceRequestTier::Trusted, + mesh_llm_config::RequestTierName::Mesh => InferenceRequestTier::Mesh, + } +} + +/// The owner a peer's certificate proves, while the certificate is valid. +fn verified_owner(summary: &OwnershipSummary, now_unix_ms: u64) -> Option<&str> { + let unexpired = summary + .expires_at_unix_ms + .is_none_or(|expires| expires > now_unix_ms); + (summary.status == OwnershipStatus::Verified && unexpired) + .then_some(summary.owner_id.as_deref()) + .flatten() +} + +/// What this node knows about one peer's owner, for [`owner_tier`]. +struct OwnerFacts<'a> { + peer_owner: Option<&'a str>, + local_owner: Option<&'a str>, + trusted: bool, + overridden: Option, +} + +/// The tier of a peer that is neither this node nor a private node. +fn owner_tier(facts: OwnerFacts<'_>) -> InferenceRequestTier { + let Some(owner) = facts.peer_owner else { + return InferenceRequestTier::Mesh; + }; + if let Some(tier) = facts.overridden { + return tier; + } + if facts + .local_owner + .is_some_and(|local| local.eq_ignore_ascii_case(owner)) + { + return InferenceRequestTier::Local; + } + if facts.trusted { + InferenceRequestTier::Trusted + } else { + InferenceRequestTier::Mesh + } +} + +impl super::Node { + /// The tier this node serves requests from `peer` at. + pub(crate) async fn peer_request_tier(&self, peer: EndpointId) -> InferenceRequestTier { + if peer == self.endpoint.id() || self.is_private_node(peer) { + return InferenceRequestTier::Local; + } + let summary = { + let state = self.state.lock().await; + state + .peers + .get(&peer) + .map(|info| info.owner_summary.clone()) + }; + let Some(summary) = summary else { + return InferenceRequestTier::Mesh; + }; + let Some(owner) = verified_owner(&summary, super::current_time_unix_ms()) else { + return InferenceRequestTier::Mesh; + }; + let local_owner = self.local_verified_owner_id().await; + let trusted = self + .trust_store + .lock() + .await + .trusted_owners + .iter() + .any(|entry| entry.owner_id.eq_ignore_ascii_case(owner)); + owner_tier(OwnerFacts { + peer_owner: Some(owner), + local_owner: local_owner.as_deref(), + trusted, + overridden: self.request_tier_owners.tier_of(owner), + }) + } + + /// The tier of a request entering at this node. A peer's request is the + /// lower of its claim and this node's view of the peer; any other request + /// started on this machine and is `local`, lowered by its own claim. + pub(crate) async fn ingress_request_tier( + &self, + raw: &[u8], + ingress_type: crate::runtime::IngressType, + requested_by: Option, + ) -> InferenceRequestTier { + let claimed = claimed_request_tier(raw); + match (ingress_type, requested_by) { + (crate::runtime::IngressType::RemoteQuicHttp, Some(peer)) => { + self.forwarded_request_tier(peer, claimed).await + } + (crate::runtime::IngressType::RemoteQuicHttp, None) => InferenceRequestTier::Mesh, + _ => claimed, + } + } + + /// The tier of a request `peer` forwarded here claiming `claimed`: the + /// lower of the claim and this node's own view of the peer. + pub(crate) async fn forwarded_request_tier( + &self, + peer: EndpointId, + claimed: InferenceRequestTier, + ) -> InferenceRequestTier { + claimed.min(self.peer_request_tier(peer).await) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const OWNER: &str = "1111111111111111111111111111111111111111111111111111111111111111"; + const OTHER: &str = "2222222222222222222222222222222222222222222222222222222222222222"; + + fn facts(peer_owner: Option<&'static str>) -> OwnerFacts<'static> { + OwnerFacts { + peer_owner, + local_owner: Some(OWNER), + trusted: false, + overridden: None, + } + } + + #[test] + fn an_unverified_peer_is_mesh_even_when_overridden() { + let tier = owner_tier(OwnerFacts { + overridden: Some(InferenceRequestTier::Local), + ..facts(None) + }); + assert_eq!(tier, InferenceRequestTier::Mesh); + } + + #[test] + fn the_own_owner_is_local_and_a_trusted_owner_is_trusted() { + assert_eq!(owner_tier(facts(Some(OWNER))), InferenceRequestTier::Local); + assert_eq!(owner_tier(facts(Some(OTHER))), InferenceRequestTier::Mesh); + let trusted = owner_tier(OwnerFacts { + trusted: true, + ..facts(Some(OTHER)) + }); + assert_eq!(trusted, InferenceRequestTier::Trusted); + } + + #[test] + fn an_override_replaces_the_derived_tier() { + let demoted = owner_tier(OwnerFacts { + overridden: Some(InferenceRequestTier::Mesh), + ..facts(Some(OWNER)) + }); + assert_eq!(demoted, InferenceRequestTier::Mesh); + let promoted = owner_tier(OwnerFacts { + overridden: Some(InferenceRequestTier::Local), + ..facts(Some(OTHER)) + }); + assert_eq!(promoted, InferenceRequestTier::Local); + } + + #[test] + fn only_a_valid_certificate_proves_an_owner() { + let summary = OwnershipSummary { + owner_id: Some(OWNER.into()), + status: OwnershipStatus::Verified, + expires_at_unix_ms: Some(1_000), + verified: true, + ..OwnershipSummary::default() + }; + assert_eq!(verified_owner(&summary, 999), Some(OWNER)); + assert_eq!(verified_owner(&summary, 1_000), None); + let untrusted = OwnershipSummary { + status: OwnershipStatus::UntrustedOwner, + ..summary + }; + assert_eq!(verified_owner(&untrusted, 0), None); + } + + #[test] + fn owner_overrides_come_from_the_config_file() { + let config = mesh_llm_config::parse_config_toml(&format!( + "[request_tiers.owners]\n\"{}\" = \"trusted\"\n", + OTHER.to_ascii_uppercase() + )) + .unwrap(); + let owners = RequestTierOwners::kept_current(&config, None, false); + assert_eq!(owners.tier_of(OTHER), Some(InferenceRequestTier::Trusted)); + assert_eq!(owners.tier_of(OWNER), None); + } + + #[tokio::test] + async fn the_tier_is_local_outside_a_classified_request() { + assert_eq!(current_request_tier(), InferenceRequestTier::Local); + let inside = + with_request_tier(InferenceRequestTier::Mesh, async { current_request_tier() }).await; + assert_eq!(inside, InferenceRequestTier::Mesh); + } + + #[test] + fn a_claim_reads_the_lowest_value_and_fails_low() { + let head = |headers: &str| { + format!("POST /v1/chat/completions HTTP/1.1\r\n{headers}\r\n").into_bytes() + }; + assert_eq!(claimed_request_tier(&head("")), InferenceRequestTier::Local); + let lowered = head("x-mesh-request-tier: local, trusted\r\nX-Mesh-Request-Tier: local\r\n"); + assert_eq!( + claimed_request_tier(&lowered), + InferenceRequestTier::Trusted + ); + let unknown = head("x-mesh-request-tier: owner\r\n"); + assert_eq!(claimed_request_tier(&unknown), InferenceRequestTier::Mesh); + } +} diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/stage_artifacts.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/stage_artifacts.rs index 6b0d0a5af1..58553b6fe9 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/stage_artifacts.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/stage_artifacts.rs @@ -198,6 +198,21 @@ impl Node { )) } + /// A stage serves its coordinator's requests no higher than this node + /// serves `requester`, whatever tier each message claims. + pub(super) async fn cap_stage_load_tier( + &self, + requester: EndpointId, + request: &mut crate::inference::skippy::StageControlRequest, + ) { + if let crate::inference::skippy::StageControlRequest::Load(load) + | crate::inference::skippy::StageControlRequest::LoadLocal(load) = request + { + let tier = self.peer_request_tier(requester).await; + load.max_request_tier = Some(tier.as_str().to_owned()); + } + } + pub(crate) async fn handle_stage_control( &self, remote: EndpointId, @@ -214,7 +229,8 @@ impl Node { remote.fmt_short() ); - let request = stage_control_request_from_proto(frame)?; + let mut request = stage_control_request_from_proto(frame)?; + self.cap_stage_load_tier(remote, &mut request).await; // #2217: Claim/Load are already identity-bound by the conversion; // Status/Inventory carry no coordinator identity in the command body, // so the authenticated requester must be a participant of the diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/stage_proto.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/stage_proto.rs index bef54ef25d..bacc494c3f 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/stage_proto.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/stage_proto.rs @@ -581,6 +581,7 @@ pub(super) fn stage_load_from_proto( load_mode: stage_load_mode_from_proto(load.load_mode)?, upstream: load.upstream.map(stage_peer_from_proto).transpose()?, downstream: load.downstream.map(stage_peer_from_proto).transpose()?, + max_request_tier: None, }) } diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/connections.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/connections.rs index e8a4316e5c..466ba92deb 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/connections.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/connections.rs @@ -332,6 +332,7 @@ fn stage_load_request() -> crate::inference::skippy::StageLoadRequest { load_mode: skippy_protocol::LoadMode::RuntimeSlice, upstream: None, downstream: None, + max_request_tier: None, } } @@ -470,6 +471,7 @@ async fn make_configured_test_node( trust_store: Arc::new(Mutex::new(TrustStore::default())), trust_policy: TrustPolicy::Off, private_nodes: Default::default(), + request_tier_owners: Default::default(), enumerate_host: false, gpu_name: None, hostname: None, diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/owner_control.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/owner_control.rs index 6f13a8c99d..6b3e7642ef 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/owner_control.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/owner_control.rs @@ -1115,3 +1115,36 @@ async fn scan_timeout_releases_caller_while_reconciliation_finishes() -> Result< ); Ok(()) } + +/// A legacy snapshot has no field for `[private]` or `[request_tiers]`, so +/// applying one keeps the node's own. +#[tokio::test] +async fn a_legacy_snapshot_keeps_the_private_list_and_request_tiers() -> Result<()> { + let node = make_test_node(super::NodeRole::Worker).await?; + let dir = tempfile::tempdir()?; + let path = dir.path().join("config.toml"); + let (private_node, owner) = (hex::encode([1u8; 32]), hex::encode([2u8; 32])); + std::fs::write( + &path, + format!( + "[private]\nnodes = [\"{private_node}\"]\n\n[request_tiers]\n\ + local_kv_reserve_percent = 25\n\n[request_tiers.owners]\n\"{owner}\" = \"mesh\"\n" + ), + )?; + *node.config_state.lock().await = crate::runtime::config_state::ConfigState::load(&path)?; + + let mut applied = crate::plugin::MeshConfig::default(); + node.restore_unsent_settings( + &mut applied, + &crate::proto::node::NodeConfigSnapshot::default(), + ) + .await; + + assert_eq!(applied.private.nodes, [private_node]); + assert_eq!(applied.request_tiers.local_kv_reserve_percent, 25); + assert_eq!( + applied.request_tiers.owners.get(&owner), + Some(&mesh_llm_config::RequestTierName::Mesh) + ); + Ok(()) +} diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/stage_control.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/stage_control.rs index 5121ad4f10..3ecc47a020 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/stage_control.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/stage_control.rs @@ -142,6 +142,7 @@ fn test_stage_load_request() -> crate::inference::skippy::StageLoadRequest { endpoint: "127.0.0.1:9002".to_string(), node_id: Some(make_test_endpoint_id(0x80)), }), + max_request_tier: None, } } @@ -1024,3 +1025,24 @@ async fn peer_load_without_downloads_is_refused_before_execution() -> Result<()> assert!(!executed.load(std::sync::atomic::Ordering::SeqCst)); Ok(()) } + +#[tokio::test] +async fn a_stage_loaded_for_a_peer_is_capped_at_the_peers_tier() -> Result<()> { + let node = Node::new_for_tests(crate::mesh::NodeRole::Worker).await?; + let stranger = make_test_endpoint_id(0x77); + let mut request = + crate::inference::skippy::StageControlRequest::Load(test_stage_load_request()); + node.cap_stage_load_tier(stranger, &mut request).await; + let crate::inference::skippy::StageControlRequest::Load(load) = &request else { + unreachable!("the request stays a load"); + }; + assert_eq!(load.max_request_tier.as_deref(), Some("mesh")); + + let mut own = crate::inference::skippy::StageControlRequest::LoadLocal(test_stage_load_request()); + node.cap_stage_load_tier(node.endpoint.id(), &mut own).await; + let crate::inference::skippy::StageControlRequest::LoadLocal(load) = &own else { + unreachable!("the request stays a local load"); + }; + assert_eq!(load.max_request_tier.as_deref(), Some("local")); + Ok(()) +} diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/stage_control_identity.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/stage_control_identity.rs index f17b8616bc..a0cf164fc6 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/stage_control_identity.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/tests/stage_control_identity.rs @@ -120,6 +120,7 @@ fn identity_test_load_request() -> crate::inference::skippy::StageLoadRequest { endpoint: "127.0.0.1:9002".to_string(), node_id: Some(make_test_endpoint_id(0x80)), }), + max_request_tier: None, } } diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/forwarded_request.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/forwarded_request.rs index a3b920238e..7e2e37206e 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/forwarded_request.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/forwarded_request.rs @@ -213,6 +213,8 @@ pub(super) fn prepare_peer_forwarded_request(raw: &[u8]) -> Result> { // A client's scope headers never pass through as is; see below. super::routing_scope::MESH_SCOPE_HEADER, super::routing_scope::MESH_SCOPE_NODES_HEADER, + // Restamped below with the tier this node serves the request at. + crate::mesh::request_tier::REQUEST_TIER_HEADER, ]; let omitted = INGRESS_CREDENTIAL_HEADERS .iter() @@ -220,6 +222,12 @@ pub(super) fn prepare_peer_forwarded_request(raw: &[u8]) -> Result> { .chain(OMITTED_ON_PEER_FORWARD.iter().copied()); let mut forwarded = finalize_forwarded_request(raw, false, None, None, &omitted.collect::>())?; + // Name the tier of this node's client, so the peer serves the request no + // higher. The peer keeps the lower of this and its own view of this node. + crate::mesh::request_tier::insert_request_tier_header( + &mut forwarded, + crate::mesh::request_tier::current_request_tier(), + ); // A private request only reaches nodes in this node's private scope. Tell that node // it is private, so it serves it only from what stays in scope (not from // a split whose stages run on a stranger's node). The receiving node @@ -254,7 +262,7 @@ mod tests { let forwarded = prepare_peer_forwarded_request(&raw).unwrap(); let mut expected = format!( - "POST /v1/responses HTTP/1.1\r\nHost: localhost\r\nX-Trace-Id: trace-123\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + "POST /v1/responses HTTP/1.1\r\nx-mesh-request-tier: local\r\nHost: localhost\r\nX-Trace-Id: trace-123\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len() ) .into_bytes(); @@ -319,6 +327,27 @@ mod tests { assert!(text.ends_with("\r\n\r\n{}"), "{text}"); } + /// The peer is told the tier this node serves the request at, never the + /// tier the client named. + #[tokio::test] + async fn the_peer_is_told_this_nodes_tier_for_the_request() { + let raw = b"POST /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\nX-Mesh-Request-Tier: local\r\nContent-Length: 2\r\n\r\n{}"; + let forwarded = crate::mesh::request_tier::with_request_tier( + skippy_inference_api::InferenceRequestTier::Trusted, + async { prepare_peer_forwarded_request(raw) }, + ) + .await + .unwrap(); + let text = String::from_utf8_lossy(&forwarded).to_ascii_lowercase(); + assert_eq!(text.matches("x-mesh-request-tier").count(), 1, "{text}"); + assert!( + text.starts_with( + "post /v1/chat/completions http/1.1\r\nx-mesh-request-tier: trusted\r\n" + ), + "{text}" + ); + } + /// Regression (CodeRabbit / erlich, PR #1671 round 2): routing headers /// must never survive a peer-to-peer hop, or a peer that re-enters /// `route_request` can re-route the request again with no hop bound. diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/ingress.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/ingress.rs index 2918c31b1e..ba39bc0f01 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/ingress.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/ingress.rs @@ -30,6 +30,9 @@ mod missing_model; mod private_scope_tests; mod realtime_relay; mod rejection_telemetry; +#[cfg(test)] +#[path = "ingress/request_tier_tests.rs"] +mod request_tier_tests; use buffered_exchange::handle_buffered_api_request; pub(super) use exchange_events::{RawProxyTerminalFacts, publish_raw_proxy_terminal}; use exchange_events::{ @@ -774,6 +777,43 @@ fn mesh_headers_force_remote( /// an effective and a terminal OpenAI exchange event to the plugin bus so any /// observing plugin can track the full lifecycle of each exchange, including /// cases where the backend returns an error or the connection is dropped. +/// Proxy `request` to the plugin endpoint serving `model_name`. The plugin's +/// own inference for the request runs no higher than its tier, until the +/// plugin has answered it. +async fn route_to_plugin_endpoint( + ctx: &IngressRouteContext<'_>, + plugin_manager: &crate::plugin::PluginManager, + endpoint: &crate::plugin::InferenceEndpointRoute, + tcp_stream: &mut ClientStream, + request: &proxy::BufferedHttpRequest, + model_name: &str, + route_observer: OpenAiRouteObserver<'_>, +) -> proxy::RouteDispatchOutcome { + let tiered_call = plugin_manager.begin_tiered_invocation( + &endpoint.plugin_name, + crate::mesh::request_tier::current_request_tier(), + ); + let outcome = proxy::route_http_endpoint_request( + ctx.node, + Some(model_name), + proxy::RouteSelectionMetadata { + provider: Some(&endpoint.plugin_name), + engine: Some(&endpoint.endpoint_id), + }, + tcp_stream, + &endpoint.address, + request, + route_observer, + ) + .await; + if let Some(call) = tiered_call + && outcome.response_written() + { + call.finish(); + } + outcome +} + async fn try_route_plugin_model( ctx: &IngressRouteContext<'_>, mut tcp_stream: ClientStream, @@ -812,16 +852,13 @@ async fn try_route_plugin_model( Ok(Some(endpoint)) => { let exchange_id = mint_and_publish_effective_raw_proxy(plugin_manager, model_name).await; - let outcome = proxy::route_http_endpoint_request( - ctx.node, - Some(model_name), - proxy::RouteSelectionMetadata { - provider: Some(&endpoint.plugin_name), - engine: Some(&endpoint.endpoint_id), - }, + let outcome = route_to_plugin_endpoint( + ctx, + plugin_manager, + &endpoint, &mut tcp_stream, - &endpoint.address, request, + model_name, route_observer, ) .await; @@ -1603,6 +1640,9 @@ async fn handle_api_proxy_connection_inner( Some(scope) => node.targets_in_private_scope(scope, &targets).await, None => targets, }; + let tier = node + .ingress_request_tier(&request.raw, ingress_type, requested_by) + .await; // Boxed: the dispatch future is large, and the scope wrapper would // otherwise move it across another stack frame. let dispatch = Box::pin(async move { @@ -1637,7 +1677,7 @@ async fn handle_api_proxy_connection_inner( ) .await; }); - mesh::with_private_scope(scope, dispatch).await; + mesh::with_private_scope(scope, mesh::request_tier::with_request_tier(tier, dispatch)).await; } /// A request that arrived over the mesh HTTP tunnel. `remote` is the tunnel's diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/ingress/realtime_relay.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/ingress/realtime_relay.rs index 93f98133e1..ed391ff23a 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/ingress/realtime_relay.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/ingress/realtime_relay.rs @@ -273,7 +273,13 @@ async fn relay_local( ) -> anyhow::Result { let mut upstream = tokio::net::TcpStream::connect(("127.0.0.1", port)).await?; upstream.set_nodelay(true)?; - upstream.write_all(opening).await?; + let classified = mesh::request_tier::mark_class_for_local_server( + opening, + mesh::current_private_scope().is_some(), + ); + upstream + .write_all(classified.as_deref().unwrap_or(opening)) + .await?; relay_bytes(client, upstream, REALTIME_IDLE_TIMEOUT).await } @@ -284,7 +290,13 @@ async fn relay_remote( peer: iroh::EndpointId, ) -> anyhow::Result { let (mut send, recv) = node.open_http_tunnel(peer).await?; - send.write_all(opening).await?; + // The peer serves the session no higher than this node's client. + let mut opening = opening.to_vec(); + mesh::request_tier::insert_request_tier_header( + &mut opening, + mesh::request_tier::current_request_tier(), + ); + send.write_all(&opening).await?; let upstream = ClientStream::from_quic_with_prefix(recv, send, Vec::new()); relay_bytes(client, upstream, REALTIME_IDLE_TIMEOUT).await } diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/ingress/request_tier_tests.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/ingress/request_tier_tests.rs new file mode 100644 index 0000000000..e5f3c644e4 --- /dev/null +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/ingress/request_tier_tests.rs @@ -0,0 +1,155 @@ +//! The tier a request is served at, as this node's local server sees it: +//! the ingress classifies the request and names it on the loopback hop. + +use super::*; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; + +/// A local server that records the head of the one request it gets. +async fn recording_backend() -> (u16, tokio::task::JoinHandle) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let task = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let mut bytes = Vec::new(); + let mut buffer = [0; 4096]; + let end = loop { + let n = stream.read(&mut buffer).await.unwrap(); + assert!(n > 0, "request ended before its head"); + bytes.extend_from_slice(&buffer[..n]); + if let Some(end) = bytes.windows(4).position(|part| part == b"\r\n\r\n") { + break end; + } + }; + let body = r#"{"id":"test","model":"m","choices":[]}"#; + let wire = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + stream.write_all(wire.as_bytes()).await.unwrap(); + String::from_utf8_lossy(&bytes[..end]).to_ascii_lowercase() + }); + (port, task) +} + +/// Send one request through the ingress to a local server; the head that +/// server received. +async fn head_at_local_server( + node: &mesh::Node, + ingress_type: crate::runtime::IngressType, + requested_by: Option, + extra_headers: &str, +) -> String { + let (port, backend) = recording_backend().await; + let mut targets = election::ModelTargets::default(); + targets + .targets + .insert("m".into(), vec![election::InferenceTarget::Local(port)]); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let ingress = { + let node = node.clone(); + tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + handle_api_proxy_connection( + node, + stream.into(), + targets, + affinity::AffinityRouter::new(), + ingress_type, + requested_by, + ) + .await; + }) + }; + let mut client = TcpStream::connect(address).await.unwrap(); + let body = r#"{"model":"m","messages":[{"role":"user","content":"hi"}]}"#; + let request = format!( + "POST /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\n{extra_headers}Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + client.write_all(request.as_bytes()).await.unwrap(); + let mut response = String::new(); + tokio::time::timeout( + std::time::Duration::from_secs(10), + client.read_to_string(&mut response), + ) + .await + .unwrap() + .unwrap(); + assert!(response.starts_with("HTTP/1.1 200"), "{response}"); + ingress.await.unwrap(); + backend.await.unwrap() +} + +fn tier_lines(head: &str) -> Vec<&str> { + head.lines() + .filter(|line| line.starts_with("x-skippy-request-tier:")) + .collect() +} + +#[tokio::test] +async fn a_local_client_is_served_at_local_unless_it_asks_for_less() { + let node = mesh::Node::new_for_tests(mesh::NodeRole::Worker) + .await + .unwrap(); + let local = crate::runtime::IngressType::LocalOpenAi; + + let head = head_at_local_server(&node, local, None, "").await; + assert!(tier_lines(&head).is_empty(), "{head}"); + + // A client cannot speak for the node to its server; it can only lower + // its own tier through the mesh header. + let head = head_at_local_server( + &node, + local, + None, + "x-skippy-request-tier: local\r\nx-skippy-cache-partition: private\r\nx-mesh-request-tier: trusted\r\n", + ) + .await; + assert_eq!( + tier_lines(&head), + ["x-skippy-request-tier: trusted"], + "{head}" + ); + assert!(!head.contains("x-skippy-cache-partition"), "{head}"); + node.endpoint.close().await; +} + +#[tokio::test] +async fn a_peer_is_served_no_higher_than_this_node_classifies_it() { + let mut node = mesh::Node::new_for_tests(mesh::NodeRole::Worker) + .await + .unwrap(); + let remote = crate::runtime::IngressType::RemoteQuicHttp; + let stranger = iroh::SecretKey::from_bytes(&[91; 32]).public(); + let listed = iroh::SecretKey::from_bytes(&[92; 32]).public(); + node.private_nodes = crate::mesh::private_nodes::PrivateNodes::of([listed]); + + // An unknown peer's claim to be local does not raise it. + let head = head_at_local_server( + &node, + remote, + Some(stranger), + "x-mesh-request-tier: local\r\n", + ) + .await; + assert_eq!(tier_lines(&head), ["x-skippy-request-tier: mesh"], "{head}"); + + // A private node is this node's own; it still names its client's tier. + let head = head_at_local_server(&node, remote, Some(listed), "").await; + assert!(tier_lines(&head).is_empty(), "{head}"); + let head = head_at_local_server( + &node, + remote, + Some(listed), + "x-mesh-request-tier: trusted\r\n", + ) + .await; + assert_eq!( + tier_lines(&head), + ["x-skippy-request-tier: trusted"], + "{head}" + ); + node.endpoint.close().await; +} diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/request_parse.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/request_parse.rs index 3d8afa302e..e1672b7fa1 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/request_parse.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/request_parse.rs @@ -482,17 +482,25 @@ where let requires_json_transform = request_requires_json_transform(&parsed.path, &body, plugin_manager.is_some()) || (transformer.is_some() && plugin_transform::is_transformable_path(&parsed.path)); - let rewrite = rewrite_request_body_for_forwarding( - &parsed.path, - &body, - plugin_manager, - Transformer { - plugins: transformer, - private_hint: parsed.private_base - || super::routing_scope::head_requests_private_scope(&raw), - node_limit: super::routing_scope::head_node_limit(&raw), - }, - requires_json_transform, + // Transforms run before the request's tier is scoped (only a client of + // this node gets them, whose tier is the one its head claims), so scope + // them to it here. + let tier = crate::mesh::request_tier::current_request_tier() + .min(crate::mesh::request_tier::claimed_request_tier(&raw)); + let rewrite = crate::mesh::request_tier::with_request_tier( + tier, + rewrite_request_body_for_forwarding( + &parsed.path, + &body, + plugin_manager, + Transformer { + plugins: transformer, + private_hint: parsed.private_base + || super::routing_scope::head_requests_private_scope(&raw), + node_limit: super::routing_scope::head_node_limit(&raw), + }, + requires_json_transform, + ), ) .await .map_err(|error| OpenAiRequestReadError::after_headers(error, &parsed))?; @@ -862,6 +870,13 @@ fn finalize_forwarded_request( if name.eq_ignore_ascii_case(RAW_LIFECYCLE_OWNER_HEADER) { continue; } + // Only this node names a request's class to its own Skippy server + // (`mesh::request_tier`); a client's or peer's naming is dropped. + if name.eq_ignore_ascii_case(skippy_inference_api::REQUEST_TIER_HEADER) + || name.eq_ignore_ascii_case(skippy_inference_api::CACHE_PARTITION_HEADER) + { + continue; + } if strip_expect && name.eq_ignore_ascii_case("expect") { continue; } diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/request_parse/plugin_transform.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/request_parse/plugin_transform.rs index c6b8de7362..d53f506bbd 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/request_parse/plugin_transform.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/request_parse/plugin_transform.rs @@ -136,6 +136,92 @@ mod tests { } } + /// Records the tier its own nested inference would run at while it + /// transforms a request, and leaves the request unchanged. + #[derive(Default)] + struct TierProbe { + manager: std::sync::OnceLock, + seen: std::sync::Mutex>, + } + + impl PluginRpcBridge for Arc { + fn handle_request( + &self, + plugin_name: String, + _method: String, + params_json: String, + ) -> BridgeFuture> { + let probe = Arc::clone(self); + Box::pin(async move { + let tier = probe + .manager + .get() + .unwrap() + .nested_request_tier(&plugin_name); + probe.seen.lock().unwrap().push(tier); + let input: RequestTransformInput = serde_json::from_str(¶ms_json).unwrap(); + Ok(RpcResult { + result_json: serde_json::to_string(&RequestTransformOutput::replaced( + input.body, + )) + .unwrap(), + }) + }) + } + + fn handle_notification(&self, _: String, _: String, _: String) -> BridgeFuture<()> { + Box::pin(async {}) + } + } + + #[tokio::test] + async fn a_transform_runs_at_the_tier_the_client_lowered_its_request_to() { + let probe = Arc::new(TierProbe::default()); + let manager = plugin::PluginManager::for_test_bridge(&["probe"], Arc::new(probe.clone())); + manager + .set_test_manifests( + [( + "probe".to_string(), + mesh_llm_plugin::plugin_manifest![ + mesh_llm_plugin::request_transform::request_transform() + ], + )] + .into(), + ) + .await; + assert!(probe.manager.set(manager.clone()).is_ok()); + let body = + json!({"model": "m", "messages": [{"role": "user", "content": "hi"}]}).to_string(); + for (header, expected) in [ + ("", skippy_inference_api::InferenceRequestTier::Local), + ( + "x-mesh-request-tier: mesh\r\n", + skippy_inference_api::InferenceRequestTier::Mesh, + ), + ] { + let (mut client, mut server) = tokio::io::duplex(64 * 1024); + let request = format!( + "POST /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\n{header}Content-Length: {}\r\n\r\n{body}", + body.len() + ); + client.write_all(request.as_bytes()).await.unwrap(); + super::super::read_http_request_with_limits_with_context( + &mut server, + super::super::HTTP_READ_LIMITS, + Some(&manager), + RequestTransforms::Apply, + ) + .await + .map_err(super::super::OpenAiRequestReadError::into_error) + .unwrap(); + assert_eq!(probe.seen.lock().unwrap().pop(), Some(expected)); + } + assert_eq!( + manager.nested_request_tier("probe"), + skippy_inference_api::InferenceRequestTier::Local + ); + } + async fn stamping_manager() -> plugin::PluginManager { let manager = plugin::PluginManager::for_test_bridge(&["stamp"], Arc::new(PathStamp)); manager diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/common.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/common.rs index 1c8f33bbf8..1337e57d51 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/common.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/common.rs @@ -794,4 +794,9 @@ mod tests { br#"{"error":{"message":"missing required field: messages"}}"# )); } + #[test] + fn a_request_refused_by_the_local_kv_reserve_is_retried_elsewhere() { + let body = br#"{"error":{"message":"request requires 6 KV tokens, which exceeds the 5 of the 10-token runtime pool that mesh requests may use; the rest is reserved for local requests"}}"#; + assert!(is_retryable_context_overflow_response(body)); + } } diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/routing.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/routing.rs index 083638d0bb..4ea5f32334 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/routing.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/response/routing.rs @@ -38,7 +38,9 @@ pub(in crate::network::openai) async fn route_local_attempt( peer_capsule_id, } = logging; let marked; - let prefetched = match mesh::current_private_scope() { + let private_scope = mesh::current_private_scope(); + let private = private_scope.is_some(); + let prefetched = match private_scope { Some(scope) => { // Whichever route chose it: a private request runs on this node // only inside its scope. @@ -52,6 +54,9 @@ pub(in crate::network::openai) async fn route_local_attempt( } None => prefetched, }; + // Skippy orders, evicts and partitions its caches by the request's class. + let classified = mesh::request_tier::mark_class_for_local_server(prefetched, private); + let prefetched = classified.as_deref().unwrap_or(prefetched); let served_model = served_model_headers_for_mesh_peer(node, tcp_stream, model, port).await; let Ok((_instance_request, mut upstream)) = acquire_local_attempt_upstream(node, port).await else { 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 94635ff51f..a5a0efb18b 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 @@ -435,7 +435,7 @@ pub async fn handle_mesh_request( let mut tcp_stream = tcp_stream; let source_addr = tcp_stream.peer_addr().ok(); let plugin_manager = node.plugin_manager().await; - let mut request = match read_http_request_with_plugin_manager_with_context( + let request = match read_http_request_with_plugin_manager_with_context( &mut tcp_stream, plugin_manager.as_ref(), super::request_parse::RequestTransforms::Apply, @@ -448,6 +448,31 @@ pub async fn handle_mesh_request( return; } }; + // Every client of this port is local; one may lower its own request. + let tier = crate::mesh::request_tier::claimed_request_tier(&request.raw); + crate::mesh::request_tier::with_request_tier( + tier, + Box::pin(serve_mesh_request( + node, + tcp_stream, + request, + source_addr, + track_demand, + affinity, + )), + ) + .await; +} + +/// Serve a request read by [`handle_mesh_request`], at the tier in scope. +async fn serve_mesh_request( + node: mesh::Node, + tcp_stream: ClientStream, + mut request: BufferedHttpRequest, + source_addr: Option, + track_demand: bool, + affinity: AffinityRouter, +) { let Some(tcp_stream) = refuse_private_at_bootstrap(&node, tcp_stream, &mut request).await else { return; diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/openai/virtual_model/mod.rs b/mesh/crates/mesh-llm-host-runtime/src/network/openai/virtual_model/mod.rs index 275c1f14dd..96892238e2 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/openai/virtual_model/mod.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/openai/virtual_model/mod.rs @@ -84,6 +84,13 @@ impl InferenceRpcBridge { capability.request_id().as_uuid().to_string(), ); } + let tier = self.plugins.nested_request_tier(plugin_name); + if tier != skippy_inference_api::InferenceRequestTier::Local { + request_builder = request_builder.header( + crate::mesh::request_tier::REQUEST_TIER_HEADER, + tier.as_str(), + ); + } if let Some(scope) = self.plugins.private_nested_scope(plugin_name) { request_builder = request_builder.header( super::routing_scope::MESH_SCOPE_HEADER, @@ -340,13 +347,21 @@ fn invoke_in_scope<'a>( ) -> impl std::future::Future> + 'a { let private_turn = mesh::current_private_scope() .map(|scope| plugins.begin_private_invocation(&route.plugin_name, Some(scope))); + // Its nested calls run no higher than the request's tier. + let tiered_turn = plugins.begin_tiered_invocation( + &route.plugin_name, + mesh::request_tier::current_request_tier(), + ); let (manager, owned_route, input_json) = (plugins.clone(), route.clone(), input_json.to_string()); - // A private turn runs to the plugin's reply even if the client leaves, - // and lingers unless the plugin replied: a timed-out turn may still run. - // Any reply ends it, an error or invalid output included. - async move { - let response = crate::plugin::private_invocations::run_to_reply(private_turn, async move { + // A private or lowered turn runs to the plugin's reply even if the + // client leaves, and lingers unless the plugin replied: a timed-out turn + // may still run. Any reply ends it, an error or invalid output included. + // Boxed: the turn's future is copied through several progress layers, + // and the call would otherwise be held twice inside each copy. + let call = Box::pin(crate::plugin::private_invocations::run_to_reply( + private_turn, + async move { manager .invoke_virtual_model_service( &owned_route, @@ -354,8 +369,10 @@ fn invoke_in_scope<'a>( Some(std::time::Duration::from_secs(300)), ) .await - }) - .await?; + }, + )); + async move { + let response = crate::plugin::tiered_invocations::run_to_reply(tiered_turn, call).await?; PluginManager::virtual_model_response(route, response) } } diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/exchange_lifecycle.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/exchange_lifecycle.rs index 2271d7cf5a..27b8e4ca72 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/exchange_lifecycle.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/exchange_lifecycle.rs @@ -221,11 +221,12 @@ impl PluginManager { ..Default::default() }; }; - { + let tier = { let state = state.lock().unwrap(); event["exchange_id"] = json!(state.exchange_id); event["endpoint"] = json!(state.endpoint); - } + state.tier + }; event["observation_id"] = json!(observation_id); if let Some(id) = event["backend_exchange_id"].as_str() { let mut emission = state.lock().unwrap(); @@ -247,7 +248,10 @@ impl PluginManager { let mut result = self .exchange_permissions_preflight(event["endpoint"].as_str().unwrap_or_default()) .await; - result.merge(self.exchange_phase(event.clone()).await); + result.merge( + crate::mesh::request_tier::with_request_tier(tier, self.exchange_phase(event.clone())) + .await, + ); let mut state = state.lock().unwrap(); let skipped = more_candidates && result.is_candidate_deny(); // A hook that failed to observe the skipped attempt still leaves the @@ -484,11 +488,22 @@ async fn invoke_phase( // moment it can see the request: the body stream is sent first. let private_call = crate::mesh::current_private_scope() .map(|scope| manager.begin_private_invocation(name, Some(scope))); - if let Some(encoded) = event["body_hex"].as_str() { - let bytes = hex::decode(encoded).map_err(|_| HookFailure::Internal)?; - if bytes.len() as u64 > grant.max_body_bytes { - return Err(HookFailure::EvidenceUnavailable); - } + let body = event["body_hex"] + .as_str() + .map(|encoded| hex::decode(encoded).map_err(|_| HookFailure::Internal)) + .transpose()?; + if body + .as_ref() + .is_some_and(|bytes| bytes.len() as u64 > grant.max_body_bytes) + { + return Err(HookFailure::EvidenceUnavailable); + } + // It also runs no higher than the request's tier, from just before the + // body is sent to the hook's reply: a hook past its deadline may still + // be working. + let tiered_call = + manager.begin_tiered_invocation(name, crate::mesh::request_tier::current_request_tier()); + if let Some(bytes) = body { let kind = if phase == "request_received" { "openai_exchange_original" } else { @@ -543,6 +558,9 @@ async fn invoke_phase( } }; let reply = reply.map_err(|_| HookFailure::Internal)?; + if let Some(call) = tiered_call { + call.finish(); + } if reply.is_error || reply.output_json.len() > 32 * 1024 { return Err(HookFailure::Internal); } @@ -644,6 +662,9 @@ struct EmissionState { selected: Option, evidence_unavailable: bool, internal_hook_failure: bool, + /// The exchange's request tier: a phase reached from the backend runs on + /// the backend's task, not the request's. + tier: skippy_inference_api::InferenceRequestTier, } #[derive(Default)] @@ -682,6 +703,8 @@ pub(crate) struct ExchangeSession { response_delivery: BTreeMap, /// A private exchange's private scope, restored for its terminal callback. scope: Option, + /// The exchange's request tier, restored for its terminal callback. + tier: skippy_inference_api::InferenceRequestTier, /// For a private exchange, keeps every observing plugin's own inference /// private from admission to its terminal callback: between callbacks it /// still holds request and response content. @@ -716,6 +739,7 @@ impl ExchangeSession { .unwrap_or(1), ); let deadline = Instant::now() + budget; + let tier = crate::mesh::request_tier::current_request_tier(); let scope = crate::mesh::current_private_scope(); let private_observers = match &scope { Some(scope) => manager @@ -755,6 +779,7 @@ impl ExchangeSession { denied: result.denied, evidence_unavailable: result.evidence_unavailable, internal_hook_failure: result.internal_hook_failure, + tier, ..Default::default() })); manager @@ -783,6 +808,7 @@ impl ExchangeSession { finished: false, response_delivery: BTreeMap::new(), scope, + tier, private_observers, }, result, @@ -824,6 +850,7 @@ impl ExchangeSession { finished: true, response_delivery: BTreeMap::new(), scope: self.scope.clone(), + tier: self.tier, private_observers: std::mem::take(&mut self.private_observers), } } @@ -831,10 +858,13 @@ impl ExchangeSession { /// its observers' private binding. async fn run_terminal(mut self, outcome: String) { let scope = self.scope.clone(); - crate::mesh::with_private_scope(scope, async { - let terminal = self.final_terminal_event(&outcome).await; - self.manager.exchange_phase(terminal).await; - }) + crate::mesh::with_private_scope( + scope, + crate::mesh::request_tier::with_request_tier(self.tier, async { + let terminal = self.final_terminal_event(&outcome).await; + self.manager.exchange_phase(terminal).await; + }), + ) .await; for observer in std::mem::take(&mut self.private_observers) { observer.finish(); diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/exchange_policy.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/exchange_policy.rs index 9296bc41da..3f7355f0c9 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/exchange_policy.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/exchange_policy.rs @@ -91,7 +91,13 @@ impl InferenceHookPolicy for NodeExchangePolicy { request: &GenerationRequest, route: &ChatExchangeRoute, ) -> InferenceResult<()> { - self.admit_typed_request( + // The backend stamps the request's class from its context; a hook + // never runs above it even on a task that carries no tier. + let tier = request + .request_class + .tier() + .min(crate::mesh::request_tier::current_request_tier()); + let admission = self.admit_typed_request( || { serde_json::to_vec( &skippy_inference_api::chat::request_view::ChatCompletionRequestRef(request), @@ -101,8 +107,8 @@ impl InferenceHookPolicy for NodeExchangePolicy { "chat_completions", "/v1/chat/completions", &route.exchange_id, - ) - .await + ); + crate::mesh::request_tier::with_request_tier(tier, admission).await } async fn admit_effective_completion( &self, @@ -228,8 +234,19 @@ impl HttpExchangePolicy for NodeExchangePolicy { event["dispatch_path"] = json!("typed_frontend"); // A private request's hooks run in its scope here too. let scope = crate::network::openai::routing_scope::local_server_scope(headers); - let (session, result) = - crate::mesh::with_private_scope(scope, ExchangeSession::begin(&manager, event)).await; + // And at its tier, which this node named on the loopback hop. + let tier = skippy_inference_api::InferenceRequestTier::from_headers( + headers, + skippy_inference_api::REQUEST_TIER_HEADER, + ); + let (session, result) = crate::mesh::with_private_scope( + scope, + crate::mesh::request_tier::with_request_tier( + tier, + ExchangeSession::begin(&manager, event), + ), + ) + .await; let denial = result.error_status().map(|status| match status { 402 | 403 => policy_denial(status, "OpenAI plugin policy denied the exchange"), _ => hook_unavailable("required OpenAI plugin admission unavailable"), diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/mod.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/mod.rs index 7f872a10cb..8e16253c9e 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/mod.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/mod.rs @@ -44,6 +44,7 @@ mod startup; mod startup_tests; mod supervision; mod support; +pub(crate) mod tiered_invocations; mod transport; mod types; mod web_ui; @@ -151,6 +152,7 @@ pub(in crate::plugin) struct PluginManagerInner { pub(in crate::plugin) rpc_bridge: Arc>>>, pub(in crate::plugin) shutting_down: AtomicBool, pub(in crate::plugin) private_invocations: private_invocations::PrivateInvocations, + pub(in crate::plugin) tiered_invocations: tiered_invocations::TieredInvocations, #[cfg(test)] pub(in crate::plugin) bridged_plugins: BTreeSet, #[cfg(test)] @@ -250,6 +252,7 @@ impl PluginManager { rpc_bridge, shutting_down: AtomicBool::new(false), private_invocations: Default::default(), + tiered_invocations: Default::default(), #[cfg(test)] bridged_plugins: BTreeSet::new(), #[cfg(test)] @@ -479,6 +482,7 @@ impl PluginManager { rpc_bridge: Arc::new(Mutex::new(Some(bridge))), shutting_down: AtomicBool::new(false), private_invocations: Default::default(), + tiered_invocations: Default::default(), bridged_plugins: plugin_names .iter() .map(|name| (*name).to_string()) @@ -511,6 +515,7 @@ impl PluginManager { rpc_bridge: Arc::new(Mutex::new(None)), shutting_down: AtomicBool::new(false), private_invocations: Default::default(), + tiered_invocations: Default::default(), bridged_plugins: BTreeSet::new(), test_endpoints: Arc::new(Mutex::new(Vec::new())), test_inference_endpoints: Arc::new(Mutex::new(Vec::new())), @@ -967,6 +972,24 @@ impl PluginManager { self.inner.private_invocations.begin(plugin_name, nodes) } + /// Mark `plugin_name` as handling a request at `tier` until the guard + /// drops; `None` for a `local` request. See [`tiered_invocations`]. + pub(crate) fn begin_tiered_invocation( + &self, + plugin_name: &str, + tier: skippy_inference_api::InferenceRequestTier, + ) -> Option { + self.inner.tiered_invocations.begin(plugin_name, tier) + } + + /// The tier nested inference from `plugin_name` runs at. + pub(crate) fn nested_request_tier( + &self, + plugin_name: &str, + ) -> skippy_inference_api::InferenceRequestTier { + self.inner.tiered_invocations.nested_tier(plugin_name) + } + /// How nested inference from `plugin_name` must be scoped, if private. pub(crate) fn private_nested_scope( &self, diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/request_transform.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/request_transform.rs index d0696ac4fd..d648c0f235 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/request_transform.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/request_transform.rs @@ -112,14 +112,24 @@ impl PluginManager { // request's own node limit when it is itself a nested call. let private_call = || private.then(|| self.begin_private_invocation(plugin_name, node_limit.clone())); + // They also run no higher than the request's tier. + let tiered_call = || { + self.begin_tiered_invocation( + plugin_name, + crate::mesh::request_tier::current_request_tier(), + ) + }; if self.is_test_bridge_enabled(plugin_name) { - let call = private_call(); + let (call, tiered) = (private_call(), tiered_call()); let output = self .mcp_request(plugin_name, "request_transform/invoke", input) .await; if let Some(call) = call { call.finish(); } + if let Some(tiered) = tiered { + tiered.finish(); + } return output; } if !self.inner.plugins.contains_key(plugin_name) { @@ -128,22 +138,26 @@ impl PluginManager { // The plugin is done once it replies, whatever the reply says; the // call runs to that reply even if the client leaves. let (manager, name) = (self.clone(), plugin_name.to_string()); - let response = super::private_invocations::run_to_reply(private_call(), async move { - let plugin = manager - .inner - .plugins - .get(&name) - .with_context(|| format!("Unknown plugin '{name}'"))?; - plugin - .invoke_service( - proto::ServiceKind::RequestTransform, - SERVICE_NAME, - &input_json, - Some(TRANSFORM_TIMEOUT), - ) - .await - }) - .await?; + let tiered = tiered_call(); + let call = Box::pin(super::private_invocations::run_to_reply( + private_call(), + async move { + let plugin = manager + .inner + .plugins + .get(&name) + .with_context(|| format!("Unknown plugin '{name}'"))?; + plugin + .invoke_service( + proto::ServiceKind::RequestTransform, + SERVICE_NAME, + &input_json, + Some(TRANSFORM_TIMEOUT), + ) + .await + }, + )); + let response = super::tiered_invocations::run_to_reply(tiered, call).await?; if response.is_error { bail!( "request transform plugin '{plugin_name}' failed: {}", diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/tiered_invocations.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/tiered_invocations.rs new file mode 100644 index 0000000000..40272dd923 --- /dev/null +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/tiered_invocations.rs @@ -0,0 +1,262 @@ +//! The tier of the requests each plugin is handling. +//! +//! A plugin calls back into the host for its own inference on a different +//! task from the request it is handling, so the request's tier does not +//! follow it (see [`crate::mesh::request_tier`]). While a plugin handles a +//! request below `local` (a virtual-model turn, an OpenAI exchange), the host +//! serves every nested call from that plugin at the lowest such tier. +//! Like [`super::private_invocations`] this is per plugin, not per request: a +//! `local` request handled by the same plugin at the same moment is lowered +//! too, never the other way round, so no peer gains a tier through a plugin. +//! +//! A plugin keeps working on a call the host sends no cancel for, so the +//! binding lasts as the private one does: to the plugin's reply +//! ([`run_to_reply`]), and for [`ABANDONED_LINGER`] after a call that ended +//! without one. + +use super::private_invocations::ABANDONED_LINGER; +use skippy_inference_api::InferenceRequestTier; +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +#[derive(Default)] +struct State { + next_id: u64, + /// Per plugin: each running invocation's tier, by invocation id. + active: BTreeMap>, + /// Per plugin: abandoned invocations' tiers, until they stop lingering. + lingering: BTreeMap>, +} + +impl State { + /// Forget `plugin`'s lingering tiers that have expired. + fn reap(&mut self, plugin: &str, now: Instant) { + if let Some(lingering) = self.lingering.get_mut(plugin) { + lingering.retain(|(until, _)| *until > now); + if lingering.is_empty() { + self.lingering.remove(plugin); + } + } + } +} + +#[derive(Clone)] +pub(crate) struct TieredInvocations { + state: Arc>, + linger: Duration, +} + +impl Default for TieredInvocations { + fn default() -> Self { + Self { + state: Arc::default(), + linger: ABANDONED_LINGER, + } + } +} + +/// Holds a plugin's nested calls at or below its tier until dropped. Call +/// [`finish`](Self::finish) once the plugin has replied; dropping it +/// unfinished keeps the tier for the linger period. +pub(crate) struct TieredInvocationGuard { + invocations: TieredInvocations, + plugin: String, + id: u64, + finished: bool, +} + +impl TieredInvocations { + fn lock(&self) -> std::sync::MutexGuard<'_, State> { + self.state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Record that `plugin` handles a request at `tier`. `None` for a + /// `local` request, which lowers nothing. + pub(crate) fn begin( + &self, + plugin: &str, + tier: InferenceRequestTier, + ) -> Option { + if tier == InferenceRequestTier::Local { + return None; + } + let mut state = self.lock(); + state.reap(plugin, Instant::now()); + let id = state.next_id; + state.next_id += 1; + state + .active + .entry(plugin.to_string()) + .or_default() + .insert(id, tier); + Some(TieredInvocationGuard { + invocations: self.clone(), + plugin: plugin.to_string(), + id, + finished: false, + }) + } + + /// The tier `plugin`'s nested inference runs at: the lowest of the + /// requests it is handling or has abandoned, `local` when there are none. + pub(crate) fn nested_tier(&self, plugin: &str) -> InferenceRequestTier { + let mut state = self.lock(); + state.reap(plugin, Instant::now()); + let active = state + .active + .get(plugin) + .into_iter() + .flat_map(|active| active.values().copied()); + let lingering = state + .lingering + .get(plugin) + .into_iter() + .flat_map(|lingering| lingering.iter().map(|(_, tier)| *tier)); + active + .chain(lingering) + .min() + .unwrap_or(InferenceRequestTier::Local) + } +} + +/// Run `call`, a plugin invocation, holding `guard` until the plugin replies +/// (`Ok`) or the call ends without a reply (`Err`, which lingers). With a +/// guard, the call runs on its own task to completion, so a caller that +/// stops waiting does not cut the binding short while the plugin works on. +pub(crate) async fn run_to_reply( + guard: Option, + call: F, +) -> anyhow::Result +where + T: Send + 'static, + F: std::future::Future> + Send + 'static, +{ + let Some(guard) = guard else { + return call.await; + }; + tokio::spawn(async move { + let reply = call.await; + if reply.is_ok() { + guard.finish(); + } + reply + }) + .await + .unwrap_or_else(|error| Err(anyhow::anyhow!("tiered plugin call failed: {error}"))) +} + +impl TieredInvocationGuard { + /// The plugin replied: this invocation no longer needs to linger. + pub(crate) fn finish(mut self) { + self.finished = true; + } +} + +impl Drop for TieredInvocationGuard { + fn drop(&mut self) { + let linger = self.invocations.linger; + let mut state = self.invocations.lock(); + let tier = state + .active + .get_mut(&self.plugin) + .and_then(|active| active.remove(&self.id)); + if state + .active + .get(&self.plugin) + .is_some_and(BTreeMap::is_empty) + { + state.active.remove(&self.plugin); + } + if !self.finished + && let Some(tier) = tier + { + state + .lingering + .entry(self.plugin.clone()) + .or_default() + .push((Instant::now() + linger, tier)); + } + // Expired entries go even if the plugin never calls back. + state.reap(&self.plugin, Instant::now()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nested_calls_run_at_the_lowest_running_tier() { + let invocations = TieredInvocations::default(); + assert_eq!(invocations.nested_tier("p"), InferenceRequestTier::Local); + assert!( + invocations + .begin("p", InferenceRequestTier::Local) + .is_none() + ); + + let trusted = invocations.begin("p", InferenceRequestTier::Trusted); + assert_eq!(invocations.nested_tier("p"), InferenceRequestTier::Trusted); + let mesh = invocations.begin("p", InferenceRequestTier::Mesh); + let second_mesh = invocations.begin("p", InferenceRequestTier::Mesh); + assert_eq!(invocations.nested_tier("p"), InferenceRequestTier::Mesh); + assert_eq!( + invocations.nested_tier("other"), + InferenceRequestTier::Local + ); + + mesh.unwrap().finish(); + assert_eq!(invocations.nested_tier("p"), InferenceRequestTier::Mesh); + second_mesh.unwrap().finish(); + assert_eq!(invocations.nested_tier("p"), InferenceRequestTier::Trusted); + trusted.unwrap().finish(); + assert_eq!(invocations.nested_tier("p"), InferenceRequestTier::Local); + let state = invocations.lock(); + assert!(state.active.is_empty() && state.lingering.is_empty()); + } + + #[test] + fn an_abandoned_invocation_keeps_its_tier_until_the_linger_ends() { + let lingering = TieredInvocations::default(); + drop(lingering.begin("p", InferenceRequestTier::Mesh)); + assert_eq!(lingering.nested_tier("p"), InferenceRequestTier::Mesh); + + let expired = TieredInvocations { + linger: Duration::ZERO, + ..TieredInvocations::default() + }; + drop(expired.begin("p", InferenceRequestTier::Mesh)); + assert_eq!(expired.nested_tier("p"), InferenceRequestTier::Local); + assert!(expired.lock().lingering.is_empty()); + } + + #[tokio::test] + async fn a_caller_that_stops_waiting_does_not_end_the_binding() { + let invocations = TieredInvocations::default(); + let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>(); + let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>(); + let guard = invocations.begin("p", InferenceRequestTier::Mesh); + let call = tokio::spawn(run_to_reply(guard, async move { + let _ = started_tx.send(()); + let _ = release_rx.await; + Ok(()) + })); + // The plugin is working; the caller then stops waiting. + started_rx.await.unwrap(); + call.abort(); + let _ = call.await; + assert_eq!(invocations.nested_tier("p"), InferenceRequestTier::Mesh); + + release_tx.send(()).unwrap(); + for _ in 0..200 { + if invocations.nested_tier("p") == InferenceRequestTier::Local { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert_eq!(invocations.nested_tier("p"), InferenceRequestTier::Local); + } +} diff --git a/mesh/crates/mesh-llm-host-runtime/src/protocol/config_tests.rs b/mesh/crates/mesh-llm-host-runtime/src/protocol/config_tests.rs index 177ca1f581..dd829af3f6 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/protocol/config_tests.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/protocol/config_tests.rs @@ -16,6 +16,7 @@ fn config_sync_full_config_roundtrip() { mesh_requirements: Default::default(), owner_control: Default::default(), private: Default::default(), + request_tiers: Default::default(), telemetry: Default::default(), analytics: Default::default(), updates: mesh_llm_config::UpdatesConfig { 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 0a5b221e56..1002e38ecf 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/protocol/convert.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/protocol/convert.rs @@ -35,7 +35,7 @@ fn skippy_stage_subprotocols( } if stage_protocol_generation_supported { features.push( - skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V16.to_string(), + skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V17.to_string(), ); } if artifact_transfer_supported { @@ -89,7 +89,7 @@ fn supports_decode_batch_policy(subprotocols: &[crate::proto::node::MeshSubproto /// Accept a stage generation only when one descriptor contains its entire bundle. fn supports_skippy_stage_generation(subprotocols: &[crate::proto::node::MeshSubprotocol]) -> bool { let required_features = [ - skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V16, + skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V17, skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_CONTROL, skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STATUS_LIST, skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_LOCAL_GGUF_CONTENT_ID_V1, @@ -1515,6 +1515,7 @@ fn legacy_proto_config_to_mesh( mesh_requirements, owner_control: Default::default(), private: Default::default(), + request_tiers: Default::default(), telemetry: Default::default(), analytics: Default::default(), updates: Default::default(), 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 84cdb96a7f..f108f5a1e0 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 @@ -107,7 +107,7 @@ fn owner_fields_roundtrip_through_proto_announcement() { .any(|feature| feature == skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STATUS_LIST) ); assert!(skippy.features.iter().any(|feature| feature - == skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V16)); + == skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V17)); assert_eq!( proto_pa .owner_attestation @@ -524,13 +524,13 @@ fn proto_announcement_without_required_generation_bundle_is_not_stage_compatible let peer_id = EndpointId::from(SecretKey::from_bytes(&[0xD0; 32]).public()); for missing in [ skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_CONTROL, - skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V16, + skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V17, skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STATUS_LIST, skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_LOCAL_GGUF_CONTENT_ID_V1, ] { let features = [ skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_CONTROL, - skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V16, + skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V17, skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STATUS_LIST, skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_LOCAL_GGUF_CONTENT_ID_V1, ] @@ -599,7 +599,7 @@ fn partial_duplicate_stage_records_do_not_form_a_generation_bundle() { major: skippy_protocol::STAGE_SUBPROTOCOL_MAJOR, features: vec![ skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_CONTROL.to_string(), - skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V16 + skippy_protocol::STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V17 .to_string(), ], }, diff --git a/mesh/crates/mesh-llm-host-runtime/src/protocol/tests/config.rs b/mesh/crates/mesh-llm-host-runtime/src/protocol/tests/config.rs index 03deb92333..042df22809 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/protocol/tests/config.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/protocol/tests/config.rs @@ -297,6 +297,7 @@ fn mesh_requirements_survive_owner_control_config_round_trip() { }, owner_control: OwnerControlConfig::default(), private: Default::default(), + request_tiers: Default::default(), telemetry: Default::default(), analytics: Default::default(), updates: Default::default(), @@ -428,6 +429,7 @@ fn config_sync_config_hash_determinism() { mesh_requirements: Default::default(), owner_control: Default::default(), private: Default::default(), + request_tiers: Default::default(), telemetry: Default::default(), analytics: Default::default(), updates: Default::default(), @@ -467,6 +469,7 @@ fn config_sync_config_hash_determinism() { mesh_requirements: Default::default(), owner_control: Default::default(), private: Default::default(), + request_tiers: Default::default(), telemetry: Default::default(), analytics: Default::default(), updates: Default::default(), @@ -540,6 +543,7 @@ fn pinned_gpu_proto_roundtrip() { mesh_requirements: Default::default(), owner_control: Default::default(), private: Default::default(), + request_tiers: Default::default(), telemetry: Default::default(), analytics: Default::default(), updates: Default::default(), diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime/config_state_tests/persistence.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime/config_state_tests/persistence.rs index 60da9c2e80..eb7b41cba9 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime/config_state_tests/persistence.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime/config_state_tests/persistence.rs @@ -42,6 +42,7 @@ fn config_sync_noop_apply_skips_disk_write() { mesh_requirements: Default::default(), owner_control: Default::default(), private: Default::default(), + request_tiers: Default::default(), telemetry: Default::default(), analytics: Default::default(), updates: Default::default(), diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime/config_state_tests/support.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime/config_state_tests/support.rs index 5027b0a085..57fab6a30a 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime/config_state_tests/support.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime/config_state_tests/support.rs @@ -98,6 +98,7 @@ pub(super) fn minimal_valid_config() -> MeshConfig { mesh_requirements: Default::default(), owner_control: Default::default(), private: Default::default(), + request_tiers: Default::default(), telemetry: Default::default(), analytics: Default::default(), updates: Default::default(), diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime/config_state_tests/sync.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime/config_state_tests/sync.rs index b296ff490e..d883ed24a9 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime/config_state_tests/sync.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime/config_state_tests/sync.rs @@ -268,6 +268,7 @@ fn config_sync_state_revision_monotonic() { mesh_requirements: Default::default(), owner_control: Default::default(), private: Default::default(), + request_tiers: Default::default(), telemetry: Default::default(), analytics: Default::default(), updates: Default::default(), @@ -320,6 +321,7 @@ fn config_sync_state_hash_changes_on_different_config() { mesh_requirements: Default::default(), owner_control: Default::default(), private: Default::default(), + request_tiers: Default::default(), telemetry: Default::default(), analytics: Default::default(), updates: Default::default(), diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/coordinator.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/coordinator.rs index 0f7d72f063..81d5874fa1 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/coordinator.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/coordinator.rs @@ -74,7 +74,7 @@ impl SplitTopologyGeneration { /// Run this generation with `choice` on every hop. The codec rides each /// stage's load request and the topology hash, so all stages of one - /// generation use the coordinator's choice. Every stage-generation-16 + /// generation use the coordinator's choice. Every stage-generation-17 /// peer decodes every codec, so no choice needs a capability check. pub(super) fn with_activation_codec(mut self, choice: SplitActivationCodec) -> Self { self.activation_codec = choice.codec; diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/loading.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/loading.rs index 671742692b..648909f7f0 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/loading.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/loading.rs @@ -17,6 +17,7 @@ use crate::runtime::local_package::{ use crate::runtime::survey; use anyhow::{Context, Result}; use mesh_llm_events::{OutputEvent, emit_event}; +use skippy_inference_api::InferenceRequestTier; use skippy_protocol::{FlashAttentionType, LoadMode, PeerConfig}; use skippy_serving::serving_hooks::SharedModelServingHooksFactory; use std::collections::HashMap; @@ -660,6 +661,8 @@ pub(super) async fn stage0_runtime_options( runtime_options.config.load_mode = settings.load_mode.clone(); runtime_options.config.bind_addr = stage0_return_endpoint.to_string(); runtime_options.config.upstream = None; + runtime_options.config.max_request_tier = + Some(split_peer_request_tier(spec).await.as_str().to_owned()); runtime_options.config.downstream = Some(PeerConfig { persistent_lane_marker: spec .node @@ -672,6 +675,29 @@ pub(super) async fn stage0_runtime_options( Ok(runtime_options) } +/// The highest tier stage 0's listener serves: the tier this node gives the +/// owner of the final stage. Only that node may open a stage transport into +/// stage 0 (to return its predictions), and stage messages carry a tier the +/// sender claims. +async fn split_peer_request_tier(spec: &SplitGenerationLoadSpec<'_>) -> InferenceRequestTier { + match remote_final_stage_owner(&spec.generation.stages, spec.node.id()) { + Some(owner) => spec.node.peer_request_tier(owner).await, + None => InferenceRequestTier::Local, + } +} + +/// The owner of the split's final stage, unless that is this node. +pub(super) fn remote_final_stage_owner( + stages: &[crate::runtime::split_planning::RuntimeSliceStagePlan], + own_id: iroh::EndpointId, +) -> Option { + stages + .iter() + .max_by_key(|stage| stage.stage_index) + .map(|stage| stage.node_id) + .filter(|owner| *owner != own_id) +} + pub(super) fn apply_admitted_activation_frontier( config: &mut skippy_protocol::StageConfig, load: &skippy::StageLoadRequest, @@ -985,6 +1011,7 @@ pub(super) fn split_runtime_stage_load_request( load_mode: settings.load_mode.clone(), upstream, downstream, + max_request_tier: None, }) } diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/test_support.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/test_support.rs index 16f21a490a..1dc4687c06 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/test_support.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/test_support.rs @@ -97,6 +97,7 @@ pub(super) fn stage_load_request(load_mode: LoadMode) -> skippy::StageLoadReques load_mode, upstream: None, downstream: None, + max_request_tier: None, } } diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/tests.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/tests.rs index 9773ece50d..f91eb3a3f6 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/tests.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/tests.rs @@ -2205,3 +2205,22 @@ fn a_split_drafts_short_dflash_blocks_unless_the_cap_is_configured() { assert_eq!(split_dflash_max_draft_tokens(Some(15), true), Some(15)); assert_eq!(split_dflash_max_draft_tokens(Some(2), true), Some(2)); } + +#[test] +fn stage_zero_is_capped_by_the_final_stage_owner_only() { + let stage = |index: u32, node| RuntimeSliceStagePlan { + stage_id: format!("stage-{index}"), + stage_index: index, + node_id: make_id(node), + layer_start: index * 10, + layer_end: index * 10 + 10, + parameter_bytes: 0, + }; + let own = make_id(1); + // Listed out of order: the final stage is the highest index, not the last entry. + let split = [stage(0, 1), stage(2, 3), stage(1, 2)]; + assert_eq!(remote_final_stage_owner(&split, own), Some(make_id(3))); + let returns_to_self = [stage(0, 1), stage(1, 2), stage(2, 1)]; + assert_eq!(remote_final_stage_owner(&returns_to_self, own), None); + assert_eq!(remote_final_stage_owner(&[], own), None); +} diff --git a/mesh/crates/mesh-llm-host-runtime/src/sdk.rs b/mesh/crates/mesh-llm-host-runtime/src/sdk.rs index 35dc7d2fc7..f3b3ed6be8 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/sdk.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/sdk.rs @@ -428,6 +428,8 @@ impl EmbeddedServingController { prompt_cache_retention: None, stream_options: None, extra: BTreeMap::new(), + // The embedding app's own request. + request_class: Default::default(), }; let handle = loaded .handle diff --git a/mesh/crates/mesh-llm-skippy-adapter/src/config/resolution.rs b/mesh/crates/mesh-llm-skippy-adapter/src/config/resolution.rs index 304d464905..3fdafcfce1 100644 --- a/mesh/crates/mesh-llm-skippy-adapter/src/config/resolution.rs +++ b/mesh/crates/mesh-llm-skippy-adapter/src/config/resolution.rs @@ -674,6 +674,12 @@ fn resolve_throughput_config(context: &ResolverContext<'_>) -> ResolvedThroughpu threads, threads_batch, tuning_profile: throughput.effective_profile, + local_kv_reserve_percent: context + .request + .mesh_config + .request_tiers + .local_kv_reserve_percent + .min(100), } } diff --git a/mesh/crates/mesh-llm-skippy-adapter/src/config/translation.rs b/mesh/crates/mesh-llm-skippy-adapter/src/config/translation.rs index 592107908a..b185e21e79 100644 --- a/mesh/crates/mesh-llm-skippy-adapter/src/config/translation.rs +++ b/mesh/crates/mesh-llm-skippy-adapter/src/config/translation.rs @@ -367,6 +367,7 @@ impl ResolvedSkippyConfig { ), generation_admission_timeout_secs: skippy_serving::DEFAULT_GENERATION_ADMISSION_TIMEOUT_SECS, + local_kv_reserve_percent: self.throughput.local_kv_reserve_percent, prefill_chunk_size: self.skippy.prefill_chunk_size, prefill_chunk_policy: resolve_prefill_chunk_policy(&self.skippy.prefill_chunking), prefill_chunk_schedule: self.skippy.prefill_chunk_schedule.clone(), diff --git a/mesh/crates/mesh-llm-skippy-adapter/src/config/types.rs b/mesh/crates/mesh-llm-skippy-adapter/src/config/types.rs index 157a911b05..ff06e56686 100644 --- a/mesh/crates/mesh-llm-skippy-adapter/src/config/types.rs +++ b/mesh/crates/mesh-llm-skippy-adapter/src/config/types.rs @@ -123,6 +123,8 @@ pub struct ResolvedThroughputConfig { pub threads: Option, pub threads_batch: Option, pub tuning_profile: String, + /// Share of the admission token budget only `local` requests may use. + pub local_kv_reserve_percent: u8, } #[derive(Clone, Debug, PartialEq)] diff --git a/mesh/crates/mesh-llm/src/commands/runtime.rs b/mesh/crates/mesh-llm/src/commands/runtime.rs index 091d7b0841..db9b8ffa05 100644 --- a/mesh/crates/mesh-llm/src/commands/runtime.rs +++ b/mesh/crates/mesh-llm/src/commands/runtime.rs @@ -1011,6 +1011,7 @@ mod tests { plugins: Vec::new(), owner_control: Default::default(), private: Default::default(), + request_tiers: Default::default(), telemetry: Default::default(), analytics: Default::default(), updates: Default::default(), diff --git a/mesh/docs/CONFIGURATION_PR8_CLOSEOUT_AUDIT.md b/mesh/docs/CONFIGURATION_PR8_CLOSEOUT_AUDIT.md index 3f47ae83b1..b98932fb2d 100644 --- a/mesh/docs/CONFIGURATION_PR8_CLOSEOUT_AUDIT.md +++ b/mesh/docs/CONFIGURATION_PR8_CLOSEOUT_AUDIT.md @@ -35,7 +35,8 @@ schema row or stale manifest row from passing review: `mesh_requirements.min_protocol_version`, `mesh_requirements.max_protocol_version`, `mesh_requirements.require_release_attestation`, `mesh_requirements.release_signer_keys`, `mesh_requirements.require_signed_gossip`, -`private.nodes`, `owner_control.bind`, `owner_control.advertise_addr`, `payments.wallet`, +`private.nodes`, `request_tiers.owners`, `request_tiers.local_kv_reserve_percent`, +`owner_control.bind`, `owner_control.advertise_addr`, `payments.wallet`, `telemetry.enabled`, `telemetry.service_name`, `telemetry.endpoint`, `telemetry.headers`, `telemetry.export_interval_secs`, `telemetry.queue_size`, diff --git a/mesh/docs/README.md b/mesh/docs/README.md index 2c8d4ef135..ce372177b4 100644 --- a/mesh/docs/README.md +++ b/mesh/docs/README.md @@ -40,6 +40,7 @@ Use this hub to find project guides that are not owned by a single Rust crate. | [specs/layer-package-repos.md](../../skippy/docs/specs/layer-package-repos.md) | Manifest schema and package artifact rules | | [specs/mesh-setup-installer.md](specs/mesh-setup-installer.md) | Bootstrap installer and `mesh-llm setup` ownership boundary | | [specs/private-routing.md](specs/private-routing.md) | `@private`/`@incognito` requests that stay on your own nodes, and how to list them | +| [specs/request-tiers.md](specs/request-tiers.md) | Serving local and owned requests before mesh requests: tiers, admission order, KV eviction and cache isolation | | [SKIPPY.md](../../skippy/docs/SKIPPY.md) | Skippy integration readiness and parity notes | Use [SKIPPY_SPLITS.md](../../skippy/docs/SKIPPY_SPLITS.md) for Skippy split-serving workflows. diff --git a/mesh/docs/design/TESTING.md b/mesh/docs/design/TESTING.md index 3a74a733ae..1ea91a4f37 100644 --- a/mesh/docs/design/TESTING.md +++ b/mesh/docs/design/TESTING.md @@ -909,8 +909,8 @@ cached and a worker does not: to open `skippy-stage/2`, then Skippy artifact-transfer stream 0x03, to fetch only its assigned package files before the normal HF fallback path. - Current/released mixed mesh: a coordinator without the complete - `stage-generation-16` control/status/content-identity/admission bundle must not - be selected for a generation-16 split topology. Missing `artifact-transfer` + `stage-generation-17` control/status/content-identity/admission bundle must not + be selected for a generation-17 split topology. Missing `artifact-transfer` only prevents peer cache sourcing; the worker may still participate when local/HF package resolution provides an independent source. diff --git a/mesh/docs/specs/private-routing.md b/mesh/docs/specs/private-routing.md index 14e0e9635c..9ae401e6f4 100644 --- a/mesh/docs/specs/private-routing.md +++ b/mesh/docs/specs/private-routing.md @@ -138,12 +138,14 @@ upgrade them, your older nodes simply don't serve private requests. On the node itself, requests marked private turn off peer consultation (Mesh hooks for images, uncertainty and drift), which would pick peers outside the scope, and run its exchange hooks in the request's scope. +Its prompt cache keeps private requests apart: a private request neither +reuses nor leaves behind cache entries a non-private request can see (see +[Request tiers](request-tiers.md)). ## Not yet - The startup (bootstrap) proxy refuses private requests (503) until the node is ready. -- A separate prompt-cache namespace, console and launcher (`--private`) - support. +- Console and launcher (`--private`) support. - Per-turn private scope for MoA nested requests. - Peer consultation for private requests. diff --git a/mesh/docs/specs/request-tiers.md b/mesh/docs/specs/request-tiers.md new file mode 100644 index 0000000000..3b8d3757fd --- /dev/null +++ b/mesh/docs/specs/request-tiers.md @@ -0,0 +1,154 @@ +# Request tiers + +A node serves requests for its owner before requests for the rest of the +mesh. Every request it serves gets a **tier** when it enters the node, and +the tier decides the order of admission, which KV cache entries go first +when memory runs out, and which prompt cache the request may reuse. + +## Tiers + +| Tier | Who | +|---|---| +| `local` | This machine; a node on its `[private] nodes` list; a node with a verified certificate from this node's own owner | +| `trusted` | A node with a verified certificate from an owner in this node's trust store | +| `mesh` | Everyone else, including any node without a verified certificate | + +A node on the `[private] nodes` list is `local` whatever its certificate +says, and no owner override changes that. A certificate counts only while it +is valid: an expired, revoked or unverifiable one makes the node `mesh`. The +node reads its trust store when it starts, so an owner added with +`mesh-llm auth trust add` is `trusted` after the next restart. + +A shared-serving membership classifies the nodes of the mesh it joined +against that membership's own trust store, its admission allowlist. Every +node the membership admits is therefore `trusted` there, and shares the +`trusted` cache with the main node's trusted owners. + +`[request_tiers] owners` in `config.toml` replaces the tier of one owner's +verified nodes: + +```toml +[request_tiers.owners] +"8a88e3dd7409f195fd52db2d3cba5d72ca6709bf1d94121bf3748801b40f6f5c" = "trusted" +``` + +An entry can raise or lower an owner. It never applies to a node without a +verified certificate from that owner. A running node rereads the entries +when the file changes. While the file is missing or does not load, the node +keeps the entries it last read, so a broken edit cannot lift an owner that +an entry lowers; owner ids that differ only in letter case are rejected. + +## Assignment + +The node a request enters decides its tier once: + +- A request from a client of this node (the API port, the console's `/v1` + passthrough, the native SDK, a plugin's own inference) is `local`. That + includes a remote caller of a console opened with `--listen-all`. +- A request a peer forwarded is at the tier this node gives that peer. + +A node that forwards a request names its client's tier in the +`x-mesh-request-tier` header. The receiving node serves the request at the +lower of that claim and its own tier for the sender, so a peer can lower +its own requests but never raise them. A client may send the header to +lower its own request. A value that is not a tier name, or a head that +cannot be read, counts as `mesh`. + +The tier follows the request's work on this node: peer consultations, +including those Skippy's generation hooks start, the peers a virtual +model's turn calls, the peer a realtime session is relayed to and the +plugins that see the request (exchange hooks, request transforms, a +plugin-served model). A plugin calls back into the node on a separate task, +so while a plugin handles a request below `local`, every nested call from +that plugin runs at the lowest tier it is handling. Each call to the plugin +holds that from when the plugin is sent the request until it replies: a +client that leaves does not end it, and a call that ended without a reply +keeps it for five minutes. The binding is per plugin, not per request, so a +`local` request the same plugin handles at the same moment is lowered too; +once the plugin has replied, its later calls are not lowered. + +## What the tier changes + +Skippy reads the tier from the request and applies it to the model's +admission and caches: + +- **Admission.** Waiting requests are admitted highest tier first. Each + time 16 higher-tier requests are admitted ahead of a waiting request, it + ranks one tier higher, up to the tier of another waiting request, so a + lower-tier request that fits the free KV budget gets a share under + steady higher-tier load. Ranking orders only requests that fit: a + lower-tier request too large for the tokens higher tiers leave free (for + `trusted` and `mesh`, outside the `local` reserve) is passed by every + higher-tier request that fits, and waits until higher-tier load leaves it + room or its admission timeout ends the wait. Waiting behind its own tier + does not age a request: a long `mesh` queue never outranks a `local` + arrival. Within a tier the usual cache-aware order applies whatever the + ages. Each tier's oldest waiter has the admission starvation bound, + checked from the highest tier down: past it, the waiter is admitted next + if it fits and no higher-tier waiter does, and otherwise holds back its + own and lower tiers, never a higher one, while the pool drains. Only waiting + requests of the same or a higher tier count against the waiting-room + limit, so mesh traffic cannot fill the room ahead of a `local` request. + The advisory predicted wait reported for a request counts the same + waiters, plus the requests already running. +- **KV reservation.** `[request_tiers] local_kv_reserve_percent` keeps a + share of each model's KV token budget for `local` requests, rounded up to + a whole token; other tiers can use only the rest. A request of another tier that needs more than the + rest is refused as exceeding the context, which a forwarding node retries + on another host. The default, `0`, reserves nothing; the setting applies + when a model loads. +- **Eviction.** Every resident prefix and recurrent-state entry records the + tier that stored it. Under memory pressure the lowest tier is evicted + first, then the usual cost and age order applies within a tier, however + old the higher tier's entries are. While higher-tier entries fill the + exact-state cache, a lower tier's snapshot that would only evict itself + is not taken. +- **Cache isolation.** Each tier keeps its own prompt cache, and private + requests (`@private`, `x-mesh-scope: private`) have their own cache within + their tier. A request never reuses a prefix another tier, or the other + side of the private line, computed. A `local` request outside the private + partition keeps the cache keys standalone Skippy uses. + +A request already running is not interrupted when a higher tier arrives. + +## Split serving + +A coordinator stamps the tier and private flag of every request on the +cache-bearing messages it sends its stages. When a node loads a stage, it +records the tier it gives the coordinator; that stage serves the +coordinator's messages no higher than that tier, whatever they claim, and +evicts by the result. It partitions its caches by both the tier it serves +and the one claimed, so claims the cap merges still never share a prefix. +The tier a stage allows is fixed when the stage loads: a change to the +trust store or the owner overrides, or a certificate that expires or is +revoked, applies to the next load. + +The last stage sends its predictions back to the coordinator's stage 0, and +only that stage's owner may open a stage connection to it. Stage 0 serves +stage messages no higher than the tier the coordinator gives that node. + +This is stage protocol generation 17. All stages of a split must run it; +older stages fail stage negotiation. + +## Limits + +- Disk (L2/L3) prefix caches are partitioned by tier but are not evicted in + tier order. +- Skippy's realtime and transcription paths do not read the tier; it only + chooses the peer a realtime session goes to. +- A middle stage of a split forwards the coordinator's stamp to the next + stage, which caps it by its own tier for the coordinator. A middle stage + could change the stamp within that cap; it already sees every token of + the request. +- A node on a public API port treats every client of that port as `local`. +- A plugin's nested inference is lowered per plugin, not per request: while + a plugin handles a `mesh` request, or for five minutes after one that + ended without a reply, the plugin's calls for `local` requests run at + `mesh` too. +- A native SDK call forwarded to a peer carries no claim; the peer serves it + at its tier for the calling node. Native SDK requests have no private + scope, so they are never served as private; carrying one would need a + private flag in the native request. +- After admission, a request takes one of the runtime's execution lanes, + which it shares with split-stage clients of the same runtime in arrival + order, whatever the tier. diff --git a/mesh/website/src/docs/pages/config-reference.md b/mesh/website/src/docs/pages/config-reference.md index b3f47ba051..a16abd0d20 100644 --- a/mesh/website/src/docs/pages/config-reference.md +++ b/mesh/website/src/docs/pages/config-reference.md @@ -87,6 +87,8 @@ produces a clear startup error rather than a partial start. | `mesh_requirements.require_signed_gossip` | boolean | `false`; require origin signatures for relayed node/cache records; changing this creates a new mesh and requires upgraded participants | node-level | process restart | wired | `--require-signed-gossip` | | `mesh_requirements.release_signer_keys` | array of string | `[]`; when non-empty, only those signer keys admit peers | node-level | process restart | wired | none | | `private.nodes` | array of string | `[]` (private requests stay on this node); node ids of 64 hex characters. See [Private routing](/docs/pages/config-toml/#private-nodes) | node-level | applies dynamically | wired | `mesh-llm private add` / `remove` | +| `request_tiers.owners` | object (string map) | `{}`; owner id (64 hex characters) to `local`, `trusted` or `mesh`, overriding the tier that owner's nodes are served at. See [Request tiers](/docs/pages/config-toml/#request-tiers) | node-level | applies dynamically | wired | none | +| `request_tiers.local_kv_reserve_percent` | integer | `0` (no reserve); 0 to 100, the share of each model's KV token budget only `local` requests may use | node-level | model reload | wired | none | | `owner_control.bind` | socket address | unset (auto); e.g. `[::]:7447` | node-level | process restart | wired | none | | `owner_control.advertise_addr` | socket address | unset (auto-detected) | node-level | process restart | wired | none | | `telemetry.enabled` | boolean | `false` | node-level | process restart | wired | none | diff --git a/mesh/website/src/docs/pages/config-toml.md b/mesh/website/src/docs/pages/config-toml.md index 74f2a58e86..42c5e5c742 100644 --- a/mesh/website/src/docs/pages/config-toml.md +++ b/mesh/website/src/docs/pages/config-toml.md @@ -64,6 +64,31 @@ nodes = ["8a88e3dd7409f195fd52db2d3cba5d72ca6709bf1d94121bf3748801b40f6f5c"] - A running node rereads the list when the file changes, without a restart. - `mesh-llm private` takes the config file's lock, so its edits never collide with a running node saving a console change. A text editor does not: the node refuses to save over an edit it sees, but an edit landing in the instant before its save can be lost. While a node is running, prefer `mesh-llm private`. +## Request tiers + +Every request this node serves gets a tier, from whom it is served for: + +- `local` — this machine, its private nodes, and nodes with a verified certificate from this node's own owner. +- `trusted` — nodes with a verified certificate from an owner in this node's trust store. +- `mesh` — everyone else. + +Higher tiers are admitted first (a waiting lower-tier request moves up one tier +each time 16 higher-tier requests are admitted ahead of it, so it is not passed +over indefinitely while it fits), their KV cache is evicted last, and each tier, plus private requests within it, keeps its own prompt +cache. A node that forwards a request names its client's tier; the receiving +node keeps the lower of that claim and its own classification of the sender. + +```toml +[request_tiers] +local_kv_reserve_percent = 20 + +[request_tiers.owners] +"8a88e3dd7409f195fd52db2d3cba5d72ca6709bf1d94121bf3748801b40f6f5c" = "trusted" +``` + +- `owners` — owner ids (64 hex characters, as `mesh-llm auth status` prints them) mapped to `local`, `trusted` or `mesh`. An entry replaces the tier the owner's verified nodes would otherwise get; it never affects nodes without a verified certificate. Owner ids that differ only in letter case are rejected. A running node rereads it when the file changes, and keeps the entries it last read while the file is missing or does not load. +- `local_kv_reserve_percent` — share of each model's KV token budget that only `local` requests may use, 0 to 100. `0` (the default) reserves nothing. Applies when a model loads. + ## Payments Paid inference is not part of the node and has no `config.toml` section. Payment diff --git a/skippy/crates/skippy-api/src/serving.rs b/skippy/crates/skippy-api/src/serving.rs index e297805805..b702187132 100644 --- a/skippy/crates/skippy-api/src/serving.rs +++ b/skippy/crates/skippy-api/src/serving.rs @@ -31,6 +31,8 @@ pub struct InferenceOptions { pub pipeline_decode_groups: Option, pub adaptive_generation_min_concurrency: Option, pub generation_queue_capacity: usize, + /// Percent of the KV token budget only `local`-tier requests may reserve. + pub local_kv_reserve_percent: u8, pub generation_admission_timeout_secs: u64, pub prefill_chunk_size: usize, pub prefill_chunk_policy: String, @@ -88,6 +90,7 @@ impl InferenceOptions { generation_queue_capacity: skippy_serving::frontend::default_generation_queue_capacity( generation_concurrency, ), + local_kv_reserve_percent: 0, generation_admission_timeout_secs: DEFAULT_GENERATION_ADMISSION_TIMEOUT_SECS, prefill_chunk_size: BUILTIN_PREFILL_CHUNK_SIZE, prefill_chunk_policy: skippy_config::local_serving::PREFILL_CHUNK_POLICY.to_string(), @@ -148,6 +151,7 @@ impl InferenceOptions { pipeline_decode_groups: self.pipeline_decode_groups, adaptive_generation_min_concurrency: self.adaptive_generation_min_concurrency, generation_queue_capacity: self.generation_queue_capacity, + local_kv_reserve_percent: self.local_kv_reserve_percent, generation_admission_timeout_secs: self.generation_admission_timeout_secs, prefill_chunk_size: self.prefill_chunk_size, prefill_chunk_policy: self.prefill_chunk_policy, diff --git a/skippy/crates/skippy-api/src/stage.rs b/skippy/crates/skippy-api/src/stage.rs index 984a9079ee..0e0646b7b9 100644 --- a/skippy/crates/skippy-api/src/stage.rs +++ b/skippy/crates/skippy-api/src/stage.rs @@ -230,6 +230,7 @@ pub fn single_stage_config( bind_addr: "127.0.0.1:0".to_string(), upstream: None, downstream: None, + max_request_tier: None, }; config.kv_cache = options .kv_cache diff --git a/skippy/crates/skippy-api/src/stage_load.rs b/skippy/crates/skippy-api/src/stage_load.rs index 5edea38e84..f6609b6e9a 100644 --- a/skippy/crates/skippy-api/src/stage_load.rs +++ b/skippy/crates/skippy-api/src/stage_load.rs @@ -76,6 +76,9 @@ pub struct AdmittedStageOptions { pub upstream: Option, pub downstream: Option, pub admission: skippy_protocol::StageAdmissionDescriptor, + /// Highest request tier this stage serves; see + /// [`StageConfig::max_request_tier`]. `None` serves the stamped tier. + pub max_request_tier: Option, } impl AdmittedStageOptions { @@ -201,6 +204,7 @@ pub fn admitted_stage_config( bind_addr: load.bind_addr.clone(), upstream: load.upstream.clone(), downstream: load.downstream.clone(), + max_request_tier: load.max_request_tier.clone(), }; let family_policy = crate::family_policy::family_policy_for_stage_config(&config); config.kv_cache = package.map_or_else( diff --git a/skippy/crates/skippy-cache/README.md b/skippy/crates/skippy-cache/README.md index 3b85fdc64a..bff991f8e7 100644 --- a/skippy/crates/skippy-cache/README.md +++ b/skippy/crates/skippy-cache/README.md @@ -24,6 +24,12 @@ used to discover shared resident prefixes. Attention admission uses physical native occupancy rather than summing overlapping logical prefix lengths. Recurrent checkpoint RAM is bounded separately and works with disk disabled. +Serving puts the request tier and private partition in the cache namespace +(see `skippy-inference-api`'s request tiers), so a prefix one tier or partition +computed never matches another's. Recurrent entries are evicted by the +retention their owner gives them (`evict_recurrent_by_retention`), least +recently used first among equals; serving uses the storing request's tier. + This adopts SGLang's separation of radix-owned attention blocks and recurrent checkpoints through llama.cpp's native memory interfaces. It does not embed SGLang's Torch runtime. See [the prompt-cache design](../../docs/PROMPT_CACHE.md) diff --git a/skippy/crates/skippy-cache/src/identity.rs b/skippy/crates/skippy-cache/src/identity.rs index 939bf51509..a7f8b2503d 100644 --- a/skippy/crates/skippy-cache/src/identity.rs +++ b/skippy/crates/skippy-cache/src/identity.rs @@ -707,6 +707,7 @@ mod identity_completeness_tests { bind_addr: "127.0.0.1:0".to_string(), upstream: None, downstream: None, + max_request_tier: None, } } @@ -1079,6 +1080,7 @@ mod identity_stability_tests { bind_addr: "127.0.0.1:0".to_string(), upstream: None, downstream: None, + max_request_tier: None, } } diff --git a/skippy/crates/skippy-cache/src/radix.rs b/skippy/crates/skippy-cache/src/radix.rs index e6a480ee3f..31314ec081 100644 --- a/skippy/crates/skippy-cache/src/radix.rs +++ b/skippy/crates/skippy-cache/src/radix.rs @@ -354,7 +354,47 @@ impl UnifiedRadixCache { } pub fn evict_lru_recurrent(&mut self) -> Option> { - let victim = self.lru_victim(ComponentKind::KvRecurrent)?; + self.evict_recurrent_by_retention(|_| 0) + } + + /// The retention of the entry [`Self::evict_recurrent_by_retention`] + /// would evict next, if any is evictable. + pub fn recurrent_victim_retention(&self, retention: impl Fn(&E) -> u64) -> Option { + self.ranked_victim(&|node| { + node.components + .recurrent + .as_ref() + .filter(|entry| entry.active_refs == 0) + .map(|entry| { + ( + retention(&entry.value), + entry.last_used, + entry.logical_bytes, + ) + }) + }) + .map(|victim| victim.retention) + } + + /// Evict the unreferenced recurrent entry with the lowest `retention`, + /// least recently used first among equals. + pub fn evict_recurrent_by_retention( + &mut self, + retention: impl Fn(&E) -> u64, + ) -> Option> { + let victim = self.ranked_victim(&|node| { + node.components + .recurrent + .as_ref() + .filter(|entry| entry.active_refs == 0) + .map(|entry| { + ( + retention(&entry.value), + entry.last_used, + entry.logical_bytes, + ) + }) + })?; let value = self.remove_recurrent(&victim.namespace, &victim.tokens)?; self.recurrent_evictions = self.recurrent_evictions.saturating_add(1); Some(RadixEviction { @@ -391,9 +431,29 @@ impl UnifiedRadixCache { } fn lru_victim(&self, component: ComponentKind) -> Option { + self.ranked_victim(&|node| match component { + ComponentKind::ResidentKv => node + .components + .resident + .as_ref() + .filter(|entry| entry.active_refs == 0) + .map(|entry| (0, entry.last_used, entry.logical_bytes)), + ComponentKind::KvRecurrent => node + .components + .recurrent + .as_ref() + .filter(|entry| entry.active_refs == 0) + .map(|entry| (0, entry.last_used, entry.logical_bytes)), + }) + } + + /// The evictable node with the lowest `(retention, last_used)`, where + /// `candidate` yields `(retention, last_used, logical_bytes)` for nodes + /// holding an evictable entry. + fn ranked_victim(&self, candidate: &VictimCandidate<'_, R, E>) -> Option { let mut victim = None; for (namespace, root) in &self.roots { - collect_lru_victim(namespace, root, component, &mut Vec::new(), &mut victim); + collect_lru_victim(namespace, root, candidate, &mut Vec::new(), &mut victim); } victim } @@ -636,6 +696,7 @@ struct Victim { tokens: Vec, logical_bytes: u64, last_used: u64, + retention: u64, } fn validate_tokens(tokens: &[i32]) -> Result<()> { @@ -832,35 +893,24 @@ fn find_recurrent_path( None } +type VictimCandidate<'a, R, E> = dyn Fn(&RadixNode) -> Option<(u64, u64, u64)> + 'a; + fn collect_lru_victim( namespace: &str, node: &RadixNode, - component: ComponentKind, + candidate: &VictimCandidate<'_, R, E>, path: &mut Vec, victim: &mut Option, ) { let original_len = path.len(); path.extend_from_slice(&node.edge); - let candidate = match component { - ComponentKind::ResidentKv => node - .components - .resident - .as_ref() - .filter(|entry| entry.active_refs == 0) - .map(|entry| (entry.last_used, entry.logical_bytes)), - ComponentKind::KvRecurrent => node - .components - .recurrent - .as_ref() - .filter(|entry| entry.active_refs == 0) - .map(|entry| (entry.last_used, entry.logical_bytes)), - }; - if let Some((last_used, logical_bytes)) = candidate { + if let Some((retention, last_used, logical_bytes)) = candidate(node) { let replace = victim .as_ref() .map(|current| { - (last_used, namespace, path.as_slice()) + (retention, last_used, namespace, path.as_slice()) < ( + current.retention, current.last_used, current.namespace.as_str(), current.tokens.as_slice(), @@ -873,11 +923,12 @@ fn collect_lru_victim( tokens: path.clone(), logical_bytes, last_used, + retention, }); } } for child in node.children.values() { - collect_lru_victim(namespace, child, component, path, victim); + collect_lru_victim(namespace, child, candidate, path, victim); } path.truncate(original_len); } diff --git a/skippy/crates/skippy-commands/src/split.rs b/skippy/crates/skippy-commands/src/split.rs index f9b1252fd5..c8f22f7089 100644 --- a/skippy/crates/skippy-commands/src/split.rs +++ b/skippy/crates/skippy-commands/src/split.rs @@ -206,6 +206,7 @@ pub fn run(args: PlanSplitCommand) -> Result<()> { upstream: index.checked_sub(1).map(peer), downstream: (index + 1 < args.workers.len()).then(|| peer(index + 1)), admission: admission.clone(), + max_request_tier: None, }; configs.push(stage_load::admitted_stage_config(&load, None, names)?); } diff --git a/skippy/crates/skippy-inference-api/README.md b/skippy/crates/skippy-inference-api/README.md index edfbe2d9c6..0e4ab93e7c 100644 --- a/skippy/crates/skippy-inference-api/README.md +++ b/skippy/crates/skippy-inference-api/README.md @@ -183,6 +183,22 @@ perform exact string matching on requests. Resolution to a concrete Hugging Face revision, GGUF file, split-shard distribution, local runtime, or staged binary chain remains backend-owned. +## Request Tiers + +Every request carries an `InferenceRequestClass`: a tier (`local`, `trusted` +or `mesh`, highest first) and whether it is private. A client of a standalone +Skippy server can lower its own request with the `x-skippy-request-tier` +header and put it in the private cache partition with +`x-skippy-cache-partition` (any value counts as private); a request without +them is `local` and not private. The router puts the class on the +`InferenceRequestContext`; an embedding host that calls a backend directly +sets it there itself. A backend reads the class from the context and stamps it on the +`GenerationRequest` (`request_class`) for its hooks; request bodies never set +it. `InferenceRequestClass::cache_namespace` turns the class into the cache +namespace prefix (`tier::`) that keeps each tier's, and each side +of the private line's, cached prefixes apart; a `local`, non-private request +keeps the plain namespace. + ## Backend Responsibility Matrix | Area | Frontend responsibility | Backend responsibility | Status | diff --git a/skippy/crates/skippy-inference-api/src/anthropic/routes.rs b/skippy/crates/skippy-inference-api/src/anthropic/routes.rs index e86acb4004..ea9b6ac4ce 100644 --- a/skippy/crates/skippy-inference-api/src/anthropic/routes.rs +++ b/skippy/crates/skippy-inference-api/src/anthropic/routes.rs @@ -62,6 +62,7 @@ pub(crate) async fn messages( >, ) -> Result { let Json(request) = json_payload(payload)?; + let class = crate::InferenceRequestClass::from_headers(&headers); let header_session = agent_session_from_header(&state.config, &headers)?; let trusted_agent_session = header_session.is_some(); let mut generation_request = messages_request_to_generation(request)?; @@ -69,9 +70,23 @@ pub(crate) async fn messages( generation_request.validate()?; if generation_request.stream { - streaming_messages(&state, context, generation_request, trusted_agent_session).await + streaming_messages( + &state, + context, + generation_request, + class, + trusted_agent_session, + ) + .await } else { - non_streaming_messages(&state, context, generation_request, trusted_agent_session).await + non_streaming_messages( + &state, + context, + generation_request, + class, + trusted_agent_session, + ) + .await } } @@ -79,9 +94,10 @@ async fn non_streaming_messages( state: &FrontendState, context: InferenceLifecycleContext, request: crate::generation::GenerationRequest, + class: crate::InferenceRequestClass, trusted_agent_session: bool, ) -> Result { - let backend_context = request_context(context.request_id, trusted_agent_session, false); + let backend_context = request_context(context.request_id, class, trusted_agent_session, false); let response = call_backend_with_context( state.config.lifecycle_observer.clone(), &context, @@ -113,11 +129,12 @@ async fn streaming_messages( state: &FrontendState, context: InferenceLifecycleContext, request: crate::generation::GenerationRequest, + class: crate::InferenceRequestClass, trusted_agent_session: bool, ) -> Result { let model = request.model.clone(); let request_id: RequestId = context.request_id; - let backend_context = request_context(request_id, trusted_agent_session, true); + let backend_context = request_context(request_id, class, trusted_agent_session, true); let cancellation = backend_context.cancellation_token(); let stream = call_backend_with_context( state.config.lifecycle_observer.clone(), @@ -251,8 +268,9 @@ pub(crate) async fn messages_count_tokens( >, ) -> Result, AnthropicRejection> { let Json(request) = json_payload(payload)?; + let class = crate::InferenceRequestClass::from_headers(&headers); let session = agent_session_from_header(&state.config, &headers)?; - let backend_context = request_context(context.request_id, session.is_some(), false); + let backend_context = request_context(context.request_id, class, session.is_some(), false); let mut chat = messages_request_to_generation(request.into_messages())?; chat.set_agent_session(session); chat.validate()?; diff --git a/skippy/crates/skippy-inference-api/src/anthropic/translate.rs b/skippy/crates/skippy-inference-api/src/anthropic/translate.rs index 4a33a22074..3dcb9a5f84 100644 --- a/skippy/crates/skippy-inference-api/src/anthropic/translate.rs +++ b/skippy/crates/skippy-inference-api/src/anthropic/translate.rs @@ -177,6 +177,7 @@ pub fn messages_request_to_generation( extra: BTreeMap::new(), }), extra: request.extra, + request_class: Default::default(), }) } diff --git a/skippy/crates/skippy-inference-api/src/backend.rs b/skippy/crates/skippy-inference-api/src/backend.rs index 7eb213f4b6..3acbf0b141 100644 --- a/skippy/crates/skippy-inference-api/src/backend.rs +++ b/skippy/crates/skippy-inference-api/src/backend.rs @@ -75,6 +75,7 @@ pub struct InferenceRequestContext { trusted_agent_session: bool, execution_scope: Option, execution_lease: Option>, + request_class: crate::InferenceRequestClass, } impl InferenceRequestContext { @@ -133,6 +134,18 @@ impl InferenceRequestContext { self.execution_scope } + /// Set the tier and cache partition a trusted front end assigned to this + /// request. Without it a request is `local` and unpartitioned. + pub fn with_request_class(mut self, class: crate::InferenceRequestClass) -> Self { + self.request_class = class; + self + } + + /// Return the request's tier and cache partition. + pub fn request_class(&self) -> crate::InferenceRequestClass { + self.request_class + } + /// Return the frontend request identifier when the caller supplied one. pub fn request_id(&self) -> Option { self.request_id @@ -172,6 +185,7 @@ impl Default for InferenceRequestContext { trusted_agent_session: false, execution_scope: None, execution_lease: None, + request_class: crate::InferenceRequestClass::default(), } } } @@ -240,6 +254,16 @@ pub trait InferenceBackend: Send + Sync + 'static { )) } + /// Serve System One with the request's tier and isolation. The default + /// ignores the context for backends without tiered caches. + async fn system_one_with_context( + &self, + request: SystemOneRequest, + _context: InferenceRequestContext, + ) -> InferenceResult { + self.system_one(request).await + } + /// Embed text or token batches. The default rejects unsupported backends. async fn embeddings( &self, diff --git a/skippy/crates/skippy-inference-api/src/chat/generation.rs b/skippy/crates/skippy-inference-api/src/chat/generation.rs index b765066b3c..26db6c4775 100644 --- a/skippy/crates/skippy-inference-api/src/chat/generation.rs +++ b/skippy/crates/skippy-inference-api/src/chat/generation.rs @@ -34,6 +34,8 @@ impl From for GenerationRequest { prompt_cache_retention: value.prompt_cache_retention, stream_options: value.stream_options, extra: value.extra, + // The body never names its class; the backend sets it from context. + request_class: Default::default(), } } } diff --git a/skippy/crates/skippy-inference-api/src/chat/request_view.rs b/skippy/crates/skippy-inference-api/src/chat/request_view.rs index 2b474a77b2..e498da8525 100644 --- a/skippy/crates/skippy-inference-api/src/chat/request_view.rs +++ b/skippy/crates/skippy-inference-api/src/chat/request_view.rs @@ -39,6 +39,8 @@ impl Serialize for ChatCompletionRequestRef<'_> { prompt_cache_retention, stream_options, extra, + // Served-in metadata, not part of the request a client sent. + request_class: _, } = self.0; let mut map = serializer.serialize_map(None)?; map.serialize_entry("model", model)?; diff --git a/skippy/crates/skippy-inference-api/src/generation/request.rs b/skippy/crates/skippy-inference-api/src/generation/request.rs index dffafccbd2..85c79b8d9c 100644 --- a/skippy/crates/skippy-inference-api/src/generation/request.rs +++ b/skippy/crates/skippy-inference-api/src/generation/request.rs @@ -52,6 +52,11 @@ pub struct GenerationRequest { pub stream_options: Option, pub extra: BTreeMap, + + /// The tier and cache partition the request is served in. A backend sets + /// it from the request context when it accepts the request, so hooks see + /// it; no request body sets it. + pub request_class: crate::InferenceRequestClass, } impl GenerationRequest { diff --git a/skippy/crates/skippy-inference-api/src/guardrails/compact.rs b/skippy/crates/skippy-inference-api/src/guardrails/compact.rs index 7a6aaaec98..8926d3e6b7 100644 --- a/skippy/crates/skippy-inference-api/src/guardrails/compact.rs +++ b/skippy/crates/skippy-inference-api/src/guardrails/compact.rs @@ -78,6 +78,14 @@ impl InferenceBackend for CompactingInferenceBackend { self.backend.system_one(request).await } + async fn system_one_with_context( + &self, + request: SystemOneRequest, + context: InferenceRequestContext, + ) -> InferenceResult { + self.backend.system_one_with_context(request, context).await + } + async fn chat_completion( &self, request: GenerationRequest, diff --git a/skippy/crates/skippy-inference-api/src/guardrails/mod.rs b/skippy/crates/skippy-inference-api/src/guardrails/mod.rs index 0e644575af..7ebf035347 100644 --- a/skippy/crates/skippy-inference-api/src/guardrails/mod.rs +++ b/skippy/crates/skippy-inference-api/src/guardrails/mod.rs @@ -322,6 +322,14 @@ impl InferenceBackend for GuardedInferenceBackend { self.backend.system_one(request).await } + async fn system_one_with_context( + &self, + request: SystemOneRequest, + context: InferenceRequestContext, + ) -> InferenceResult { + self.backend.system_one_with_context(request, context).await + } + async fn chat_completion( &self, request: GenerationRequest, diff --git a/skippy/crates/skippy-inference-api/src/hooks.rs b/skippy/crates/skippy-inference-api/src/hooks.rs index 100500de82..34a3070351 100644 --- a/skippy/crates/skippy-inference-api/src/hooks.rs +++ b/skippy/crates/skippy-inference-api/src/hooks.rs @@ -428,6 +428,14 @@ impl InferenceBackend for HookedInferenceBackend { self.backend.system_one(request).await } + async fn system_one_with_context( + &self, + request: SystemOneRequest, + context: InferenceRequestContext, + ) -> InferenceResult { + self.backend.system_one_with_context(request, context).await + } + async fn chat_completion( &self, request: GenerationRequest, @@ -441,6 +449,7 @@ impl InferenceBackend for HookedInferenceBackend { mut request: GenerationRequest, context: InferenceRequestContext, ) -> InferenceResult { + request.request_class = context.request_class(); let exchange_id = uuid::Uuid::new_v4().to_string(); // Armed immediately after minting the exchange id — before // `before_chat_completion` and `on_effective_chat_completion` run — @@ -539,6 +548,7 @@ impl InferenceBackend for HookedInferenceBackend { mut request: GenerationRequest, context: InferenceRequestContext, ) -> InferenceResult { + request.request_class = context.request_class(); let exchange_id = uuid::Uuid::new_v4().to_string(); context.publish_exchange_id(exchange_id.clone()); // Same admission-time arming as `chat_completion_with_context` above diff --git a/skippy/crates/skippy-inference-api/src/lib.rs b/skippy/crates/skippy-inference-api/src/lib.rs index 8a36c67644..a5fdae1238 100644 --- a/skippy/crates/skippy-inference-api/src/lib.rs +++ b/skippy/crates/skippy-inference-api/src/lib.rs @@ -18,6 +18,7 @@ pub mod lifecycle; pub mod models; pub mod realtime; mod request_lifecycle; +mod request_tier; pub mod rerank; pub mod responses; pub mod router; @@ -80,6 +81,10 @@ pub use lifecycle::{ request_id_response_header, }; pub use models::{ModelId, ModelIdError, ModelObject, ModelsResponse}; +pub use request_tier::{ + CACHE_PARTITION_HEADER, InferenceRequestClass, InferenceRequestTier, PRIVATE_CACHE_PARTITION, + REQUEST_TIER_HEADER, +}; pub use rerank::{RerankDocument, RerankRequest, RerankResponse, RerankResult}; pub use responses::{ NormalizationOutcome, ResponseAdapterMode, ResponsesRequest, StreamUsage, diff --git a/skippy/crates/skippy-inference-api/src/request_tier.rs b/skippy/crates/skippy-inference-api/src/request_tier.rs new file mode 100644 index 0000000000..2f5bf7158d --- /dev/null +++ b/skippy/crates/skippy-inference-api/src/request_tier.rs @@ -0,0 +1,306 @@ +//! Request tiers: whom a request is served for. The tier orders admission and +//! eviction, and each tier (and the private partition) gets its own caches. + +use axum::http::HeaderMap; + +/// Header a trusted front end sets on the loopback hop to name the tier. +/// +/// Skippy reads every value of this header and keeps the lowest one, so a +/// header can only lower a request's tier. A request without it is `local`: +/// whoever reaches the server directly is on this machine. +pub const REQUEST_TIER_HEADER: &str = "x-skippy-request-tier"; + +/// Header that moves a request into the private cache partition. +/// +/// The only accepted value is `private`. A private request never reuses, or +/// leaves behind, cache entries visible to non-private requests of its tier. +pub const CACHE_PARTITION_HEADER: &str = "x-skippy-cache-partition"; + +/// The value of [`CACHE_PARTITION_HEADER`] that selects the private partition. +pub const PRIVATE_CACHE_PARTITION: &str = "private"; + +/// Whom a request is served for, from lowest to highest precedence. +#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub enum InferenceRequestTier { + /// Anyone else on the mesh. + Mesh, + /// A node whose owner this node's operator trusts. + Trusted, + /// This machine, or a node of this node's own owner. + #[default] + Local, +} + +impl InferenceRequestTier { + /// Every tier, from lowest to highest. + pub const ALL: [Self; 3] = [Self::Mesh, Self::Trusted, Self::Local]; + + /// The lowercase name used in headers, config and metrics. + pub const fn as_str(self) -> &'static str { + match self { + Self::Mesh => "mesh", + Self::Trusted => "trusted", + Self::Local => "local", + } + } + + /// Parse a tier name, ignoring case and surrounding whitespace. + pub fn parse(value: &str) -> Option { + let value = value.trim(); + Self::ALL + .into_iter() + .find(|tier| tier.as_str().eq_ignore_ascii_case(value)) + } + + /// Scheduling priority: a higher value is admitted first. + pub const fn priority(self) -> u64 { + match self { + Self::Mesh => 0, + Self::Trusted => 1, + Self::Local => 2, + } + } + + /// Stable one-byte code for wire headers and cache identities. + pub const fn code(self) -> u8 { + match self { + Self::Mesh => 0, + Self::Trusted => 1, + Self::Local => 2, + } + } + + /// Decode [`Self::code`]; unknown codes are rejected. + pub const fn from_code(code: u8) -> Option { + match code { + 0 => Some(Self::Mesh), + 1 => Some(Self::Trusted), + 2 => Some(Self::Local), + _ => None, + } + } + + /// The lowest tier among the values of `header`, starting from `Local`. + /// + /// A value that is not a tier name counts as `Mesh`, so a malformed header + /// fails low rather than being ignored. + pub fn from_headers(headers: &HeaderMap, header: &str) -> Self { + headers + .get_all(header) + .iter() + .flat_map(|value| { + value + .to_str() + .map(|value| value.split(',').map(Self::parse).collect::>()) + .unwrap_or_else(|_| vec![None]) + }) + .map(|tier| tier.unwrap_or(Self::Mesh)) + .fold(Self::Local, Self::min) + } +} + +impl std::fmt::Display for InferenceRequestTier { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.as_str()) + } +} + +/// A request's tier plus whether it uses the private cache partition. +#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] +pub struct InferenceRequestClass { + tier: InferenceRequestTier, + private: bool, +} + +impl InferenceRequestClass { + pub const fn new(tier: InferenceRequestTier, private: bool) -> Self { + Self { tier, private } + } + + /// Read the class a trusted front end stamped on an HTTP request. + pub fn from_headers(headers: &HeaderMap) -> Self { + // `private` is the only partition the header names, so any value, even + // an unreadable one, keeps the request out of the shared partition. + let private = headers.contains_key(CACHE_PARTITION_HEADER); + Self::new( + InferenceRequestTier::from_headers(headers, REQUEST_TIER_HEADER), + private, + ) + } + + pub const fn tier(self) -> InferenceRequestTier { + self.tier + } + + pub const fn is_private(self) -> bool { + self.private + } + + /// Lower the tier to `tier` if that is lower; never raise it. + pub fn limited_to(self, tier: InferenceRequestTier) -> Self { + Self::new(self.tier.min(tier), self.private) + } + + /// The cache partition label, or `None` for the default partition + /// (`local`, not private), which keeps cache keys unchanged for + /// standalone Skippy. + pub fn cache_partition(self) -> Option { + match (self.tier, self.private) { + (InferenceRequestTier::Local, false) => None, + (tier, false) => Some(tier.as_str().to_owned()), + (tier, true) => Some(format!("{}-{PRIVATE_CACHE_PARTITION}", tier.as_str())), + } + } + + /// Partition a cache namespace by this class. The default class returns + /// `namespace` unchanged; any other class prefixes it with + /// `tier::`, which no unpartitioned namespace starts with. + pub fn cache_namespace(self, namespace: Option) -> Option { + match self.cache_partition() { + Some(partition) => Some(format!( + "{CACHE_NAMESPACE_TIER_PREFIX}{partition}:{}", + namespace.unwrap_or_default() + )), + None => namespace, + } + } + + /// Recover the class from a namespace built by [`Self::cache_namespace`]. + /// An unpartitioned namespace is the default class; an unrecognized + /// partition is `mesh`, so a malformed one is evicted first. + pub fn from_cache_namespace(namespace: Option<&str>) -> Self { + let Some(rest) = namespace.and_then(|ns| ns.strip_prefix(CACHE_NAMESPACE_TIER_PREFIX)) + else { + return Self::default(); + }; + let partition = rest + .split_once(':') + .map_or(rest, |(partition, _)| partition); + let (tier, private) = match partition.strip_suffix(PRIVATE_CACHE_PARTITION) { + Some(tier) => (tier.strip_suffix('-').unwrap_or(tier), true), + None => (partition, false), + }; + Self::new( + InferenceRequestTier::parse(tier).unwrap_or(InferenceRequestTier::Mesh), + private, + ) + } +} + +/// Prefix that marks a cache namespace partitioned by request class. +const CACHE_NAMESPACE_TIER_PREFIX: &str = "tier:"; + +#[cfg(test)] +mod tests { + use super::*; + use axum::http::HeaderValue; + + fn headers(pairs: &[(&'static str, &'static str)]) -> HeaderMap { + let mut headers = HeaderMap::new(); + for (name, value) in pairs { + headers.append(*name, HeaderValue::from_static(value)); + } + headers + } + + #[test] + fn missing_header_is_local() { + assert_eq!( + InferenceRequestClass::from_headers(&HeaderMap::new()), + InferenceRequestClass::default() + ); + assert_eq!( + InferenceRequestClass::default().tier(), + InferenceRequestTier::Local + ); + } + + #[test] + fn repeated_values_keep_the_lowest_tier() { + let headers = headers(&[ + (REQUEST_TIER_HEADER, "local"), + (REQUEST_TIER_HEADER, "Trusted, local"), + ]); + assert_eq!( + InferenceRequestTier::from_headers(&headers, REQUEST_TIER_HEADER), + InferenceRequestTier::Trusted + ); + } + + #[test] + fn unknown_values_fail_low() { + let headers = headers(&[(REQUEST_TIER_HEADER, "owner")]); + assert_eq!( + InferenceRequestTier::from_headers(&headers, REQUEST_TIER_HEADER), + InferenceRequestTier::Mesh + ); + } + + #[test] + fn limiting_never_raises() { + let class = InferenceRequestClass::new(InferenceRequestTier::Trusted, false); + assert_eq!( + class.limited_to(InferenceRequestTier::Local).tier(), + InferenceRequestTier::Trusted + ); + assert_eq!( + class.limited_to(InferenceRequestTier::Mesh).tier(), + InferenceRequestTier::Mesh + ); + } + + #[test] + fn partitions_are_distinct_and_default_is_unpartitioned() { + let partitions = InferenceRequestTier::ALL + .into_iter() + .flat_map(|tier| [false, true].map(|private| InferenceRequestClass::new(tier, private))) + .map(InferenceRequestClass::cache_partition) + .collect::>(); + assert_eq!(partitions.iter().filter(|p| p.is_none()).count(), 1); + let named = partitions + .into_iter() + .flatten() + .collect::>(); + assert_eq!(named.len(), 5); + assert!( + InferenceRequestClass::from_headers(&headers(&[(CACHE_PARTITION_HEADER, "private")])) + .is_private() + ); + assert!( + InferenceRequestClass::from_headers(&headers(&[( + CACHE_PARTITION_HEADER, + "private, private" + )])) + .is_private() + ); + assert!(!InferenceRequestClass::from_headers(&HeaderMap::new()).is_private()); + } + + #[test] + fn cache_namespaces_round_trip_every_class() { + for tier in InferenceRequestTier::ALL { + for private in [false, true] { + let class = InferenceRequestClass::new(tier, private); + for inner in [None, Some("openai:prompt_cache_key:tier:local".to_owned())] { + let namespace = class.cache_namespace(inner); + assert_eq!( + InferenceRequestClass::from_cache_namespace(namespace.as_deref()), + class + ); + } + } + } + assert_eq!( + InferenceRequestClass::from_cache_namespace(Some("tier:owner:x")).tier(), + InferenceRequestTier::Mesh + ); + } + + #[test] + fn codes_round_trip() { + for tier in InferenceRequestTier::ALL { + assert_eq!(InferenceRequestTier::from_code(tier.code()), Some(tier)); + } + assert_eq!(InferenceRequestTier::from_code(3), None); + } +} diff --git a/skippy/crates/skippy-inference-api/src/router.rs b/skippy/crates/skippy-inference-api/src/router.rs index 1bccee75a9..8be1476ed6 100644 --- a/skippy/crates/skippy-inference-api/src/router.rs +++ b/skippy/crates/skippy-inference-api/src/router.rs @@ -382,6 +382,7 @@ async fn models( async fn system_one( State(state): State, Extension(context): Extension, + headers: HeaderMap, payload: Result, JsonRejection>, ) -> Result, InferenceError> { let Json(request) = json_payload(payload)?; @@ -391,7 +392,9 @@ async fn system_one( InferenceBackendOperation::SystemOne, "system_one", state.config.backend_timeout, - state.backend.system_one(request), + state + .backend + .system_one_with_context(request, plain_request_context(context.request_id, &headers)), ) .await?; state.response_completed( @@ -405,6 +408,7 @@ async fn system_one( async fn decisions( State(state): State, Extension(context): Extension, + headers: HeaderMap, payload: Result, JsonRejection>, ) -> Result, InferenceError> { let Json(request) = json_payload(payload)?; @@ -414,7 +418,10 @@ async fn decisions( InferenceBackendOperation::SystemOne, "decisions", state.config.backend_timeout, - state.backend.system_one(request.to_system_one()?), + state.backend.system_one_with_context( + request.to_system_one()?, + plain_request_context(context.request_id, &headers), + ), ) .await?; let usage = response.usage; @@ -431,11 +438,12 @@ async fn decisions( async fn embeddings( State(state): State, Extension(context): Extension, + headers: HeaderMap, payload: Result, JsonRejection>, ) -> Result { let Json(request) = json_payload(payload)?; request.validate()?; - let backend_context = InferenceRequestContext::with_request_id(context.request_id); + let backend_context = plain_request_context(context.request_id, &headers); let response: EmbeddingResponse = call_backend_with_context( state.config.lifecycle_observer.clone(), &context, @@ -459,11 +467,12 @@ async fn embeddings( async fn rerank( State(state): State, Extension(context): Extension, + headers: HeaderMap, payload: Result, JsonRejection>, ) -> Result { let Json(request) = json_payload(payload)?; request.validate()?; - let backend_context = InferenceRequestContext::with_request_id(context.request_id); + let backend_context = plain_request_context(context.request_id, &headers); let response: RerankResponse = call_backend_with_context( state.config.lifecycle_observer.clone(), &context, @@ -483,11 +492,12 @@ async fn rerank( async fn audio_speech( State(state): State, Extension(context): Extension, + headers: HeaderMap, payload: Result, JsonRejection>, ) -> Result { let Json(request) = json_payload(payload)?; request.validate()?; - let backend_context = InferenceRequestContext::with_request_id(context.request_id); + let backend_context = plain_request_context(context.request_id, &headers); let response = call_backend_with_context( state.config.lifecycle_observer.clone(), &context, @@ -516,18 +526,34 @@ fn audio_response(audio: AudioResponse) -> Result { async fn audio_transcriptions( State(state): State, Extension(context): Extension, + headers: HeaderMap, multipart: Result, ) -> Result { - audio_text_request(state, context, multipart_payload(multipart)?, false).await + audio_text_request( + state, + context, + &headers, + multipart_payload(multipart)?, + false, + ) + .await } /// Select English translation without changing the multipart upload contract. async fn audio_translations( State(state): State, Extension(context): Extension, + headers: HeaderMap, multipart: Result, ) -> Result { - audio_text_request(state, context, multipart_payload(multipart)?, true).await + audio_text_request( + state, + context, + &headers, + multipart_payload(multipart)?, + true, + ) + .await } /// Convert extractor rejection into the frontend's structured invalid-request error. @@ -552,13 +578,14 @@ fn multipart_error(error: MultipartError, field: &str) -> InferenceError { async fn audio_text_request( state: FrontendState, context: InferenceLifecycleContext, + headers: &HeaderMap, multipart: Multipart, translate: bool, ) -> Result { let request = parse_audio_multipart(multipart).await?; request.validate()?; let response_format = request.response_format.clone(); - let backend_context = InferenceRequestContext::with_request_id(context.request_id); + let backend_context = plain_request_context(context.request_id, headers); let operation = if translate { InferenceBackendOperation::AudioTranslation } else { @@ -630,13 +657,15 @@ async fn completions( payload: Result, JsonRejection>, ) -> Result { let Json(mut request) = json_payload(payload)?; + let class = crate::InferenceRequestClass::from_headers(&headers); let header_session = agent_session_from_header(&state.config, &headers)?; let trusted_agent_session = header_session.is_some(); request.set_agent_session(header_session); request.validate()?; if request.stream { let include_usage = request.include_usage(); - let backend_context = request_context(context.request_id, trusted_agent_session, true); + let backend_context = + request_context(context.request_id, class, trusted_agent_session, true); let cancellation = backend_context.cancellation_token(); let stream = call_backend_with_context( state.config.lifecycle_observer.clone(), @@ -680,7 +709,8 @@ async fn completions( })); Ok(sse_response(events, cancellation, lifecycle)) } else { - let backend_context = request_context(context.request_id, trusted_agent_session, false); + let backend_context = + request_context(context.request_id, class, trusted_agent_session, false); let response = call_backend_with_context( state.config.lifecycle_observer.clone(), &context, @@ -787,12 +817,24 @@ fn resolve_agent_session( } } +/// A backend context for routes without agent sessions or stream usage, +/// carrying the tier and cache partition the front end stamped on it. +pub(crate) fn plain_request_context( + request_id: RequestId, + headers: &HeaderMap, +) -> InferenceRequestContext { + InferenceRequestContext::with_request_id(request_id) + .with_request_class(crate::InferenceRequestClass::from_headers(headers)) +} + pub(crate) fn request_context( request_id: RequestId, + class: crate::InferenceRequestClass, trusted_agent_session: bool, observe_stream_usage: bool, ) -> InferenceRequestContext { - let mut context = InferenceRequestContext::with_request_id(request_id); + let mut context = + InferenceRequestContext::with_request_id(request_id).with_request_class(class); if trusted_agent_session { context = context.with_trusted_agent_session(); } diff --git a/skippy/crates/skippy-inference-api/src/router/generation.rs b/skippy/crates/skippy-inference-api/src/router/generation.rs index d9500a0162..2a01c2a2f3 100644 --- a/skippy/crates/skippy-inference-api/src/router/generation.rs +++ b/skippy/crates/skippy-inference-api/src/router/generation.rs @@ -10,6 +10,7 @@ pub(super) async fn chat_completions( ) -> Result { let Json(request) = json_payload(payload)?; let mut request = GenerationRequest::from(request); + let class = crate::InferenceRequestClass::from_headers(&headers); let header_session = agent_session_from_header(&state.config, &headers)?; let trusted_agent_session = header_session.is_some(); request.set_agent_session(header_session); @@ -17,7 +18,8 @@ pub(super) async fn chat_completions( if request.stream { let include_usage = request.include_usage(); let model = request.model.clone(); - let backend_context = request_context(context.request_id, trusted_agent_session, true); + let backend_context = + request_context(context.request_id, class, trusted_agent_session, true); let cancellation = backend_context.cancellation_token(); let stream = call_backend_with_context( state.config.lifecycle_observer.clone(), @@ -72,7 +74,8 @@ pub(super) async fn chat_completions( } Ok(response) } else { - let backend_context = request_context(context.request_id, trusted_agent_session, false); + let backend_context = + request_context(context.request_id, class, trusted_agent_session, false); let response = call_backend_with_context( state.config.lifecycle_observer.clone(), &context, @@ -120,6 +123,7 @@ pub(super) async fn responses( let request: ChatCompletionRequest = serde_json::from_value(value).map_err(|error| { InferenceError::invalid_request(format!("invalid Responses request: {error}")) })?; + let class = crate::InferenceRequestClass::from_headers(&headers); let header_session = agent_session_from_header(&state.config, &headers)?; let trusted_agent_session = header_session.is_some(); let mut request = GenerationRequest::from(request); @@ -131,9 +135,9 @@ pub(super) async fn responses( request.validate()?; match normalization.response_adapter { ResponseAdapterMode::OpenAiResponsesStream => { - stream_responses(&state, &context, request, trusted_agent_session).await + stream_responses(&state, &context, request, class, trusted_agent_session).await } - _ => non_streaming_responses(&state, &context, request, trusted_agent_session).await, + _ => non_streaming_responses(&state, &context, request, class, trusted_agent_session).await, } } @@ -141,10 +145,11 @@ async fn stream_responses( state: &FrontendState, context: &InferenceLifecycleContext, request: GenerationRequest, + class: crate::InferenceRequestClass, trusted_agent_session: bool, ) -> Result { let include_usage = request.include_usage(); - let backend_context = request_context(context.request_id, trusted_agent_session, true); + let backend_context = request_context(context.request_id, class, trusted_agent_session, true); let cancellation = backend_context.cancellation_token(); let state_machine = Arc::new(Mutex::new(ResponseSseState::new(request.model.clone()))); let stream = call_backend_with_context( @@ -195,9 +200,10 @@ async fn non_streaming_responses( state: &FrontendState, context: &InferenceLifecycleContext, request: GenerationRequest, + class: crate::InferenceRequestClass, trusted_agent_session: bool, ) -> Result { - let backend_context = request_context(context.request_id, trusted_agent_session, false); + let backend_context = request_context(context.request_id, class, trusted_agent_session, false); let response = call_backend_with_context( state.config.lifecycle_observer.clone(), context, diff --git a/skippy/crates/skippy-protocol/README.md b/skippy/crates/skippy-protocol/README.md index c78f349dce..04fbf1de65 100644 --- a/skippy/crates/skippy-protocol/README.md +++ b/skippy/crates/skippy-protocol/README.md @@ -62,10 +62,17 @@ DFlash status lists the encodings it reads (`bf16`, `q8`, `q4`), and the DFlash plan sent to every earlier stage names the one they send. A final stage that lists none attaches no split DFlash. -Current generation 16 raises the stage frame budget from 8 MiB to 64 MiB, so a +Generation 16 raised the stage frame budget from 8 MiB to 64 MiB, so a prefill chunk of a wide boundary crosses as one frame; a chunk whose output -still exceeds the budget is sent as consecutive prefill frames. All -participants must advertise `stage-generation-16`; older peers fail closed. +still exceeds the budget is sent as consecutive prefill frames. + +Current generation 17 (wire header version 18) carries each request's tier +and private cache partition in the state header flags of every +cache-bearing message (bits 17-18: how many tiers below `local`; bit 19: +private). A stage lowers that claim to the highest tier its host assigned +the stage at load (`StageConfig.max_request_tier`), then partitions and +evicts its caches by the result. All participants must advertise +`stage-generation-17`; older peers fail closed. Admission requires mesh-subprotocol control, list-valued status responses, strict local-content identity, canonical stage-admission descriptors, and stale diff --git a/skippy/crates/skippy-protocol/src/binary/types.rs b/skippy/crates/skippy-protocol/src/binary/types.rs index f5d323b87e..834c184559 100644 --- a/skippy/crates/skippy-protocol/src/binary/types.rs +++ b/skippy/crates/skippy-protocol/src/binary/types.rs @@ -5,8 +5,9 @@ use crate::StageActivationCodec; use super::invalid_data; // v17 adds unsampled prefill readouts and bounded selected-score replies. +// v18 adds the request tier and private-partition flags on stage messages. // Stage peers must be upgraded together; the Mesh gossip envelope stays additive. -pub const STAGE_STATE_VERSION: i32 = 17; +pub const STAGE_STATE_VERSION: i32 = 18; pub const MAX_STAGE_LOGIT_BIAS: usize = 256; pub const MAX_STAGE_SAMPLERS: usize = 16; pub const MAX_STAGE_DRY_SEQUENCE_BREAKERS: usize = 8; @@ -219,6 +220,14 @@ pub mod state_flags { /// attention window. Stages forward no DFlash feature rows for them, and /// the draft does not ingest them; its context starts after them. pub const SPLIT_DFLASH_UNATTENDED_ROWS: i32 = 1 << 16; + /// Bits 17..=18: how many tiers below `local` the request is served at + /// (0 local, 1 trusted, 2 mesh; 3 is read as mesh). A stage caps this at + /// its own classification of the coordinator, partitions its caches by + /// it, and evicts lower tiers first. + pub const REQUEST_TIER_DEMOTION_SHIFT: u32 = 17; + pub const REQUEST_TIER_DEMOTION_MASK: i32 = 0x3 << REQUEST_TIER_DEMOTION_SHIFT; + /// The request uses the private cache partition of its tier. + pub const PRIVATE_CACHE_PARTITION: i32 = 1 << 19; } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -424,6 +433,34 @@ impl StageStateHeader { | state_flags::NATIVE_MTP_DRAFT_TOKENS_SET; } + /// How many tiers below `local` the request is served at: 0 local, + /// 1 trusted, 2 mesh. The unused value 3 reads as mesh. + pub fn request_tier_demotion(self) -> u8 { + let value = (self.flags & state_flags::REQUEST_TIER_DEMOTION_MASK) + >> state_flags::REQUEST_TIER_DEMOTION_SHIFT; + (value as u8).min(2) + } + + /// Stamp the request tier as tiers below `local`, saturating at mesh. + pub fn set_request_tier_demotion(&mut self, demotion: u8) { + let value = i32::from(demotion.min(2)); + self.flags = (self.flags & !state_flags::REQUEST_TIER_DEMOTION_MASK) + | (value << state_flags::REQUEST_TIER_DEMOTION_SHIFT); + } + + /// Whether the request uses its tier's private cache partition. + pub fn private_cache_partition(self) -> bool { + self.flags & state_flags::PRIVATE_CACHE_PARTITION != 0 + } + + pub fn set_private_cache_partition(&mut self, private: bool) { + if private { + self.flags |= state_flags::PRIVATE_CACHE_PARTITION; + } else { + self.flags &= !state_flags::PRIVATE_CACHE_PARTITION; + } + } + /// Whether the sender accepts drafts that follow a rejected window's correction. pub fn accepts_native_mtp_draft_after_correction(self) -> bool { self.flags & state_flags::NATIVE_MTP_DRAFT_AFTER_CORRECTION != 0 diff --git a/skippy/crates/skippy-protocol/src/config.rs b/skippy/crates/skippy-protocol/src/config.rs index b7dff697dc..67f4cc3924 100644 --- a/skippy/crates/skippy-protocol/src/config.rs +++ b/skippy/crates/skippy-protocol/src/config.rs @@ -542,6 +542,12 @@ pub struct StageConfig { pub upstream: Option, #[serde(default)] pub downstream: Option, + /// The highest request tier (`local`, `trusted` or `mesh`) this stage + /// serves. The host sets it from its own classification of the node that + /// loaded the stage; a wire claim above it is lowered to it. `None` means + /// `local`: the stage trusts the tier its coordinator stamps. + #[serde(default)] + pub max_request_tier: Option, } impl StageConfig { diff --git a/skippy/crates/skippy-protocol/src/lib.rs b/skippy/crates/skippy-protocol/src/lib.rs index dc6db840ac..93a2ebc33d 100644 --- a/skippy/crates/skippy-protocol/src/lib.rs +++ b/skippy/crates/skippy-protocol/src/lib.rs @@ -43,7 +43,7 @@ pub use validation::{ STAGE_SUBPROTOCOL_FEATURE_LOCAL_GGUF_CONTENT_ID_V1, STAGE_SUBPROTOCOL_FEATURE_PERSISTENT_LANE_MARKER, STAGE_SUBPROTOCOL_FEATURE_STAGE_CONTROL, STAGE_SUBPROTOCOL_FEATURE_STAGE_GENERATION, - STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V16, STAGE_SUBPROTOCOL_FEATURE_STATUS_LIST, + STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V17, STAGE_SUBPROTOCOL_FEATURE_STATUS_LIST, STAGE_SUBPROTOCOL_MAJOR, STAGE_SUBPROTOCOL_NAME, StageFrameError, validate_stage_admission_descriptor, validate_stage_artifact_transfer_request, validate_stage_artifact_transfer_response, validate_stage_control_request, @@ -304,7 +304,7 @@ mod tests { ); } use super::{ - STAGE_PROTOCOL_GENERATION, STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V16, + STAGE_PROTOCOL_GENERATION, STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V17, StageFrameError, validate_stage_admission_descriptor, validate_stage_artifact_transfer_request, validate_stage_artifact_transfer_response, validate_stage_control_request, validate_stage_control_response, @@ -315,7 +315,7 @@ mod tests { #[test] fn stage_protocol_generation_feature_names_current_generation() { assert_eq!( - STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V16, + STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V17, format!("stage-generation-{STAGE_PROTOCOL_GENERATION}") ); } diff --git a/skippy/crates/skippy-protocol/src/validation.rs b/skippy/crates/skippy-protocol/src/validation.rs index 11cb6132f8..638c403270 100644 --- a/skippy/crates/skippy-protocol/src/validation.rs +++ b/skippy/crates/skippy-protocol/src/validation.rs @@ -10,13 +10,13 @@ pub const STAGE_SUBPROTOCOL_NAME: &str = "skippy-stage"; pub const STAGE_SUBPROTOCOL_MAJOR: u32 = 2; pub const STAGE_SUBPROTOCOL_FEATURE_STAGE_CONTROL: &str = "stage-control"; pub const STAGE_SUBPROTOCOL_FEATURE_PERSISTENT_LANE_MARKER: &str = "persistent-lane-marker"; -pub const STAGE_PROTOCOL_GENERATION: u32 = 16; +pub const STAGE_PROTOCOL_GENERATION: u32 = 17; /// Generation-scoped stage capability. A peer can advertise `stage-control` /// while still rejecting current-generation frames, so split planning gates on /// this exact token before sending current-generation control requests. -pub const STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V16: &str = "stage-generation-16"; +pub const STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V17: &str = "stage-generation-17"; pub const STAGE_SUBPROTOCOL_FEATURE_STAGE_GENERATION: &str = - STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V16; + STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V17; pub const STAGE_SUBPROTOCOL_FEATURE_ARTIFACT_TRANSFER: &str = "artifact-transfer"; pub const STAGE_SUBPROTOCOL_FEATURE_STATUS_LIST: &str = "status-list"; pub const STAGE_SUBPROTOCOL_FEATURE_LOCAL_GGUF_CONTENT_ID_V1: &str = "local-gguf-content-id-v1"; diff --git a/skippy/crates/skippy-scheduler/README.md b/skippy/crates/skippy-scheduler/README.md index abf55cf5b5..080a7ae378 100644 --- a/skippy/crates/skippy-scheduler/README.md +++ b/skippy/crates/skippy-scheduler/README.md @@ -52,6 +52,17 @@ enqueue-time score and is emitted as stale-fallback telemetry. New arrivals may re-rank the remaining queue. This request radix is scheduling-only and never changes unified-cache recency. +Explicit priority is the request tier when serving (`local` above `trusted` +above `mesh`). Each time `PRIORITY_AGING_TURNS` higher-priority candidates +are selected ahead of a waiting candidate, it ranks one level higher, but +only up to a level another candidate holds, so the order stays total and +age never reorders candidates of one priority. Callers count those +selections with `PriorityPassovers` and pass each candidate's +`passed_over`. For +eviction, `EvictableCacheEntry::retention_priority` ranks ahead of recompute +value: serving sets it from the tier that stored the entry, so the lowest +tier is evicted first. + ## License Licensed under Apache-2.0. diff --git a/skippy/crates/skippy-scheduler/src/cache_policy.rs b/skippy/crates/skippy-scheduler/src/cache_policy.rs index b9cd3fa960..8a306e4628 100644 --- a/skippy/crates/skippy-scheduler/src/cache_policy.rs +++ b/skippy/crates/skippy-scheduler/src/cache_policy.rs @@ -56,6 +56,42 @@ impl CacheAffinity { } } +/// Times a candidate is passed over to gain one priority level. Priority is +/// strict among fresh arrivals, but a lower-priority candidate climbs one level +/// each time this many higher-priority candidates are selected ahead of it, so +/// no level starves. Waiting behind its own or a lower level does not count: +/// a busy lower level never catches up with a higher one by queueing alone. +pub const PRIORITY_AGING_TURNS: u64 = 16; + +/// Counts selections by priority, so a waiting candidate's +/// [`CacheAwareCandidate::passed_over`] can be read off at any time. +#[derive(Debug, Default, Clone)] +pub struct PriorityPassovers { + selected: std::collections::BTreeMap, +} + +impl PriorityPassovers { + /// Record that a candidate of `priority` was selected. + pub fn record_selection(&mut self, priority: u64) { + let count = self.selected.entry(priority).or_default(); + *count = count.saturating_add(1); + } + + /// The selections so far above `priority`. Keep it when a candidate of + /// `priority` starts waiting and pass it to [`Self::passed_over`] later. + pub fn mark(&self, priority: u64) -> u64 { + self.selected + .range(priority.saturating_add(1)..) + .map(|(_, count)| *count) + .fold(0, u64::saturating_add) + } + + /// How many higher-priority candidates were selected since `mark`. + pub fn passed_over(&self, priority: u64, mark: u64) -> u64 { + self.mark(priority).saturating_sub(mark) + } +} + #[derive(Debug, Clone, Copy)] pub struct CacheAwareCandidate<'a> { pub index: usize, @@ -64,6 +100,9 @@ pub struct CacheAwareCandidate<'a> { pub prompt_tokens: &'a [i32], pub enqueued_turn: u64, pub order: u64, + /// How many higher-priority candidates were selected while this one + /// waited (see [`PriorityPassovers`]); it ages the candidate's priority. + pub passed_over: u64, } /// Order cache candidates by priority, saved work plus aging, then waiting @@ -101,6 +140,10 @@ pub fn order_cache_aware_candidates_with_anchor<'a>( anchor_prompt: Option<&[i32]>, ) -> Vec { let candidates = candidates.into_iter().collect::>(); + let levels = candidates + .iter() + .map(|candidate| candidate.priority) + .collect::>(); let mut dfs_ranks = vec![0usize; candidates.len()]; if group_waiting_prefixes { let mut dfs_order = Vec::with_capacity(candidates.len()); @@ -124,9 +167,8 @@ pub fn order_cache_aware_candidates_with_anchor<'a>( ranked.sort_by(|(left, left_dfs_rank), (right, right_dfs_rank)| { let left_score = effective_score(left, current_turn, aging_cost_per_turn); let right_score = effective_score(right, current_turn, aging_cost_per_turn); - right - .priority - .cmp(&left.priority) + priority_rank(right, &levels) + .cmp(&priority_rank(left, &levels)) .then_with(|| { if group_waiting_prefixes { grouping_score(right, current_turn, aging_cost_per_turn).cmp(&grouping_score( @@ -154,6 +196,28 @@ pub fn order_cache_aware_candidates_with_anchor<'a>( .collect() } +/// Priority plus one level per [`PRIORITY_AGING_TURNS`] times passed over. +fn aged_priority(candidate: &CacheAwareCandidate<'_>) -> u64 { + candidate + .priority + .saturating_add(candidate.passed_over / PRIORITY_AGING_TURNS) +} + +/// The highest priority among `levels` (the candidates' own priorities) that +/// `candidate` has aged to. Age only lifts a candidate to a level another +/// candidate holds, so candidates of one level keep the cache-aware order +/// whatever their ages. +fn priority_rank( + candidate: &CacheAwareCandidate<'_>, + levels: &std::collections::BTreeSet, +) -> u64 { + levels + .range(..=aged_priority(candidate)) + .next_back() + .copied() + .unwrap_or(candidate.priority) +} + fn grouping_score( candidate: &CacheAwareCandidate<'_>, current_turn: u64, @@ -301,6 +365,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -309,6 +374,7 @@ mod tests { prompt_tokens: &[4, 5, 6], enqueued_turn: 0, order: 1, + passed_over: 0, }, ], 0, @@ -333,6 +399,7 @@ mod tests { prompt_tokens, enqueued_turn: 0, order: index as u64, + passed_over: 0, }), 0, 10, @@ -349,6 +416,7 @@ mod tests { prompt_tokens: prompts[index], enqueued_turn: 0, order: index as u64, + passed_over: 0, }), 1, 10, @@ -371,6 +439,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -379,6 +448,7 @@ mod tests { prompt_tokens: &[4, 5, 6], enqueued_turn: 11, order: 1, + passed_over: 0, }, ], 11, @@ -401,6 +471,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -409,6 +480,7 @@ mod tests { prompt_tokens: &[4, 5, 6], enqueued_turn: 0, order: 1, + passed_over: 0, }, ], 0, @@ -418,6 +490,82 @@ mod tests { assert_eq!(selected, Some(0)); } + #[test] + fn waiting_lower_priority_climbs_one_level_per_aging_window() { + let affinity = CacheAffinity::default(); + let candidates = |passed_over: u64| { + order_cache_aware_candidates( + [ + CacheAwareCandidate { + index: 0, + priority: 0, + affinity: &affinity, + prompt_tokens: &[1], + enqueued_turn: 0, + order: 0, + passed_over, + }, + CacheAwareCandidate { + index: 1, + priority: 2, + affinity: &affinity, + prompt_tokens: &[2], + enqueued_turn: 100, + order: 1, + passed_over: 0, + }, + ], + 100, + 10, + false, + ) + }; + // A fresh higher-priority arrival passes a waiter two levels below it + // until that waiter has been passed over two full windows; then age + // decides. + assert_eq!(candidates(2 * PRIORITY_AGING_TURNS - 1), vec![1, 0]); + assert_eq!(candidates(2 * PRIORITY_AGING_TURNS), vec![0, 1]); + } + + #[test] + fn age_never_reorders_candidates_of_one_priority() { + let affinity = CacheAffinity::default(); + let candidate = |index, passed_over| CacheAwareCandidate { + index, + priority: 1, + affinity: &affinity, + prompt_tokens: &[1], + enqueued_turn: 0, + order: index as u64, + passed_over, + }; + let levels = std::collections::BTreeSet::from([1]); + let long = 10 * PRIORITY_AGING_TURNS; + assert_eq!(priority_rank(&candidate(0, long), &levels), 1); + assert_eq!(priority_rank(&candidate(1, 0), &levels), 1); + let with_higher = std::collections::BTreeSet::from([1, 2, 4]); + assert_eq!(priority_rank(&candidate(0, long), &with_higher), 4); + assert_eq!( + priority_rank(&candidate(0, PRIORITY_AGING_TURNS), &with_higher), + 2 + ); + assert_eq!(priority_rank(&candidate(1, 0), &with_higher), 1); + } + + #[test] + fn only_higher_priority_selections_pass_a_candidate_over() { + let mut passovers = PriorityPassovers::default(); + let mark = passovers.mark(1); + passovers.record_selection(0); + passovers.record_selection(1); + assert_eq!(passovers.passed_over(1, mark), 0); + passovers.record_selection(2); + passovers.record_selection(5); + assert_eq!(passovers.passed_over(1, mark), 2); + assert_eq!(passovers.passed_over(2, passovers.mark(2)), 0); + assert_eq!(passovers.mark(u64::MAX), 0); + } + #[test] fn dfs_weight_groups_the_heaviest_equal_score_prefix_subtree() { let affinity = CacheAffinity::default(); @@ -430,6 +578,7 @@ mod tests { prompt_tokens: &[9, 9, 9], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -438,6 +587,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 0, order: 1, + passed_over: 0, }, CacheAwareCandidate { index: 2, @@ -446,6 +596,7 @@ mod tests { prompt_tokens: &[1, 2, 4], enqueued_turn: 0, order: 2, + passed_over: 0, }, ], 0, @@ -468,6 +619,7 @@ mod tests { prompt_tokens: &[9, 9, 9], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -476,6 +628,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 1, order: 1, + passed_over: 0, }, CacheAwareCandidate { index: 2, @@ -484,6 +637,7 @@ mod tests { prompt_tokens: &[1, 2, 4], enqueued_turn: 2, order: 2, + passed_over: 0, }, ], 3, @@ -506,6 +660,7 @@ mod tests { prompt_tokens: &[9, 9, 9], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -514,6 +669,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 9, order: 1, + passed_over: 0, }, CacheAwareCandidate { index: 2, @@ -522,6 +678,7 @@ mod tests { prompt_tokens: &[1, 2, 4], enqueued_turn: 10, order: 2, + passed_over: 0, }, ], 10, @@ -544,6 +701,7 @@ mod tests { prompt_tokens: &[9, 9, 9], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -552,6 +710,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 0, order: 1, + passed_over: 0, }, CacheAwareCandidate { index: 2, @@ -560,6 +719,7 @@ mod tests { prompt_tokens: &[1, 2, 4], enqueued_turn: 0, order: 2, + passed_over: 0, }, ], 0, @@ -583,6 +743,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -591,6 +752,7 @@ mod tests { prompt_tokens: &[1, 2, 4], enqueued_turn: 0, order: 1, + passed_over: 0, }, CacheAwareCandidate { index: 2, @@ -599,6 +761,7 @@ mod tests { prompt_tokens: &[9, 9, 9], enqueued_turn: 0, order: 2, + passed_over: 0, }, ], 0, @@ -625,6 +788,7 @@ mod tests { prompt_tokens: &left, enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -633,6 +797,7 @@ mod tests { prompt_tokens: &right, enqueued_turn: 0, order: 1, + passed_over: 0, }, ], 0, diff --git a/skippy/crates/skippy-scheduler/src/capacity.rs b/skippy/crates/skippy-scheduler/src/capacity.rs index 7c8cfa9650..6de4c32b09 100644 --- a/skippy/crates/skippy-scheduler/src/capacity.rs +++ b/skippy/crates/skippy-scheduler/src/capacity.rs @@ -7,6 +7,10 @@ pub struct EvictableCacheEntry { pub units: u64, pub recompute_cost: u64, pub last_used: u64, + /// Entries with a lower retention priority are evicted first, before + /// recompute value is considered. Serving uses the request tier's + /// priority, so mesh entries go before trusted ones and those before local. + pub retention_priority: u64, } /// Current occupancy for one independently constrained memory component. @@ -144,9 +148,13 @@ pub fn rank_eviction_candidates(entries: &mut [EvictableCacheEntry]) { fn compare_eviction_value(left: &EvictableCacheEntry, right: &EvictableCacheEntry) -> Ordering { let left_units = left.units.max(1); let right_units = right.units.max(1); - u128::from(left.recompute_cost) - .saturating_mul(u128::from(right_units)) - .cmp(&u128::from(right.recompute_cost).saturating_mul(u128::from(left_units))) + left.retention_priority + .cmp(&right.retention_priority) + .then_with(|| { + u128::from(left.recompute_cost) + .saturating_mul(u128::from(right_units)) + .cmp(&u128::from(right.recompute_cost).saturating_mul(u128::from(left_units))) + }) .then_with(|| left.last_used.cmp(&right.last_used)) .then_with(|| left.recompute_cost.cmp(&right.recompute_cost)) .then_with(|| left.id.cmp(&right.id)) @@ -162,6 +170,7 @@ mod tests { units, recompute_cost, last_used, + retention_priority: 0, } } @@ -255,6 +264,27 @@ mod tests { assert!(plan.victim_ids.is_empty()); } + #[test] + fn evicts_lower_retention_priority_before_cheaper_entries() { + let mut entries = vec![ + EvictableCacheEntry { + retention_priority: 2, + ..entry("local-cheap", 30, 1, 1) + }, + entry("mesh-expensive", 30, 300, 2), + EvictableCacheEntry { + retention_priority: 1, + ..entry("trusted-cheap", 30, 1, 0) + }, + ]; + rank_eviction_candidates(&mut entries); + let order = entries + .iter() + .map(|entry| entry.id.as_str()) + .collect::>(); + assert_eq!(order, ["mesh-expensive", "trusted-cheap", "local-cheap"]); + } + #[test] fn evicts_low_recompute_cost_before_older_expensive_entries() { let plan = plan_component_capacity( diff --git a/skippy/crates/skippy-scheduler/src/engine.rs b/skippy/crates/skippy-scheduler/src/engine.rs index c88cfa7406..092d128043 100644 --- a/skippy/crates/skippy-scheduler/src/engine.rs +++ b/skippy/crates/skippy-scheduler/src/engine.rs @@ -3,7 +3,7 @@ use std::time::{Duration, Instant}; use crate::{ CacheAwareCandidate, IterationPhase, IterationPlan, IterationPrediction, IterationTelemetry, - IterationWork, SchedulerConfig, SchedulerMetrics, Sequence, SequenceStatus, + IterationWork, PriorityPassovers, SchedulerConfig, SchedulerMetrics, Sequence, SequenceStatus, order_cache_aware_candidates, }; @@ -32,6 +32,7 @@ pub struct Scheduler { metrics: SchedulerMetrics, consecutive_prefill_iterations: usize, waiting_turn: u64, + passovers: PriorityPassovers, next_waiting_order: u64, waiting_order_dirty: bool, decode_us_ewma_by_rows: BTreeMap, @@ -55,6 +56,7 @@ impl Scheduler { metrics: SchedulerMetrics::default(), consecutive_prefill_iterations: 0, waiting_turn: 0, + passovers: PriorityPassovers::default(), next_waiting_order: 0, waiting_order_dirty: false, decode_us_ewma_by_rows: BTreeMap::new(), @@ -84,6 +86,7 @@ impl Scheduler { self.metrics.prefix_misses = self.metrics.prefix_misses.saturating_add(1); } sequence.enqueued_turn = self.waiting_turn; + sequence.passover_mark = self.passovers.mark(sequence.priority); sequence.enqueue_order = self.next_waiting_order; self.next_waiting_order = self.next_waiting_order.saturating_add(1); self.waiting.push_back(sequence); @@ -482,6 +485,8 @@ impl Scheduler { }; self.release_memory(&sequence); sequence.reset_for_recompute(); + // Admissions made while it ran did not pass it over. + sequence.passover_mark = self.passovers.mark(sequence.priority); sequence.enqueue_order = self.next_waiting_order; self.next_waiting_order = self.next_waiting_order.saturating_add(1); self.waiting.push_front(sequence); @@ -534,6 +539,7 @@ impl Scheduler { fn admit_waiting(&mut self) -> usize { let mut admitted = 0; + let mut highest_admitted = None; let mut deferred = VecDeque::new(); if self.waiting_order_dirty { let order = order_cache_aware_candidates( @@ -547,6 +553,9 @@ impl Scheduler { prompt_tokens: &sequence.prompt_tokens, enqueued_turn: sequence.enqueued_turn, order: sequence.enqueue_order, + passed_over: self + .passovers + .passed_over(sequence.priority, sequence.passover_mark), }), self.waiting_turn, self.config.cache_aging_cost_per_iteration, @@ -569,12 +578,23 @@ impl Scheduler { continue; } self.reserve_memory(&sequence); + self.passovers.record_selection(sequence.priority); + highest_admitted = highest_admitted.max(Some(sequence.priority)); sequence.status = SequenceStatus::Running; sequence.admitted_at = Some(Instant::now()); self.active.insert(sequence.id.clone(), sequence); admitted += 1; } self.waiting = deferred; + // Passing lower priorities over can age them past another level. + if let Some(highest) = highest_admitted + && self + .waiting + .iter() + .any(|waiting| waiting.priority < highest) + { + self.waiting_order_dirty = true; + } self.refresh_counts(); admitted } @@ -1285,4 +1305,36 @@ mod tests { assert_eq!(scheduler.sequence("cold").unwrap().enqueued_turn, 0); } } + + #[test] + fn a_preempted_sequence_is_not_aged_by_admissions_made_while_it_ran() { + let mut scheduler = Scheduler::new(SchedulerConfig { + max_active_sequences: 1, + memory_components: vec![MemoryComponent { + name: "kv".into(), + capacity_bytes: 2, + resident_bytes: 0, + bytes_per_token: 1, + bytes_per_sequence: 0, + }], + ..SchedulerConfig::default() + }); + scheduler + .submit(sequence("mesh", 2, 4).with_admission_tokens(1)) + .unwrap(); + scheduler.plan_iteration(); + assert_eq!(scheduler.snapshot().active_ids, ["mesh"]); + for _ in 0..2 * crate::PRIORITY_AGING_TURNS { + scheduler.passovers.record_selection(2); + } + assert_eq!(scheduler.preempt_for_component_pressure(&[3]), ["mesh"]); + scheduler.preempt_for_component_pressure(&[0]); + let mut local = sequence("local", 2, 4).with_admission_tokens(1); + local.priority = 2; + scheduler.submit(local).unwrap(); + + scheduler.plan_iteration(); + + assert_eq!(scheduler.snapshot().active_ids, ["local"]); + } } diff --git a/skippy/crates/skippy-scheduler/src/lib.rs b/skippy/crates/skippy-scheduler/src/lib.rs index b42838062d..c5a2bd6d43 100644 --- a/skippy/crates/skippy-scheduler/src/lib.rs +++ b/skippy/crates/skippy-scheduler/src/lib.rs @@ -12,8 +12,9 @@ mod sequence; mod telemetry; pub use cache_policy::{ - CacheAffinity, CacheAwareCandidate, StageCacheAffinity, order_cache_aware_candidates, - order_cache_aware_candidates_with_anchor, select_cache_aware_candidate, + CacheAffinity, CacheAwareCandidate, PRIORITY_AGING_TURNS, PriorityPassovers, + StageCacheAffinity, order_cache_aware_candidates, order_cache_aware_candidates_with_anchor, + select_cache_aware_candidate, }; pub use capacity::{ CapacityDemand, CapacityPlan, ComponentCapacitySnapshot, EvictableCacheEntry, diff --git a/skippy/crates/skippy-scheduler/src/sequence.rs b/skippy/crates/skippy-scheduler/src/sequence.rs index 690550d81b..5357faf1e2 100644 --- a/skippy/crates/skippy-scheduler/src/sequence.rs +++ b/skippy/crates/skippy-scheduler/src/sequence.rs @@ -47,6 +47,8 @@ pub struct Sequence { pub(crate) prefill_cursor: usize, pub(crate) enqueued_turn: u64, pub(crate) enqueue_order: u64, + /// [`crate::PriorityPassovers::mark`] when the sequence started waiting. + pub(crate) passover_mark: u64, } impl Sequence { @@ -75,6 +77,7 @@ impl Sequence { prefill_cursor: 0, enqueued_turn: 0, enqueue_order: 0, + passover_mark: 0, } } diff --git a/skippy/crates/skippy-serving/README.md b/skippy/crates/skippy-serving/README.md index b8211634b1..424c727bb6 100644 --- a/skippy/crates/skippy-serving/README.md +++ b/skippy/crates/skippy-serving/README.md @@ -160,11 +160,11 @@ deadline handling. ## Notes - `serve --stage-transport binary` is the tuned binary stage-to-stage path. -- Binary stages participate in the breaking generation-16 stage protocol. - Stage compatibility requires the complete `stage-generation-16` control, +- Binary stages participate in the breaking generation-17 stage protocol. + Stage compatibility requires the complete `stage-generation-17` control, status-list, strict-content-identity, stage-admission, and stale-window-discard bundle, including bounded causal decision readouts. Older peers are rejected - during split planning rather than being mixed into a generation-16 topology. + during split planning rather than being mixed into a generation-17 topology. - Binary stages accept upstream protocol connections concurrently. Model execution remains serialized by the per-process runtime lock, but readiness, abandoned, or broken connections do not monopolize the listener and block the diff --git a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/public_frontend.rs b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/public_frontend.rs index edecc6330e..fb4acd8a27 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/public_frontend.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/public_frontend.rs @@ -64,6 +64,7 @@ pub(super) fn start(launch: PublicFrontendLaunch) -> Result, #[cfg(test)] released: Condvar, @@ -47,6 +50,7 @@ struct GenerationTokenBudgetState { pub(super) struct GenerationTokenBudgetRequest { prompt_tokens: usize, max_tokens: u32, + tier: InferenceRequestTier, } #[derive(Debug)] @@ -58,14 +62,19 @@ pub(super) struct GenerationTokenReservation { impl GenerationTokenBudget { /// All frontends sharing a runtime reserve against one aggregate pool. + /// The first frontend sets the pool's `local` reserve. pub(crate) fn shared_for_runtime( runtime: &mut crate::runtime_state::RuntimeState, configured_tokens: usize, + local_reserve_percent: u8, ) -> Arc { if let Some(budget) = runtime.generation_token_budget.as_ref() { return Arc::clone(budget); } - let budget = Arc::new(Self::for_runtime(runtime, configured_tokens)); + let budget = Arc::new( + Self::for_runtime(runtime, configured_tokens) + .with_local_reserve_percent(local_reserve_percent), + ); runtime.generation_token_budget = Some(Arc::clone(&budget)); budget } @@ -88,6 +97,7 @@ impl GenerationTokenBudget { pub(super) fn new(ctx_size: usize) -> Self { Self { capacity_tokens: ctx_size.max(1), + local_reserve_tokens: 0, state: Mutex::new(GenerationTokenBudgetState::default()), #[cfg(test)] released: Condvar::new(), @@ -95,17 +105,41 @@ impl GenerationTokenBudget { } } + /// Hold back `percent` of the pool for `local` requests. Lower tiers + /// cannot reserve into that share; `local` requests can use all of it. + /// The reserve rounds up, so lower tiers never get more than the rest. + pub(super) fn with_local_reserve_percent(mut self, percent: u8) -> Self { + let percent = usize::from(percent.min(100)); + self.local_reserve_tokens = self + .capacity_tokens + .saturating_mul(percent) + .div_ceil(100) + .min(self.capacity_tokens); + self + } + + /// The share of the pool a request at `tier` may occupy together with + /// everything already reserved. + fn capacity_for(&self, tier: InferenceRequestTier) -> usize { + match tier { + InferenceRequestTier::Local => self.capacity_tokens, + InferenceRequestTier::Trusted | InferenceRequestTier::Mesh => self + .capacity_tokens + .saturating_sub(self.local_reserve_tokens), + } + } + pub(super) fn try_reserve( self: &Arc, request: GenerationTokenBudgetRequest, ) -> InferenceResult> { let tokens = request.reservation_tokens(); - self.ensure_request_fits(tokens)?; + self.ensure_request_fits(tokens, request.tier)?; let mut state = self .state .lock() .map_err(|_| InferenceError::backend("generation token budget lock poisoned"))?; - if state.active_tokens.saturating_add(tokens) > self.capacity_tokens { + if state.active_tokens.saturating_add(tokens) > self.capacity_for(request.tier) { return Ok(None); } state.active_tokens = state.active_tokens.saturating_add(tokens); @@ -121,12 +155,12 @@ impl GenerationTokenBudget { request: GenerationTokenBudgetRequest, ) -> InferenceResult { let tokens = request.reservation_tokens(); - self.ensure_request_fits(tokens)?; + self.ensure_request_fits(tokens, request.tier)?; let state = self .state .lock() .map_err(|_| InferenceError::backend("generation token budget lock poisoned"))?; - Ok(state.active_tokens.saturating_add(tokens) <= self.capacity_tokens) + Ok(state.active_tokens.saturating_add(tokens) <= self.capacity_for(request.tier)) } pub(super) fn release_notification(&self) -> &Notify { @@ -150,7 +184,7 @@ impl GenerationTokenBudget { cancellation: Option<&skippy_inference_api::CancellationToken>, ) -> InferenceResult { let tokens = request.reservation_tokens(); - self.ensure_request_fits(tokens)?; + self.ensure_request_fits(tokens, request.tier)?; let deadline = Instant::now() + admission_timeout; let mut state = self .state @@ -160,7 +194,7 @@ impl GenerationTokenBudget { if cancellation.is_some_and(skippy_inference_api::CancellationToken::is_cancelled) { return Err(InferenceError::backend("request cancelled")); } - if state.active_tokens.saturating_add(tokens) <= self.capacity_tokens { + if state.active_tokens.saturating_add(tokens) <= self.capacity_for(request.tier) { state.active_tokens = state.active_tokens.saturating_add(tokens); return Ok(GenerationTokenReservation { budget: self.clone(), @@ -204,12 +238,26 @@ impl GenerationTokenBudget { self.capacity_tokens } - fn ensure_request_fits(&self, requested_tokens: usize) -> InferenceResult<()> { - if requested_tokens <= self.capacity_tokens { + fn ensure_request_fits( + &self, + requested_tokens: usize, + tier: InferenceRequestTier, + ) -> InferenceResult<()> { + let capacity = self.capacity_for(tier); + if requested_tokens <= capacity { return Ok(()); } + if capacity == self.capacity_tokens { + return Err(InferenceError::context_length_exceeded(format!( + "request requires {requested_tokens} KV tokens but the runtime pool holds {}", + self.capacity_tokens + ))); + } + // Worded as an overflow, so a mesh router retries it on another node. Err(InferenceError::context_length_exceeded(format!( - "request requires {requested_tokens} KV tokens but the runtime pool holds {}", + "request requires {requested_tokens} KV tokens, which exceeds the {capacity} of the \ + {}-token runtime pool that {tier} requests may use; the rest is reserved for local \ + requests", self.capacity_tokens ))) } @@ -228,9 +276,16 @@ impl GenerationTokenBudgetRequest { Self { prompt_tokens, max_tokens, + tier: InferenceRequestTier::default(), } } + /// Reserve as a request at `tier`. + pub(super) fn with_tier(mut self, tier: InferenceRequestTier) -> Self { + self.tier = tier; + self + } + pub(super) fn reservation_tokens(self) -> usize { let max_tokens = usize::try_from(self.max_tokens).unwrap_or(usize::MAX); let decode_headroom = max_tokens.min(DECODE_BATCH_HEADROOM_TOKENS); @@ -357,8 +412,8 @@ mod tests { fn multiple_frontends_share_one_runtime_token_reservation_pool() { let mut runtime = crate::runtime_state::RuntimeState::new_modelless_with_capacity_for_test(2, 1024); - let first = GenerationTokenBudget::shared_for_runtime(&mut runtime, 512); - let second = GenerationTokenBudget::shared_for_runtime(&mut runtime, 512); + let first = GenerationTokenBudget::shared_for_runtime(&mut runtime, 512, 0); + let second = GenerationTokenBudget::shared_for_runtime(&mut runtime, 512, 0); assert!(Arc::ptr_eq(&first, &second)); let reservation = first .try_reserve(GenerationTokenBudgetRequest::new(768, 0)) @@ -468,4 +523,13 @@ mod tests { assert!(error.to_string().contains("KV token budget")); assert_eq!(budget.active_tokens(), 800); } + + #[test] + fn the_local_reserve_rounds_up() { + let budget = GenerationTokenBudget::new(10).with_local_reserve_percent(25); + assert_eq!(budget.capacity_for(InferenceRequestTier::Mesh), 7); + assert_eq!(budget.capacity_for(InferenceRequestTier::Local), 10); + let all = GenerationTokenBudget::new(10).with_local_reserve_percent(100); + assert_eq!(all.capacity_for(InferenceRequestTier::Trusted), 0); + } } diff --git a/skippy/crates/skippy-serving/src/frontend/backend.rs b/skippy/crates/skippy-serving/src/frontend/backend.rs index 04fe4c5465..7cfd99d9e3 100644 --- a/skippy/crates/skippy-serving/src/frontend/backend.rs +++ b/skippy/crates/skippy-serving/src/frontend/backend.rs @@ -483,6 +483,7 @@ impl GenerationAdmissionController { work: GenerationAdmissionWork, scheduling: GenerationAdmissionScheduling, ) -> InferenceResult<(GenerationAdmissionPermit, Option)> { + let scheduling = scheduling.with_tier(ids.request_tier()); let deadline = if admission_timeout.is_zero() { None } else { @@ -551,13 +552,15 @@ impl GenerationAdmissionController { if cancellation.is_cancelled() { return Err(request_cancelled_error()); } + let tier = scheduling.tier(); let claim = self.generation_limit.admission_queue().claim_or_enqueue( self.generation_limit.semaphore(), self.generation_token_budget.clone(), GenerationTokenBudgetRequest::new( usize::try_from(work.prompt_tokens).unwrap_or(usize::MAX), u32::try_from(work.decode_tokens).unwrap_or(u32::MAX), - ), + ) + .with_tier(tier), scheduling, self.generation_queue_depth.clone(), self.generation_queue_limit, @@ -579,8 +582,8 @@ impl GenerationAdmissionController { self.generation_limit.note_queued_demand(); self.generation_service_estimator .set_concurrency(self.generation_limit.current_limit()); - let predicted_wait_ms = self.generation_service_estimator.predicted_wait_ms(); - let queued_work = self.generation_service_estimator.reserve_queued(work); + let predicted_wait_ms = self.generation_service_estimator.predicted_wait_ms(tier); + let queued_work = self.generation_service_estimator.reserve_queued(work, tier); let resources = lease .acquire( self.generation_limit.semaphore(), @@ -900,6 +903,7 @@ impl StageOpenAiBackend { scheduling: GenerationAdmissionScheduling, ) -> InferenceResult<(GenerationAdmissionPermit, Option)> { let admission_started = Instant::now(); + let tier = ids.request_tier(); let result = GenerationAdmissionController::for_backend(self) .acquire_scheduled_work( ids, @@ -940,7 +944,9 @@ impl StageOpenAiBackend { "llama_stage.generation_admission_error".to_string(), json!(error.body().error.message), ); - if let Some(predicted_wait_ms) = self.generation_service_estimator.predicted_wait_ms() { + if let Some(predicted_wait_ms) = + self.generation_service_estimator.predicted_wait_ms(tier) + { attrs.insert( "llama_stage.generation_predicted_wait_ms".to_string(), json!(predicted_wait_ms), @@ -1304,3 +1310,5 @@ impl StageOpenAiBackend { #[cfg(test)] mod tests; +#[cfg(test)] +mod tier_admission_tests; diff --git a/skippy/crates/skippy-serving/src/frontend/backend/inference.rs b/skippy/crates/skippy-serving/src/frontend/backend/inference.rs index 7fbf61cef6..41abcbf0a2 100644 --- a/skippy/crates/skippy-serving/src/frontend/backend/inference.rs +++ b/skippy/crates/skippy-serving/src/frontend/backend/inference.rs @@ -22,7 +22,17 @@ impl InferenceBackend for StageOpenAiBackend { /// Serve System One requests through the backend's selected execution path. async fn system_one(&self, request: SystemOneRequest) -> InferenceResult { - self.serve_system_one(request).await + self.serve_system_one(request, Default::default()).await + } + + /// Serve System One at the request's tier and in its cache partition. + async fn system_one_with_context( + &self, + request: SystemOneRequest, + context: InferenceRequestContext, + ) -> InferenceResult { + self.serve_system_one(request, context.request_class()) + .await } async fn chat_completion( @@ -37,9 +47,10 @@ impl InferenceBackend for StageOpenAiBackend { /// Keep the scope through prompt preparation, native request IDs and cache selection. async fn chat_completion_with_context( &self, - request: GenerationRequest, + mut request: GenerationRequest, context: InferenceRequestContext, ) -> InferenceResult { + request.request_class = context.request_class(); let ids = generation_ids( InferenceCacheHints::from_chat_request(&request), request.agent_session(), @@ -194,9 +205,10 @@ impl InferenceBackend for StageOpenAiBackend { /// Retain the context in the native worker while producing bounded response events. async fn chat_completion_stream( &self, - request: GenerationRequest, + mut request: GenerationRequest, context: InferenceRequestContext, ) -> InferenceResult { + request.request_class = context.request_class(); let ids = generation_ids( InferenceCacheHints::from_chat_request(&request), request.agent_session(), diff --git a/skippy/crates/skippy-serving/src/frontend/backend/tests/admission.rs b/skippy/crates/skippy-serving/src/frontend/backend/tests/admission.rs index 3fad40b42e..6c076ae618 100644 --- a/skippy/crates/skippy-serving/src/frontend/backend/tests/admission.rs +++ b/skippy/crates/skippy-serving/src/frontend/backend/tests/admission.rs @@ -464,7 +464,7 @@ async fn inflated_prediction_waits_for_capacity_and_preserves_queue_bounds() { let timeout = Duration::from_secs(1); let predicted = controller .generation_service_estimator - .predicted_wait_ms() + .predicted_wait_ms(skippy_inference_api::InferenceRequestTier::Local) .unwrap(); assert!(predicted > timeout.as_secs_f64() * 1_000.0); let ids = trusted_ids("agent-2"); @@ -499,7 +499,9 @@ async fn inflated_prediction_waits_for_capacity_and_preserves_queue_bounds() { assert_eq!(controller.generation_limit.available_permits(), 1); assert_eq!(controller.generation_token_budget.active_tokens(), 0); assert_eq!( - controller.generation_service_estimator.predicted_wait_ms(), + controller + .generation_service_estimator + .predicted_wait_ms(skippy_inference_api::InferenceRequestTier::Local), Some(0.0) ); assert!( @@ -546,7 +548,9 @@ async fn advisory_prediction_does_not_bypass_an_expired_admission_deadline() { assert_eq!(controller.generation_limit.available_permits(), 1); assert_eq!(controller.generation_token_budget.active_tokens(), 0); assert_eq!( - controller.generation_service_estimator.predicted_wait_ms(), + controller + .generation_service_estimator + .predicted_wait_ms(skippy_inference_api::InferenceRequestTier::Local), Some(0.0) ); } diff --git a/skippy/crates/skippy-serving/src/frontend/backend/tier_admission_tests.rs b/skippy/crates/skippy-serving/src/frontend/backend/tier_admission_tests.rs new file mode 100644 index 0000000000..04eb14d98e --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/backend/tier_admission_tests.rs @@ -0,0 +1,434 @@ +//! Admission by request tier: higher tiers are admitted first, keep their +//! room in the waiting queue and in the KV pool, and are not held behind a +//! lower tier's head-of-line reservation. + +use super::*; +use crate::frontend::generation::ADMISSION_STARVATION_BOUND_TURNS; +use skippy_inference_api::{CancellationToken, InferenceRequestClass, InferenceRequestTier}; +use skippy_scheduler::PRIORITY_AGING_TURNS; + +/// A generous bound for an event the test waits on, so a slow or busy +/// machine does not fail it. +const WAIT: Duration = Duration::from_secs(60); + +fn controller( + generation_concurrency: usize, + generation_queue_limit: usize, + token_capacity: usize, + local_reserve_percent: u8, +) -> GenerationAdmissionController { + GenerationAdmissionController { + generation_limit: Arc::new(GenerationConcurrencyController::fixed( + generation_concurrency, + )), + generation_queue_depth: Arc::new(AtomicUsize::new(0)), + generation_queue_limit, + generation_service_estimator: Arc::new(GenerationServiceEstimator::new( + generation_concurrency, + )), + generation_session_locks: Arc::new(Mutex::new(BTreeMap::new())), + generation_token_budget: Arc::new( + GenerationTokenBudget::new(token_capacity) + .with_local_reserve_percent(local_reserve_percent), + ), + } +} + +fn ids(session_id: &str, tier: InferenceRequestTier) -> InferenceGenerationIds { + InferenceGenerationIds::new_with_trust( + InferenceCacheHints::default(), + Some(session_id), + true, + None, + ) + .with_request_class(InferenceRequestClass::new(tier, false)) +} + +async fn admit( + controller: &GenerationAdmissionController, + session_id: &str, + tier: InferenceRequestTier, + tokens: usize, +) -> InferenceResult<(GenerationAdmissionPermit, Option)> { + controller + .acquire_work( + &ids(session_id, tier), + &CancellationToken::new(), + Duration::ZERO, + GenerationAdmissionWork::new(tokens, 0), + ) + .await +} + +async fn wait_for_queue_depth(controller: &GenerationAdmissionController, depth: usize) { + tokio::time::timeout(WAIT, async { + while controller.generation_queue_depth.load(Ordering::Acquire) != depth { + tokio::task::yield_now().await; + } + }) + .await + .expect("waiters reached the queue"); +} + +#[tokio::test] +async fn the_local_reserve_is_kept_for_local_requests() { + let controller = controller(4, 4, 10, 50); + let too_large = admit(&controller, "mesh-large", InferenceRequestTier::Mesh, 6).await; + let error = too_large + .err() + .expect("a mesh request cannot use the reserve"); + assert!( + error.body().error.message.contains("reserved for local"), + "{}", + error.body().error.message + ); + + let mesh = admit(&controller, "mesh", InferenceRequestTier::Mesh, 5) + .await + .expect("mesh fits outside the reserve"); + let local = tokio::time::timeout( + WAIT, + admit(&controller, "local", InferenceRequestTier::Local, 5), + ) + .await + .expect("local is not queued behind mesh") + .expect("local fits in the reserve"); + assert_eq!(controller.generation_token_budget.active_tokens(), 10); + drop((mesh, local)); +} + +#[tokio::test] +async fn a_lower_tier_cannot_fill_the_waiting_room_ahead_of_local() { + let controller = controller(1, 1, 100, 0); + let active = admit(&controller, "active", InferenceRequestTier::Local, 1) + .await + .expect("the lane is free"); + + let waiting_controller = controller.clone(); + let mesh_waiter = tokio::spawn(async move { + admit(&waiting_controller, "mesh-1", InferenceRequestTier::Mesh, 1).await + }); + wait_for_queue_depth(&controller, 1).await; + let full = admit(&controller, "mesh-2", InferenceRequestTier::Mesh, 1).await; + assert!(full.is_err(), "the mesh share of the room is full"); + + let local_controller = controller.clone(); + let local_waiter = tokio::spawn(async move { + admit(&local_controller, "local", InferenceRequestTier::Local, 1).await + }); + wait_for_queue_depth(&controller, 2).await; + + // The younger local waiter is admitted first. + drop(active); + let local = tokio::time::timeout(WAIT, local_waiter) + .await + .expect("local admitted") + .unwrap() + .expect("local admission succeeded"); + assert!(!mesh_waiter.is_finished()); + drop(local); + let mesh = tokio::time::timeout(WAIT, mesh_waiter) + .await + .expect("mesh admitted after local") + .unwrap() + .expect("mesh admission succeeded"); + drop(mesh); +} + +#[tokio::test] +async fn an_unfitting_senior_mesh_waiter_does_not_hold_back_local_requests() { + // 10 tokens, 5 of them reserved for local requests. + let controller = controller(4, 4, 10, 50); + // A long local request keeps the mesh share full. + let long_local = admit(&controller, "long-local", InferenceRequestTier::Local, 6) + .await + .expect("local fits"); + let mesh_controller = controller.clone(); + let mesh_waiter = tokio::spawn(async move { + admit(&mesh_controller, "mesh", InferenceRequestTier::Mesh, 1).await + }); + wait_for_queue_depth(&controller, 1).await; + + // Past the starvation bound, local requests that fit are still admitted. + for wave in 0..ADMISSION_STARVATION_BOUND_TURNS + 4 { + let local = tokio::time::timeout( + WAIT, + admit( + &controller, + &format!("local-{wave}"), + InferenceRequestTier::Local, + 4, + ), + ) + .await + .unwrap_or_else(|_| panic!("local request {wave} was held behind the mesh waiter")) + .expect("local admission succeeded"); + drop(local); + } + assert!(!mesh_waiter.is_finished()); + + drop(long_local); + let mesh = tokio::time::timeout(WAIT, mesh_waiter) + .await + .expect("mesh admitted once the pool drains") + .unwrap() + .expect("mesh admission succeeded"); + drop(mesh); +} + +#[tokio::test] +async fn an_older_mesh_waiter_does_not_take_a_starving_local_waiters_hold() { + let controller = controller(4, 8, 10, 0); + let active = admit(&controller, "active", InferenceRequestTier::Local, 6) + .await + .expect("the pool is free"); + // The oldest waiter is a mesh request; a large local one queues behind it. + let mesh_controller = controller.clone(); + let mesh_waiter = tokio::spawn(async move { + admit(&mesh_controller, "mesh", InferenceRequestTier::Mesh, 5).await + }); + wait_for_queue_depth(&controller, 1).await; + let large_controller = controller.clone(); + let large_local = tokio::spawn(async move { + admit( + &large_controller, + "large-local", + InferenceRequestTier::Local, + 7, + ) + .await + }); + wait_for_queue_depth(&controller, 2).await; + + // Smaller local requests pass the large one until it has waited long enough. + for turn in 0..ADMISSION_STARVATION_BOUND_TURNS { + let small = tokio::time::timeout( + WAIT, + admit( + &controller, + &format!("small-{turn}"), + InferenceRequestTier::Local, + 4, + ), + ) + .await + .unwrap_or_else(|_| panic!("small local request {turn} was held")) + .expect("small local admission succeeded"); + drop(small); + } + + // Now the pool drains for the large local request, not for the older + // mesh one: a small local newcomer waits. Had it been admitted, its + // tokens would keep the large request out of the drained pool. + let small_controller = controller.clone(); + let late_small = tokio::spawn(async move { + admit( + &small_controller, + "late-small", + InferenceRequestTier::Local, + 4, + ) + .await + }); + wait_for_queue_depth(&controller, 3).await; + drop(active); + let large = tokio::time::timeout(WAIT, large_local) + .await + .expect("the large local request is admitted once the pool drains") + .unwrap() + .expect("large local admission succeeded"); + drop(large); + for waiter in [late_small, mesh_waiter] { + let admitted = tokio::time::timeout(WAIT, waiter) + .await + .expect("the remaining waiters are admitted") + .unwrap() + .expect("admission succeeded"); + drop(admitted); + } +} + +#[tokio::test] +async fn a_local_request_is_admitted_ahead_of_a_long_mesh_queue() { + const MESH_WAITERS: usize = 40; + let controller = controller(1, 64, 1_000, 0); + let active = admit(&controller, "active", InferenceRequestTier::Local, 1) + .await + .expect("the lane is free"); + // Each mesh request holds the lane until the test releases it. + let (admitted_tx, mut admitted_rx) = tokio::sync::mpsc::unbounded_channel(); + let mut releases = Vec::new(); + for index in 0..MESH_WAITERS { + let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>(); + releases.push(Some(release_tx)); + let (mesh_controller, admitted_tx) = (controller.clone(), admitted_tx.clone()); + tokio::spawn(async move { + let permit = admit( + &mesh_controller, + &format!("mesh-{index}"), + InferenceRequestTier::Mesh, + 1, + ) + .await; + // Only a request that holds the lane counts as admitted. + let _ = admitted_tx.send( + permit + .as_ref() + .map(|_| index) + .map_err(|error| error.body().error.message.clone()), + ); + let _ = release_rx.await; + drop(permit); + }); + } + wait_for_queue_depth(&controller, MESH_WAITERS).await; + + // Serve the mesh queue until every remaining mesh waiter is past the + // starvation bound, keeping the last one admitted on the lane. + drop(active); + let bound = usize::try_from(ADMISSION_STARVATION_BOUND_TURNS).unwrap(); + let mut on_lane = None; + for served in 0..bound { + let index = tokio::time::timeout(WAIT, admitted_rx.recv()) + .await + .expect("a mesh request is admitted") + .unwrap() + .expect("mesh admission succeeded"); + if served + 1 < bound { + releases[index].take().unwrap().send(()).unwrap(); + } else { + on_lane = Some(index); + } + } + + // A local request that arrives now goes next, not after the mesh queue. + let local_controller = controller.clone(); + let local = tokio::spawn(async move { + admit(&local_controller, "local", InferenceRequestTier::Local, 1).await + }); + wait_for_queue_depth(&controller, MESH_WAITERS - bound + 1).await; + releases[on_lane.unwrap()].take().unwrap().send(()).unwrap(); + let local = tokio::time::timeout(WAIT, local) + .await + .expect("the local request is admitted next") + .unwrap() + .expect("local admission succeeded"); + assert!( + admitted_rx.try_recv().is_err(), + "no mesh request went first" + ); + drop(local); + for release in releases.into_iter().flatten() { + let _ = release.send(()); + } +} + +/// Which waiter one admission wave went to. +enum Wave { + Mesh(T), + Local(T), +} + +#[tokio::test] +async fn a_mesh_request_passed_over_by_local_ones_is_admitted_in_bounded_time() { + let controller = controller(1, 8, 1_000, 0); + let mut on_lane = admit(&controller, "active", InferenceRequestTier::Local, 1) + .await + .expect("the lane is free"); + let mesh_controller = controller.clone(); + let mut mesh = tokio::spawn(async move { + admit(&mesh_controller, "mesh", InferenceRequestTier::Mesh, 1).await + }); + wait_for_queue_depth(&controller, 1).await; + + // A steady stream of local requests: one is always waiting with the mesh one. + let limit = 2 * PRIORITY_AGING_TURNS + 1; + for passed in 0..=limit { + let local_controller = controller.clone(); + let mut local = tokio::spawn(async move { + admit( + &local_controller, + &format!("local-{passed}"), + InferenceRequestTier::Local, + 1, + ) + .await + }); + wait_for_queue_depth(&controller, 2).await; + drop(on_lane); + let wave = tokio::time::timeout(WAIT, async { + tokio::select! { + admitted = &mut mesh => Wave::Mesh(admitted), + admitted = &mut local => Wave::Local(admitted), + } + }) + .await + .unwrap_or_else(|_| panic!("nobody was admitted in wave {passed}")); + match wave { + Wave::Mesh(admitted) => { + let mesh = admitted.unwrap().expect("mesh admission succeeded"); + assert!( + passed >= 2 * PRIORITY_AGING_TURNS, + "mesh went early after {passed}" + ); + drop(mesh); + let local = tokio::time::timeout(WAIT, &mut local) + .await + .expect("the waiting local request follows") + .unwrap() + .expect("local admission succeeded"); + drop(local); + return; + } + Wave::Local(admitted) => { + on_lane = admitted.unwrap().expect("local admission succeeded"); + } + } + assert!(passed < limit, "mesh was never admitted"); + } +} + +/// A `mesh` waiter elected while a bigger `local` waiter did not fit loses +/// the lane once a release makes room for the `local` one. +#[tokio::test] +async fn a_local_waiter_that_fits_after_a_release_goes_before_an_elected_mesh_one() { + let controller = controller(1, 8, 10, 0); + let active = admit(&controller, "active", InferenceRequestTier::Local, 6) + .await + .expect("the lane is free"); + let mesh_controller = controller.clone(); + let mesh_waiter = tokio::spawn(async move { + admit(&mesh_controller, "mesh", InferenceRequestTier::Mesh, 2).await + }); + // The mesh request queues first, so it is waiter 0. + wait_for_queue_depth(&controller, 1).await; + let local_controller = controller.clone(); + let local_waiter = tokio::spawn(async move { + admit(&local_controller, "local", InferenceRequestTier::Local, 5).await + }); + // Both wait, and the mesh waiter (id 0) is elected: only it fits the + // tokens left beside the active request. + let queue = controller.generation_limit.admission_queue(); + tokio::time::timeout(WAIT, async { + while queue.election_for_test() != (2, Some(0)) { + tokio::task::yield_now().await; + } + }) + .await + .expect("the mesh waiter was elected with both waiting"); + + drop(active); + let local = tokio::time::timeout(WAIT, local_waiter) + .await + .expect("local admitted") + .unwrap() + .expect("local admission succeeded"); + assert!(!mesh_waiter.is_finished()); + drop(local); + let mesh = tokio::time::timeout(WAIT, mesh_waiter) + .await + .expect("mesh admitted after local") + .unwrap() + .expect("mesh admission succeeded"); + drop(mesh); +} diff --git a/skippy/crates/skippy-serving/src/frontend/embedded_generation.rs b/skippy/crates/skippy-serving/src/frontend/embedded_generation.rs index 285453bc39..e0a00be8ee 100644 --- a/skippy/crates/skippy-serving/src/frontend/embedded_generation.rs +++ b/skippy/crates/skippy-serving/src/frontend/embedded_generation.rs @@ -217,6 +217,7 @@ impl StageOpenAiBackend { tokens: chunk, request_id, session_id, + request_class: request.ids.request_class(), })?; message.state.set_split_dflash_unattended_rows(unattended); let stage0_timer = PhaseTimer::start(); @@ -796,6 +797,7 @@ impl StageOpenAiBackend { sampling: wire_sampling.clone(), sideband_capacity: skippy_protocol::binary::MAX_STAGE_SIDEBAND_VALUES, native_mtp_draft_tokens: request.native_mtp_draft_tokens(), + request_class: request.ids.request_class(), })?; decode_message.set_split_dflash(request.split_dflash()); let mut native_mtp = NativeMtpVerifier::default(); @@ -1340,6 +1342,7 @@ impl StageOpenAiBackend { tokens: &input_tokens, sampling: wire_sampling.clone(), native_mtp_draft_tokens: request.native_mtp_draft_tokens(), + request_class: request.ids.request_class(), })?; message.state.set_split_dflash(request.split_dflash()); let dispatched = self.dispatch_embedded_stage_message( @@ -1740,6 +1743,7 @@ impl StageOpenAiBackend { tokens: &verify_inputs, sampling: wire_sampling.clone(), native_mtp_draft_tokens: request.native_mtp_draft_tokens(), + request_class: request.ids.request_class(), })?; message.state.set_split_dflash(request.split_dflash()); let verify = self.execute_embedded_stage_message( diff --git a/skippy/crates/skippy-serving/src/frontend/embedded_generation/lifecycle.rs b/skippy/crates/skippy-serving/src/frontend/embedded_generation/lifecycle.rs index 6be84e1a5a..8ae98a5305 100644 --- a/skippy/crates/skippy-serving/src/frontend/embedded_generation/lifecycle.rs +++ b/skippy/crates/skippy-serving/src/frontend/embedded_generation/lifecycle.rs @@ -16,6 +16,7 @@ use crate::frontend::{ generation_receipt::GenerationLifecycleState, speculative::{InferenceSpeculativeStats, SpeculativeDecodeConfig}, util::{openai_backend_error, openai_io_error}, + wire_messages::stop_message, }; use crate::runtime_state::RuntimeState; @@ -24,14 +25,10 @@ use crate::runtime_state::RuntimeState; /// discarded. fn stop_lane_session( stream: &mut TcpStream, - request_id: u64, - session_id: u64, + stop: &StageWireMessage, draft_owed: bool, ) -> std::io::Result<()> { - write_stage_message( - &mut *stream, - &StageWireMessage::stop_with_identity(request_id, session_id), - )?; + write_stage_message(&mut *stream, stop)?; let mut kind = recv_reply(&mut *stream)?.kind; if draft_owed && kind == WireReplyKind::PredictedTokens { kind = recv_reply(&mut *stream)?.kind; @@ -52,8 +49,7 @@ fn stop_lane_session( fn settle_lane_in_background( lane_pool: Arc, lane: PersistentStageLane, - request_id: u64, - session_id: u64, + stop: StageWireMessage, ) { let lane_id = lane.id; let pool = Arc::clone(&lane_pool); @@ -61,7 +57,7 @@ fn settle_lane_in_background( .name("skippy-lane-settle".to_string()) .spawn(move || { let mut lane = lane; - match stop_lane_session(&mut lane.stream, request_id, session_id, true) { + match stop_lane_session(&mut lane.stream, &stop, true) { Ok(()) => pool.return_lane(lane), Err(error) => { tracing::debug!( @@ -564,8 +560,11 @@ impl StageOpenAiBackend { Some(pool) => settle_lane_in_background( pool, lane, - request.ids.request_id, - request.ids.session_id, + stop_message( + request.ids.request_id, + request.ids.session_id, + request.ids.request_class(), + ), ), None => { let lane_id = lane.id; @@ -578,8 +577,11 @@ impl StageOpenAiBackend { let stop_result = stop_lane_session( &mut lane.stream, - request.ids.request_id, - request.ids.session_id, + &stop_message( + request.ids.request_id, + request.ids.session_id, + request.ids.request_class(), + ), false, ); self.drop_embedded_runtime_session(request, session_key, SessionEnd::Completed); @@ -707,19 +709,36 @@ mod tests { #[test] fn stopping_a_lane_drains_an_owed_draft_reply_before_the_ack() { let mut stream = stop_peer(&[WireReplyKind::PredictedTokens, WireReplyKind::Ack]); - stop_lane_session(&mut stream, 1, 2, true).unwrap(); + stop_lane_session( + &mut stream, + &StageWireMessage::stop_with_identity(1, 2), + true, + ) + .unwrap(); } #[test] fn stopping_a_lane_accepts_an_ack_when_the_draft_went_elsewhere() { let mut stream = stop_peer(&[WireReplyKind::Ack]); - stop_lane_session(&mut stream, 1, 2, true).unwrap(); + stop_lane_session( + &mut stream, + &StageWireMessage::stop_with_identity(1, 2), + true, + ) + .unwrap(); } #[test] fn stopping_a_lane_with_no_owed_draft_refuses_a_draft_reply() { let mut stream = stop_peer(&[WireReplyKind::PredictedTokens, WireReplyKind::Ack]); - assert!(stop_lane_session(&mut stream, 1, 2, false).is_err()); + assert!( + stop_lane_session( + &mut stream, + &StageWireMessage::stop_with_identity(1, 2), + false + ) + .is_err() + ); } fn ngram_config() -> SpeculativeDecodeConfig { diff --git a/skippy/crates/skippy-serving/src/frontend/generation.rs b/skippy/crates/skippy-serving/src/frontend/generation.rs index d069ecc635..e50024601e 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation.rs @@ -10,6 +10,7 @@ mod persistent_lanes; mod queue; mod request_defaults; mod server; +mod service_estimate; mod streaming; mod timeouts; mod tool_call_stream; @@ -48,6 +49,7 @@ pub(in crate::frontend) use incremental_text::recorded_fixture; pub(in crate::frontend) use parsing::*; pub(in crate::frontend) use persistent_lanes::*; pub(in crate::frontend) use queue::*; +pub(in crate::frontend) use service_estimate::*; pub(in crate::frontend) use streaming::*; pub(in crate::frontend) use timeouts::*; pub(in crate::frontend) use types::*; diff --git a/skippy/crates/skippy-serving/src/frontend/generation/cache_hints.rs b/skippy/crates/skippy-serving/src/frontend/generation/cache_hints.rs index c68ce0f8f4..57b043c9e5 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/cache_hints.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/cache_hints.rs @@ -3,6 +3,8 @@ use crate::frontend::util::now_unix_millis; use crate::frontend::util::stable_wire_id; use skippy_inference_api::CompletionRequest; use skippy_inference_api::InferenceExecutionScope; +use skippy_inference_api::InferenceRequestClass; +use skippy_inference_api::InferenceRequestTier; use skippy_inference_api::generation::GenerationRequest; use skippy_protocol::binary::StageReplyStats; use std::sync::OnceLock; @@ -118,6 +120,37 @@ impl InferenceGenerationIds { self } + /// Partition native sessions and every cache identity by the request's + /// tier and private flag. The default class (local, not private) keeps + /// identities unchanged, so standalone Skippy behaves as before. + pub(in crate::frontend) fn with_request_class(mut self, class: InferenceRequestClass) -> Self { + if let Some(partition) = class.cache_partition() { + self.session_id = stable_wire_id(&[ + b"tiered-inference-session", + partition.as_bytes(), + &self.session_id.to_le_bytes(), + ]); + self.session_label = format!("{partition}-{}", self.session_label); + self.request_id = stable_wire_id(&[ + b"tiered-inference-request", + partition.as_bytes(), + &self.request_id.to_le_bytes(), + ]); + } + self.cache.request_class = class; + self + } + + /// The tier this request is served at. + pub(in crate::frontend) fn request_tier(&self) -> InferenceRequestTier { + self.cache.request_class.tier() + } + + /// The tier and cache partition this request is served in. + pub(in crate::frontend) fn request_class(&self) -> InferenceRequestClass { + self.cache.request_class + } + pub(in crate::frontend) fn request_id_string(&self) -> String { self.request_id.to_string() } @@ -191,6 +224,60 @@ mod tests { ); } + #[test] + /// Each tier and the private partition get their own sessions and cache + /// namespace; the default local class keeps the unpartitioned identities. + fn request_classes_partition_sessions_and_cache() { + let make = |class| { + InferenceGenerationIds::new_with_trust( + InferenceCacheHints { + prompt_cache_key: Some("same-key".into()), + ..Default::default() + }, + Some("same-agent"), + true, + None, + ) + .with_request_class(class) + }; + let local = make(InferenceRequestClass::default()); + let unclassed = InferenceGenerationIds::new_with_trust( + InferenceCacheHints { + prompt_cache_key: Some("same-key".into()), + ..Default::default() + }, + Some("same-agent"), + true, + None, + ); + assert_eq!(local.session_id, unclassed.session_id); + assert_eq!(local.cache.namespace(), unclassed.cache.namespace()); + + let classes = InferenceRequestTier::ALL.into_iter().flat_map(|tier| { + [false, true].map(|private| make(InferenceRequestClass::new(tier, private))) + }); + let ids = classes.collect::>(); + let sessions = ids + .iter() + .map(|ids| ids.session_id) + .collect::>(); + let namespaces = ids + .iter() + .map(|ids| ids.cache.namespace()) + .collect::>(); + assert_eq!(sessions.len(), ids.len()); + assert_eq!(namespaces.len(), ids.len()); + let mesh = make(InferenceRequestClass::new( + InferenceRequestTier::Mesh, + false, + )); + assert_eq!(mesh.request_tier(), InferenceRequestTier::Mesh); + assert_eq!( + mesh.cache.namespace().as_deref(), + Some("tier:mesh:openai:prompt_cache_key:same-key") + ); + } + #[test] fn trusted_agent_session_reuses_native_session_but_not_request_id() { let first = InferenceGenerationIds::new_with_trust( @@ -271,6 +358,7 @@ pub(in crate::frontend) struct InferenceCacheHints { pub(in crate::frontend) prompt_cache_key: Option, pub(in crate::frontend) prompt_cache_retention: Option, execution_scope: Option, + request_class: InferenceRequestClass, } impl InferenceCacheHints { @@ -288,6 +376,7 @@ impl InferenceCacheHints { .map(prompt_cache_retention_label) .map(ToString::to_string), execution_scope: None, + request_class: InferenceRequestClass::default(), } } @@ -305,6 +394,7 @@ impl InferenceCacheHints { .map(prompt_cache_retention_label) .map(ToString::to_string), execution_scope: None, + request_class: InferenceRequestClass::default(), } } @@ -315,13 +405,14 @@ impl InferenceCacheHints { .prompt_cache_key .as_ref() .map(|key| format!("openai:prompt_cache_key:{key}")); - match self.execution_scope { + let namespace = match self.execution_scope { Some(scope) => Some(format!( "execution:{scope}:{}", namespace.unwrap_or_default() )), None => namespace, - } + }; + self.request_class.cache_namespace(namespace) } } diff --git a/skippy/crates/skippy-serving/src/frontend/generation/execution.rs b/skippy/crates/skippy-serving/src/frontend/generation/execution.rs index bd08c33c29..1f07d7a327 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/execution.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/execution.rs @@ -20,6 +20,7 @@ pub(in crate::frontend) fn generation_ids( frontend_request_id, ) .with_execution_scope(context.execution_scope()) + .with_request_class(context.request_class()) } /// Run blocking inference while owning its permit and full request context. diff --git a/skippy/crates/skippy-serving/src/frontend/generation/queue.rs b/skippy/crates/skippy-serving/src/frontend/generation/queue.rs index 22886d5687..ca076f48dc 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/queue.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/queue.rs @@ -17,11 +17,14 @@ use serde_json::json; use skippy_inference_api::CancellationToken; use skippy_inference_api::InferenceError; use skippy_inference_api::InferenceErrorKind; +use skippy_inference_api::InferenceRequestTier; use skippy_inference_api::InferenceResult; use skippy_protocol::StageConfig; -use skippy_scheduler::{CacheAffinity, CacheAwareCandidate, order_cache_aware_candidates}; +use skippy_scheduler::{ + CacheAffinity, CacheAwareCandidate, PriorityPassovers, order_cache_aware_candidates, +}; use std::collections::BTreeMap; -use std::collections::VecDeque; +use std::collections::BTreeSet; use std::sync::Arc; use std::sync::Mutex; use std::sync::atomic::AtomicUsize; @@ -32,8 +35,6 @@ use tokio::sync::Notify; use tokio::sync::OwnedSemaphorePermit; use tokio::sync::Semaphore; -const SERVICE_RATE_EWMA_ALPHA: f64 = 0.25; -const SERVICE_RATE_WINDOW: usize = 64; const ADMISSION_CACHE_AGING_COST_PER_TURN: u64 = 4_096; /// How many admissions the oldest waiter may be bypassed before the queue stops @@ -49,7 +50,8 @@ const ADMISSION_CACHE_AGING_COST_PER_TURN: u64 = 4_096; /// request fits an empty pool (`claim_or_enqueue` rejects impossible requests up /// front), so draining always makes progress. The bound trades a little /// throughput and cache locality for a hard ceiling on bypasses before drain -/// reservation begins. +/// reservation begins. Higher tiers are not held: the bound caps bypasses by +/// the waiter's own and lower tiers. pub(in crate::frontend) const ADMISSION_STARVATION_BOUND_TURNS: u64 = 32; pub(in crate::frontend) type GenerationCacheAffinityRefresh = @@ -59,6 +61,7 @@ pub(in crate::frontend) type GenerationCacheAffinityRefresh = pub(in crate::frontend) struct GenerationAdmissionScheduling { prompt_tokens: Arc<[i32]>, refresh_affinity: GenerationCacheAffinityRefresh, + tier: InferenceRequestTier, } impl GenerationAdmissionScheduling { @@ -69,8 +72,20 @@ impl GenerationAdmissionScheduling { Self { prompt_tokens, refresh_affinity, + tier: InferenceRequestTier::default(), } } + + /// Rank this work at `tier`: higher tiers are admitted first, and lower + /// tiers never take a higher tier's room in the waiting queue. + pub(in crate::frontend) fn with_tier(mut self, tier: InferenceRequestTier) -> Self { + self.tier = tier; + self + } + + pub(in crate::frontend) fn tier(&self) -> InferenceRequestTier { + self.tier + } } impl Default for GenerationAdmissionScheduling { @@ -78,6 +93,7 @@ impl Default for GenerationAdmissionScheduling { Self { prompt_tokens: Arc::from([]), refresh_affinity: Arc::new(CacheAffinity::default), + tier: InferenceRequestTier::default(), } } } @@ -88,16 +104,155 @@ struct GenerationAdmissionWaiter { token_budget_request: GenerationTokenBudgetRequest, enqueued_turn: u64, order: u64, + /// [`PriorityPassovers::mark`] when the waiter entered the room. + passover_mark: u64, +} + +/// A waiter as one election sees it. +struct WaiterSnapshot { + id: u64, + waiter: GenerationAdmissionWaiter, + /// How many higher-tier waiters were admitted while it waited. + passed_over: u64, +} + +/// What the anti-starvation head-of-line reservation asks of the next +/// election. +enum SeniorHold { + /// Hand the lane to this senior waiter, which fits now, so a higher + /// cache-value newcomer cannot re-occupy the drained pool ahead of it. + Select(u64), + /// A senior waiter of this tier does not fit yet: only higher tiers may + /// pass it, so the pool drains for it rather than letting a steady + /// stream of smaller requests of its own or a lower tier keep passing it. + HoldAtOrBelow(InferenceRequestTier), + None, +} + +/// Each tier's oldest waiter (smallest enqueued turn, then smallest order) +/// is the one at risk in that tier. From the highest tier down, the first +/// that has been bypassed `ADMISSION_STARVATION_BOUND_TURNS` times gets the +/// reservation. A higher tier is never held for a lower one: a senior is +/// handed the lane only when no higher-tier waiter fits, and a lower tier's +/// old waiter cannot remove a higher tier's protection. Across tiers, aging +/// protects only a lower-tier waiter that fits: one that does not fit waits +/// until higher-tier load leaves it room, or until its deadline. +fn senior_hold( + waiters: &[WaiterSnapshot], + turn: u64, + token_budget: &GenerationTokenBudget, +) -> InferenceResult { + let mut seniors = BTreeMap::::new(); + for snapshot in waiters { + let senior = seniors + .entry(snapshot.waiter.scheduling.tier) + .or_insert(snapshot); + let age = + |snapshot: &WaiterSnapshot| (snapshot.waiter.enqueued_turn, snapshot.waiter.order); + if age(snapshot) < age(senior) { + *senior = snapshot; + } + } + let mut higher_tier_fits = false; + for (tier, senior) in seniors.into_iter().rev() { + if turn.saturating_sub(senior.waiter.enqueued_turn) >= ADMISSION_STARVATION_BOUND_TURNS { + if !token_budget.can_reserve_now(senior.waiter.token_budget_request)? { + return Ok(SeniorHold::HoldAtOrBelow(tier)); + } + if !higher_tier_fits { + return Ok(SeniorHold::Select(senior.id)); + } + } + higher_tier_fits = + higher_tier_fits || tier_has_fitting_waiter(waiters, tier, token_budget)?; + } + Ok(SeniorHold::None) +} + +fn tier_has_fitting_waiter( + waiters: &[WaiterSnapshot], + tier: InferenceRequestTier, + token_budget: &GenerationTokenBudget, +) -> InferenceResult { + for snapshot in waiters { + if snapshot.waiter.scheduling.tier == tier + && token_budget.can_reserve_now(snapshot.waiter.token_budget_request)? + { + return Ok(true); + } + } + Ok(false) } #[derive(Default)] struct GenerationAdmissionQueueState { turn: u64, + /// Admissions by tier priority, which age the waiters they pass over. + passovers: PriorityPassovers, next_id: u64, + /// Advances whenever the waiting set changes, so an election run on an + /// older snapshot is not published. + revision: u64, selected_id: Option, + /// The published winner's tier and the waiters that fit when it won. + selection_basis: Option, waiters: BTreeMap, } +struct SelectionBasis { + tier: InferenceRequestTier, + fit: BTreeSet, +} + +/// One election's view of the waiting room. +struct ElectionSnapshot { + revision: u64, + turn: u64, + waiters: Vec, +} + +impl GenerationAdmissionQueueState { + /// A published winner is stale once a higher-tier waiter that did not + /// fit at its election fits now: a release can make room for it. + fn selection_is_stale(&self, token_budget: &GenerationTokenBudget) -> InferenceResult { + let Some(basis) = self.selection_basis.as_ref() else { + return Ok(false); + }; + for (id, waiter) in &self.waiters { + if waiter.scheduling.tier > basis.tier + && !basis.fit.contains(id) + && token_budget.can_reserve_now(waiter.token_budget_request)? + { + return Ok(true); + } + } + Ok(false) + } + + fn clear_selection(&mut self) { + self.selected_id = None; + self.selection_basis = None; + } + + fn snapshot(&self) -> ElectionSnapshot { + ElectionSnapshot { + revision: self.revision, + turn: self.turn, + waiters: self + .waiters + .iter() + .map(|(id, waiter)| WaiterSnapshot { + id: *id, + waiter: waiter.clone(), + passed_over: self + .passovers + .passed_over(waiter.scheduling.tier.priority(), waiter.passover_mark), + }) + .collect(), + } + } +} + /// Scheduler-owned waiting room in front of the finite native lane pool. /// /// Tokenized prompts enter this queue before acquiring a generation lane, so @@ -143,7 +298,9 @@ impl GenerationAdmissionQueue { { return Ok(GenerationAdmissionClaim::Acquired(resources)); } - let reservation = reserve_generation_queue(generation_queue_depth, generation_queue_limit) + let reservation = tier_has_queue_room(&state, scheduling.tier, generation_queue_limit) + .then(|| reserve_generation_queue(generation_queue_depth, usize::MAX)) + .flatten() .ok_or_else(generation_queue_full_error)?; let id = state.next_id; state.next_id = state.next_id.saturating_add(1); @@ -151,7 +308,9 @@ impl GenerationAdmissionQueue { // Claiming a lane or entering the waiting room is one queue-locked operation. A lane that // becomes free after the failed fast claim cannot be taken by a newer arrival before this // waiter is visible. - state.selected_id = None; + state.clear_selection(); + state.revision = state.revision.wrapping_add(1); + let passover_mark = state.passovers.mark(scheduling.tier.priority()); state.waiters.insert( id, GenerationAdmissionWaiter { @@ -159,6 +318,7 @@ impl GenerationAdmissionQueue { token_budget_request, enqueued_turn: turn, order: id, + passover_mark, }, ); drop(state); @@ -174,6 +334,16 @@ impl GenerationAdmissionQueue { )) } + /// The number of waiters and the published winner. + #[cfg(test)] + pub(in crate::frontend) fn election_for_test(&self) -> (usize, Option) { + let state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + (state.waiters.len(), state.selected_id) + } + pub(in crate::frontend) fn notify_lane_available(&self) { self.changed.notify_waiters(); } @@ -189,92 +359,40 @@ impl GenerationAdmissionQueue { .election .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - // Refreshing affinity consults the prefix cache and can be more - // expensive than queue bookkeeping. Snapshot under the queue lock, - // then release it before crossing that subsystem boundary. - let (turn, waiters) = { - let state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some(selected_id) = state.selected_id { - return Ok(Some(selected_id)); - } - ( - state.turn, - state - .waiters - .iter() - .map(|(id, waiter)| (*id, waiter.clone())) - .collect::>(), - ) - }; - // Anti-starvation head-of-line reservation. The oldest waiter (smallest - // enqueued turn, then smallest order) is the one at risk: once it has - // been bypassed ADMISSION_STARVATION_BOUND_TURNS times, reserve the pool - // for it instead of letting a steady stream of smaller, currently-fitting - // requests keep passing it. If it now fits, hand it the lane directly so a - // higher cache-value newcomer cannot re-occupy the drained pool ahead of - // it; otherwise select nobody so active reservations keep draining. - if let Some((senior_id, senior)) = waiters - .iter() - .min_by_key(|(_, waiter)| (waiter.enqueued_turn, waiter.order)) - && turn.saturating_sub(senior.enqueued_turn) >= ADMISSION_STARVATION_BOUND_TURNS - { - let senior_id = *senior_id; - if !token_budget.can_reserve_now(senior.token_budget_request)? { - return Ok(None); - } + loop { + // Refreshing affinity consults the prefix cache and can be more + // expensive than queue bookkeeping. Snapshot under the queue + // lock, then release it before crossing that subsystem boundary. + let snapshot = { + let mut state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(selected_id) = state.selected_id { + if !state.selection_is_stale(token_budget)? { + return Ok(Some(selected_id)); + } + state.clear_selection(); + } + state.snapshot() + }; + let fit = fitting_waiters(&snapshot.waiters, token_budget)?; + let winner = elect(&snapshot, &fit, token_budget)?; let mut state = self .state .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - if state.selected_id.is_none() && state.waiters.contains_key(&senior_id) { - state.selected_id = Some(senior_id); + // A waiter that arrived or left during the election was not + // ranked: elect again from the current set. + if state.revision != snapshot.revision { + continue; } - return Ok(state.selected_id); - } - let mut eligible_waiters = Vec::with_capacity(waiters.len()); - for (id, waiter) in waiters { - if token_budget.can_reserve_now(waiter.token_budget_request)? { - eligible_waiters.push((id, waiter)); + if let Some((id, tier)) = winner { + state.selected_id = Some(id); + state.selection_basis = Some(SelectionBasis { tier, fit }); } + return Ok(state.selected_id); } - let affinities = eligible_waiters - .iter() - .map(|(_, waiter)| (waiter.scheduling.refresh_affinity)()) - .collect::>(); - let selected_id = order_cache_aware_candidates( - eligible_waiters - .iter() - .map(|(_, waiter)| waiter) - .zip(affinities.iter()) - .enumerate() - .map(|(index, (waiter, affinity))| CacheAwareCandidate { - index, - priority: 0, - affinity, - prompt_tokens: &waiter.scheduling.prompt_tokens, - enqueued_turn: waiter.enqueued_turn, - order: waiter.order, - }), - turn, - ADMISSION_CACHE_AGING_COST_PER_TURN, - true, - ) - .first() - .and_then(|index| eligible_waiters.get(*index).map(|(id, _)| id)) - .copied(); - let mut state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - if state.selected_id.is_none() - && selected_id.is_some_and(|id| state.waiters.contains_key(&id)) - { - state.selected_id = selected_id; - } - Ok(state.selected_id) } fn remove(&self, id: u64) -> bool { @@ -284,8 +402,11 @@ impl GenerationAdmissionQueue { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); let removed = state.waiters.remove(&id).is_some(); + if removed { + state.revision = state.revision.wrapping_add(1); + } if state.selected_id == Some(id) { - state.selected_id = None; + state.clear_selection(); } removed }; @@ -295,20 +416,125 @@ impl GenerationAdmissionQueue { removed } - fn complete_selection(&self, id: u64) { + /// Take a lane and its tokens for waiter `id` if it is the current + /// winner. Confirming the election and claiming happen under one lock, + /// so a waiter that arrives after the election is not passed by it. + fn claim_if_selected( + &self, + id: u64, + generation_limit: Arc, + token_budget: &Arc, + token_budget_request: GenerationTokenBudgetRequest, + ) -> InferenceResult> { + if self.selected_waiter(token_budget)? != Some(id) { + return Ok(None); + } let mut state = self .state .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - if state.waiters.remove(&id).is_some() { + if state.selected_id != Some(id) { + return Ok(None); + } + if state.selection_is_stale(token_budget)? { + // Elect again, this waiter included. + state.clear_selection(); + drop(state); + self.changed.notify_waiters(); + return Ok(None); + } + let Some(resources) = + try_acquire_generation_resources(generation_limit, token_budget, token_budget_request)? + else { + return Ok(None); + }; + Self::complete_selection(&mut state, id); + drop(state); + self.changed.notify_waiters(); + Ok(Some(resources)) + } + + fn complete_selection(state: &mut GenerationAdmissionQueueState, id: u64) { + if let Some(waiter) = state.waiters.remove(&id) { + state.revision = state.revision.wrapping_add(1); state.turn = state.turn.saturating_add(1); + state + .passovers + .record_selection(waiter.scheduling.tier.priority()); } if state.selected_id == Some(id) { - state.selected_id = None; + state.clear_selection(); } } } +/// The waiters whose token request fits the budget now. +fn fitting_waiters( + waiters: &[WaiterSnapshot], + token_budget: &GenerationTokenBudget, +) -> InferenceResult> { + let mut fit = BTreeSet::new(); + for snapshot in waiters { + if token_budget.can_reserve_now(snapshot.waiter.token_budget_request)? { + fit.insert(snapshot.id); + } + } + Ok(fit) +} + +/// The waiter the next free lane goes to, with its tier. +fn elect( + snapshot: &ElectionSnapshot, + fit: &BTreeSet, + token_budget: &GenerationTokenBudget, +) -> InferenceResult> { + let tier_of = |id: u64| { + snapshot + .waiters + .iter() + .find(|candidate| candidate.id == id) + .map(|candidate| (id, candidate.waiter.scheduling.tier)) + }; + let held_for = match senior_hold(&snapshot.waiters, snapshot.turn, token_budget)? { + SeniorHold::Select(senior_id) => return Ok(tier_of(senior_id)), + SeniorHold::HoldAtOrBelow(tier) => Some(tier), + SeniorHold::None => None, + }; + let eligible_waiters = snapshot + .waiters + .iter() + .filter(|candidate| { + fit.contains(&candidate.id) + && held_for.is_none_or(|tier| candidate.waiter.scheduling.tier > tier) + }) + .collect::>(); + let affinities = eligible_waiters + .iter() + .map(|candidate| (candidate.waiter.scheduling.refresh_affinity)()) + .collect::>(); + let winner = order_cache_aware_candidates( + eligible_waiters + .iter() + .zip(affinities.iter()) + .enumerate() + .map(|(index, (candidate, affinity))| CacheAwareCandidate { + index, + priority: candidate.waiter.scheduling.tier.priority(), + affinity, + prompt_tokens: &candidate.waiter.scheduling.prompt_tokens, + enqueued_turn: candidate.waiter.enqueued_turn, + order: candidate.waiter.order, + passed_over: candidate.passed_over, + }), + snapshot.turn, + ADMISSION_CACHE_AGING_COST_PER_TURN, + true, + ) + .first() + .and_then(|index| eligible_waiters.get(*index).map(|candidate| candidate.id)); + Ok(winner.and_then(tier_of)) +} + pub(in crate::frontend) enum GenerationAdmissionClaim { Acquired(GenerationAdmissionResources), Queued(GenerationAdmissionQueueLease), @@ -348,16 +574,13 @@ impl GenerationAdmissionQueueLease { let token_released = self.token_budget.release_notification().notified(); tokio::pin!(token_released); token_released.as_mut().enable(); - if self.queue.selected_waiter(&self.token_budget)? == Some(self.id) - && let Some(resources) = try_acquire_generation_resources( - generation_limit.clone(), - &self.token_budget, - self.token_budget_request, - )? - { - self.queue.complete_selection(self.id); + if let Some(resources) = self.queue.claim_if_selected( + self.id, + generation_limit.clone(), + &self.token_budget, + self.token_budget_request, + )? { self.reservation.take(); - self.queue.changed.notify_waiters(); return Ok(resources); } if let Some(deadline) = deadline { @@ -413,229 +636,6 @@ impl Drop for GenerationAdmissionQueueLease { } } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(in crate::frontend) struct GenerationAdmissionWork { - pub(in crate::frontend) prompt_tokens: u64, - pub(in crate::frontend) decode_tokens: u64, -} - -impl GenerationAdmissionWork { - pub(in crate::frontend) fn new(prompt_tokens: usize, decode_tokens: u32) -> Self { - Self { - prompt_tokens: u64::try_from(prompt_tokens).unwrap_or(u64::MAX), - decode_tokens: u64::from(decode_tokens), - } - } -} - -#[derive(Default)] -struct GenerationServiceState { - active: GenerationAdmissionWork, - queued: GenerationAdmissionWork, - prefill_ms_per_token_ewma: Option, - decode_ms_per_token_ewma: Option, - prefill_ms_per_token_samples: VecDeque, - decode_ms_per_token_samples: VecDeque, -} - -pub(in crate::frontend) struct GenerationServiceEstimator { - concurrency: AtomicUsize, - state: Mutex, -} - -impl GenerationServiceEstimator { - pub(in crate::frontend) fn new(concurrency: usize) -> Self { - Self { - concurrency: AtomicUsize::new(concurrency.max(1)), - state: Mutex::new(GenerationServiceState::default()), - } - } - - pub(in crate::frontend) fn predicted_wait_ms(&self) -> Option { - let state = self.state.lock().ok()?; - predicted_wait_ms_for_state(&state, self.concurrency.load(Ordering::Acquire)) - } - - pub(in crate::frontend) fn estimated_prefill_ms(&self, tokens: usize) -> Option { - let state = self.state.lock().ok()?; - state - .prefill_ms_per_token_ewma - .map(|per_token| per_token * tokens as f64) - .filter(|cost| cost.is_finite() && *cost >= 0.0) - } - - pub(in crate::frontend) fn set_concurrency(&self, concurrency: usize) { - self.concurrency - .store(concurrency.max(1), Ordering::Release); - } - - pub(in crate::frontend) fn reserve_queued( - self: &Arc, - work: GenerationAdmissionWork, - ) -> GenerationQueuedWorkReservation { - let Ok(mut state) = self.state.lock() else { - return GenerationQueuedWorkReservation { - estimator: self.clone(), - work, - queued: false, - }; - }; - // Predictions include interference and unfinished requests' original - // work, so they are advisory. The queue owns capacity and deadlines. - state.queued = add_work(state.queued, work); - GenerationQueuedWorkReservation { - estimator: self.clone(), - work, - queued: true, - } - } - - pub(in crate::frontend) fn start_active( - self: &Arc, - work: GenerationAdmissionWork, - ) -> GenerationActiveWorkReservation { - if let Ok(mut state) = self.state.lock() { - state.active = add_work(state.active, work); - } - GenerationActiveWorkReservation { - estimator: self.clone(), - work, - } - } - - pub(in crate::frontend) fn observe_completed( - &self, - work: GenerationAdmissionWork, - prompt_ms: f64, - decode_ms: f64, - ) { - let Ok(mut state) = self.state.lock() else { - return; - }; - if work.prompt_tokens > 0 && prompt_ms.is_finite() && prompt_ms > 0.0 { - let sample = prompt_ms / work.prompt_tokens as f64; - state.prefill_ms_per_token_ewma = - Some(update_ewma(state.prefill_ms_per_token_ewma, sample)); - push_sample(&mut state.prefill_ms_per_token_samples, sample); - } - if work.decode_tokens > 0 && decode_ms.is_finite() && decode_ms > 0.0 { - let sample = decode_ms / work.decode_tokens as f64; - state.decode_ms_per_token_ewma = - Some(update_ewma(state.decode_ms_per_token_ewma, sample)); - push_sample(&mut state.decode_ms_per_token_samples, sample); - } - } -} - -fn predicted_wait_ms_for_state(state: &GenerationServiceState, concurrency: usize) -> Option { - let prompt_ms_per_token = conservative_ms_per_token( - state.prefill_ms_per_token_ewma, - &state.prefill_ms_per_token_samples, - ); - let decode_ms_per_token = conservative_ms_per_token( - state.decode_ms_per_token_ewma, - &state.decode_ms_per_token_samples, - ); - if prompt_ms_per_token.is_none() && decode_ms_per_token.is_none() { - return None; - } - let work = add_work(state.active, state.queued); - let prompt_ms = prompt_ms_per_token.unwrap_or(0.0) * work.prompt_tokens as f64; - let decode_ms = decode_ms_per_token.unwrap_or(0.0) * work.decode_tokens as f64; - Some((prompt_ms + decode_ms) / concurrency.max(1) as f64) -} - -pub(in crate::frontend) struct GenerationQueuedWorkReservation { - estimator: Arc, - work: GenerationAdmissionWork, - queued: bool, -} - -impl GenerationQueuedWorkReservation { - pub(in crate::frontend) fn promote(mut self) -> GenerationActiveWorkReservation { - if let Ok(mut state) = self.estimator.state.lock() { - state.queued = subtract_work(state.queued, self.work); - state.active = add_work(state.active, self.work); - } - self.queued = false; - GenerationActiveWorkReservation { - estimator: self.estimator.clone(), - work: self.work, - } - } -} - -impl Drop for GenerationQueuedWorkReservation { - fn drop(&mut self) { - if self.queued - && let Ok(mut state) = self.estimator.state.lock() - { - state.queued = subtract_work(state.queued, self.work); - } - } -} - -pub(in crate::frontend) struct GenerationActiveWorkReservation { - estimator: Arc, - work: GenerationAdmissionWork, -} - -impl Drop for GenerationActiveWorkReservation { - fn drop(&mut self) { - if let Ok(mut state) = self.estimator.state.lock() { - state.active = subtract_work(state.active, self.work); - } - } -} - -fn add_work( - left: GenerationAdmissionWork, - right: GenerationAdmissionWork, -) -> GenerationAdmissionWork { - GenerationAdmissionWork { - prompt_tokens: left.prompt_tokens.saturating_add(right.prompt_tokens), - decode_tokens: left.decode_tokens.saturating_add(right.decode_tokens), - } -} - -fn subtract_work( - left: GenerationAdmissionWork, - right: GenerationAdmissionWork, -) -> GenerationAdmissionWork { - GenerationAdmissionWork { - prompt_tokens: left.prompt_tokens.saturating_sub(right.prompt_tokens), - decode_tokens: left.decode_tokens.saturating_sub(right.decode_tokens), - } -} - -fn update_ewma(previous: Option, sample: f64) -> f64 { - previous.map_or(sample, |previous| { - previous * (1.0 - SERVICE_RATE_EWMA_ALPHA) + sample * SERVICE_RATE_EWMA_ALPHA - }) -} - -fn push_sample(samples: &mut VecDeque, sample: f64) { - if samples.len() == SERVICE_RATE_WINDOW { - samples.pop_front(); - } - samples.push_back(sample); -} - -fn conservative_ms_per_token(ewma: Option, samples: &VecDeque) -> Option { - let mut sorted = samples.iter().copied().collect::>(); - sorted.sort_by(f64::total_cmp); - let p95 = if sorted.is_empty() { - None - } else { - let index = (sorted.len() * 95).div_ceil(100).saturating_sub(1); - sorted.get(index).copied() - }; - match (ewma, p95) { - (Some(ewma), Some(p95)) => Some(ewma.max(p95)), - (Some(value), None) | (None, Some(value)) => Some(value), - (None, None) => None, - } -} #[cfg(test)] use tokio::sync::TryAcquireError; @@ -713,6 +713,23 @@ pub(in crate::frontend) async fn acquire_generation_permit_with_queue( .await } +/// Whether a request at `tier` may join the waiting room. Only waiters at the +/// same or a higher tier count against the limit, so lower-tier traffic cannot +/// fill the room ahead of a higher tier. The room holds at most one limit per +/// tier. +fn tier_has_queue_room( + state: &GenerationAdmissionQueueState, + tier: InferenceRequestTier, + generation_queue_limit: usize, +) -> bool { + state + .waiters + .values() + .filter(|waiter| waiter.scheduling.tier >= tier) + .count() + < generation_queue_limit +} + pub(in crate::frontend) fn reserve_generation_queue( generation_queue_depth: Arc, generation_queue_limit: usize, @@ -901,52 +918,3 @@ pub(in crate::frontend) fn generation_queue_timeout_error(timeout: Duration) -> ) .with_retry_after_secs(GENERATION_RETRY_AFTER_SECS) } - -#[cfg(test)] -mod service_estimator_tests { - use super::*; - - #[test] - fn high_prediction_does_not_refuse_work_accounting() { - let estimator = Arc::new(GenerationServiceEstimator::new(1)); - let work = GenerationAdmissionWork::new(100, 100); - estimator.observe_completed(work, 100.0, 100.0); - let active = estimator.start_active(work); - - assert_eq!(estimator.predicted_wait_ms(), Some(200.0)); - let queued = estimator.reserve_queued(work); - assert_eq!(estimator.predicted_wait_ms(), Some(400.0)); - drop(queued); - assert_eq!(estimator.predicted_wait_ms(), Some(200.0)); - drop(active); - assert_eq!(estimator.predicted_wait_ms(), Some(0.0)); - } - - #[test] - fn queued_and_active_work_are_released_by_raii() { - let estimator = Arc::new(GenerationServiceEstimator::new(2)); - let work = GenerationAdmissionWork::new(80, 20); - estimator.observe_completed(work, 80.0, 20.0); - let queued = estimator.reserve_queued(work); - assert_eq!(estimator.predicted_wait_ms(), Some(50.0)); - - let active = queued.promote(); - assert_eq!(estimator.predicted_wait_ms(), Some(50.0)); - drop(active); - assert_eq!(estimator.predicted_wait_ms(), Some(0.0)); - } - - #[test] - fn conservative_rate_uses_the_slower_p95_sample() { - let samples = VecDeque::from([1.0, 1.0, 1.0, 10.0]); - assert_eq!(conservative_ms_per_token(Some(1.5), &samples), Some(10.0)); - } - - #[test] - fn prefill_estimate_uses_observed_stage_rate() { - let estimator = GenerationServiceEstimator::new(1); - assert_eq!(estimator.estimated_prefill_ms(128), None); - estimator.observe_completed(GenerationAdmissionWork::new(100, 0), 25.0, 0.0); - assert_eq!(estimator.estimated_prefill_ms(40), Some(10.0)); - } -} diff --git a/skippy/crates/skippy-serving/src/frontend/generation/server.rs b/skippy/crates/skippy-serving/src/frontend/generation/server.rs index 2bb54df17d..0dc8bcb76e 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/server.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/server.rs @@ -98,6 +98,8 @@ pub struct EmbeddedOpenAiArgs { pub pipeline_decode_groups: Option, pub adaptive_generation_min_concurrency: Option, pub generation_queue_capacity: usize, + /// Percent of the KV token budget only `local`-tier requests may reserve. + pub local_kv_reserve_percent: u8, pub generation_admission_timeout_secs: u64, pub prefill_chunk_size: usize, pub prefill_chunk_policy: String, @@ -434,7 +436,11 @@ fn embedded_openai_backend_with_state_kind( let (generation_token_budget, runtime_lane_admission) = { let mut runtime = crate::runtime_state::panic_recovery::lock_runtime(&args.runtime); ( - GenerationTokenBudget::shared_for_runtime(&mut runtime, ctx_size), + GenerationTokenBudget::shared_for_runtime( + &mut runtime, + ctx_size, + args.local_kv_reserve_percent, + ), runtime.lane_admission(), ) }; diff --git a/skippy/crates/skippy-serving/src/frontend/generation/service_estimate.rs b/skippy/crates/skippy-serving/src/frontend/generation/service_estimate.rs new file mode 100644 index 0000000000..1449dd4465 --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/generation/service_estimate.rs @@ -0,0 +1,350 @@ +//! How long queued generation work is predicted to wait, from the work +//! admitted and queued and the service rate observed so far. Predictions +//! are advisory: the queue owns capacity and deadlines. + +use skippy_inference_api::InferenceRequestTier; +use std::collections::BTreeMap; +use std::collections::VecDeque; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; + +const SERVICE_RATE_EWMA_ALPHA: f64 = 0.25; +const SERVICE_RATE_WINDOW: usize = 64; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(in crate::frontend) struct GenerationAdmissionWork { + pub(in crate::frontend) prompt_tokens: u64, + pub(in crate::frontend) decode_tokens: u64, +} + +impl GenerationAdmissionWork { + pub(in crate::frontend) fn new(prompt_tokens: usize, decode_tokens: u32) -> Self { + Self { + prompt_tokens: u64::try_from(prompt_tokens).unwrap_or(u64::MAX), + decode_tokens: u64::from(decode_tokens), + } + } +} + +#[derive(Default)] +struct GenerationServiceState { + active: GenerationAdmissionWork, + /// Queued work by request tier: a request waits behind active work and + /// queued work at its own tier or higher, which is admitted first. + queued: BTreeMap, + prefill_ms_per_token_ewma: Option, + decode_ms_per_token_ewma: Option, + prefill_ms_per_token_samples: VecDeque, + decode_ms_per_token_samples: VecDeque, +} + +pub(in crate::frontend) struct GenerationServiceEstimator { + concurrency: AtomicUsize, + state: Mutex, +} + +impl GenerationServiceEstimator { + pub(in crate::frontend) fn new(concurrency: usize) -> Self { + Self { + concurrency: AtomicUsize::new(concurrency.max(1)), + state: Mutex::new(GenerationServiceState::default()), + } + } + + /// The predicted wait for a request at `tier`. + pub(in crate::frontend) fn predicted_wait_ms(&self, tier: InferenceRequestTier) -> Option { + let state = self.state.lock().ok()?; + predicted_wait_ms_for_state(&state, self.concurrency.load(Ordering::Acquire), tier) + } + + pub(in crate::frontend) fn estimated_prefill_ms(&self, tokens: usize) -> Option { + let state = self.state.lock().ok()?; + state + .prefill_ms_per_token_ewma + .map(|per_token| per_token * tokens as f64) + .filter(|cost| cost.is_finite() && *cost >= 0.0) + } + + pub(in crate::frontend) fn set_concurrency(&self, concurrency: usize) { + self.concurrency + .store(concurrency.max(1), Ordering::Release); + } + + /// Account `work` as queued for a request at `tier`. + pub(in crate::frontend) fn reserve_queued( + self: &Arc, + work: GenerationAdmissionWork, + tier: InferenceRequestTier, + ) -> GenerationQueuedWorkReservation { + let Ok(mut state) = self.state.lock() else { + return GenerationQueuedWorkReservation { + estimator: self.clone(), + work, + tier, + queued: false, + }; + }; + // Predictions include interference and unfinished requests' original + // work, so they are advisory. The queue owns capacity and deadlines. + let queued = state.queued.entry(tier).or_default(); + *queued = add_work(*queued, work); + GenerationQueuedWorkReservation { + estimator: self.clone(), + work, + tier, + queued: true, + } + } + + pub(in crate::frontend) fn start_active( + self: &Arc, + work: GenerationAdmissionWork, + ) -> GenerationActiveWorkReservation { + if let Ok(mut state) = self.state.lock() { + state.active = add_work(state.active, work); + } + GenerationActiveWorkReservation { + estimator: self.clone(), + work, + } + } + + pub(in crate::frontend) fn observe_completed( + &self, + work: GenerationAdmissionWork, + prompt_ms: f64, + decode_ms: f64, + ) { + let Ok(mut state) = self.state.lock() else { + return; + }; + if work.prompt_tokens > 0 && prompt_ms.is_finite() && prompt_ms > 0.0 { + let sample = prompt_ms / work.prompt_tokens as f64; + state.prefill_ms_per_token_ewma = + Some(update_ewma(state.prefill_ms_per_token_ewma, sample)); + push_sample(&mut state.prefill_ms_per_token_samples, sample); + } + if work.decode_tokens > 0 && decode_ms.is_finite() && decode_ms > 0.0 { + let sample = decode_ms / work.decode_tokens as f64; + state.decode_ms_per_token_ewma = + Some(update_ewma(state.decode_ms_per_token_ewma, sample)); + push_sample(&mut state.decode_ms_per_token_samples, sample); + } + } +} + +fn predicted_wait_ms_for_state( + state: &GenerationServiceState, + concurrency: usize, + tier: InferenceRequestTier, +) -> Option { + let prompt_ms_per_token = conservative_ms_per_token( + state.prefill_ms_per_token_ewma, + &state.prefill_ms_per_token_samples, + ); + let decode_ms_per_token = conservative_ms_per_token( + state.decode_ms_per_token_ewma, + &state.decode_ms_per_token_samples, + ); + if prompt_ms_per_token.is_none() && decode_ms_per_token.is_none() { + return None; + } + let work = state + .queued + .range(tier..) + .fold(state.active, |work, (_, queued)| add_work(work, *queued)); + let prompt_ms = prompt_ms_per_token.unwrap_or(0.0) * work.prompt_tokens as f64; + let decode_ms = decode_ms_per_token.unwrap_or(0.0) * work.decode_tokens as f64; + Some((prompt_ms + decode_ms) / concurrency.max(1) as f64) +} + +pub(in crate::frontend) struct GenerationQueuedWorkReservation { + estimator: Arc, + work: GenerationAdmissionWork, + tier: InferenceRequestTier, + queued: bool, +} + +impl GenerationQueuedWorkReservation { + pub(in crate::frontend) fn promote(mut self) -> GenerationActiveWorkReservation { + if let Ok(mut state) = self.estimator.state.lock() { + unqueue(&mut state, self.tier, self.work); + state.active = add_work(state.active, self.work); + } + self.queued = false; + GenerationActiveWorkReservation { + estimator: self.estimator.clone(), + work: self.work, + } + } +} + +impl Drop for GenerationQueuedWorkReservation { + fn drop(&mut self) { + if self.queued + && let Ok(mut state) = self.estimator.state.lock() + { + unqueue(&mut state, self.tier, self.work); + } + } +} + +pub(in crate::frontend) struct GenerationActiveWorkReservation { + estimator: Arc, + work: GenerationAdmissionWork, +} + +impl Drop for GenerationActiveWorkReservation { + fn drop(&mut self) { + if let Ok(mut state) = self.estimator.state.lock() { + state.active = subtract_work(state.active, self.work); + } + } +} + +fn unqueue( + state: &mut GenerationServiceState, + tier: InferenceRequestTier, + work: GenerationAdmissionWork, +) { + if let Some(queued) = state.queued.get_mut(&tier) { + *queued = subtract_work(*queued, work); + if *queued == GenerationAdmissionWork::default() { + state.queued.remove(&tier); + } + } +} + +fn add_work( + left: GenerationAdmissionWork, + right: GenerationAdmissionWork, +) -> GenerationAdmissionWork { + GenerationAdmissionWork { + prompt_tokens: left.prompt_tokens.saturating_add(right.prompt_tokens), + decode_tokens: left.decode_tokens.saturating_add(right.decode_tokens), + } +} + +fn subtract_work( + left: GenerationAdmissionWork, + right: GenerationAdmissionWork, +) -> GenerationAdmissionWork { + GenerationAdmissionWork { + prompt_tokens: left.prompt_tokens.saturating_sub(right.prompt_tokens), + decode_tokens: left.decode_tokens.saturating_sub(right.decode_tokens), + } +} + +fn update_ewma(previous: Option, sample: f64) -> f64 { + previous.map_or(sample, |previous| { + previous * (1.0 - SERVICE_RATE_EWMA_ALPHA) + sample * SERVICE_RATE_EWMA_ALPHA + }) +} + +fn push_sample(samples: &mut VecDeque, sample: f64) { + if samples.len() == SERVICE_RATE_WINDOW { + samples.pop_front(); + } + samples.push_back(sample); +} + +fn conservative_ms_per_token(ewma: Option, samples: &VecDeque) -> Option { + let mut sorted = samples.iter().copied().collect::>(); + sorted.sort_by(f64::total_cmp); + let p95 = if sorted.is_empty() { + None + } else { + let index = (sorted.len() * 95).div_ceil(100).saturating_sub(1); + sorted.get(index).copied() + }; + match (ewma, p95) { + (Some(ewma), Some(p95)) => Some(ewma.max(p95)), + (Some(value), None) | (None, Some(value)) => Some(value), + (None, None) => None, + } +} + +#[cfg(test)] +mod service_estimator_tests { + use super::*; + + #[test] + fn high_prediction_does_not_refuse_work_accounting() { + let estimator = Arc::new(GenerationServiceEstimator::new(1)); + let work = GenerationAdmissionWork::new(100, 100); + estimator.observe_completed(work, 100.0, 100.0); + let active = estimator.start_active(work); + let local = InferenceRequestTier::Local; + + assert_eq!(estimator.predicted_wait_ms(local), Some(200.0)); + let queued = estimator.reserve_queued(work, local); + assert_eq!(estimator.predicted_wait_ms(local), Some(400.0)); + drop(queued); + assert_eq!(estimator.predicted_wait_ms(local), Some(200.0)); + drop(active); + assert_eq!(estimator.predicted_wait_ms(local), Some(0.0)); + } + + #[test] + fn queued_and_active_work_are_released_by_raii() { + let estimator = Arc::new(GenerationServiceEstimator::new(2)); + let work = GenerationAdmissionWork::new(80, 20); + estimator.observe_completed(work, 80.0, 20.0); + let queued = estimator.reserve_queued(work, InferenceRequestTier::Local); + assert_eq!( + estimator.predicted_wait_ms(InferenceRequestTier::Local), + Some(50.0) + ); + + let active = queued.promote(); + assert_eq!( + estimator.predicted_wait_ms(InferenceRequestTier::Local), + Some(50.0) + ); + drop(active); + assert_eq!( + estimator.predicted_wait_ms(InferenceRequestTier::Local), + Some(0.0) + ); + } + + /// Queued mesh work is admitted after a local request, so it does not + /// count toward the local request's predicted wait. + #[test] + fn a_request_waits_only_behind_work_at_its_tier_or_higher() { + let estimator = Arc::new(GenerationServiceEstimator::new(1)); + let work = GenerationAdmissionWork::new(100, 100); + estimator.observe_completed(work, 100.0, 100.0); + let _mesh = estimator.reserve_queued(work, InferenceRequestTier::Mesh); + let _trusted = estimator.reserve_queued(work, InferenceRequestTier::Trusted); + + assert_eq!( + estimator.predicted_wait_ms(InferenceRequestTier::Local), + Some(0.0) + ); + assert_eq!( + estimator.predicted_wait_ms(InferenceRequestTier::Trusted), + Some(200.0) + ); + assert_eq!( + estimator.predicted_wait_ms(InferenceRequestTier::Mesh), + Some(400.0) + ); + } + + #[test] + fn conservative_rate_uses_the_slower_p95_sample() { + let samples = VecDeque::from([1.0, 1.0, 1.0, 10.0]); + assert_eq!(conservative_ms_per_token(Some(1.5), &samples), Some(10.0)); + } + + #[test] + fn prefill_estimate_uses_observed_stage_rate() { + let estimator = GenerationServiceEstimator::new(1); + assert_eq!(estimator.estimated_prefill_ms(128), None); + estimator.observe_completed(GenerationAdmissionWork::new(100, 0), 25.0, 0.0); + assert_eq!(estimator.estimated_prefill_ms(40), Some(10.0)); + } +} diff --git a/skippy/crates/skippy-serving/src/frontend/generation_flow.rs b/skippy/crates/skippy-serving/src/frontend/generation_flow.rs index f72183c6a6..bdf66c502e 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation_flow.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation_flow.rs @@ -30,6 +30,7 @@ use crate::frontend::wire_messages::ReusableDecodeMessage; use crate::frontend::wire_messages::ReusableDecodeMessageArgs; use crate::frontend::wire_messages::generation_config_message; use crate::frontend::wire_messages::multimodal_prefill_message; +use crate::frontend::wire_messages::stop_message; use crate::kv_integration::proactive_eviction_attrs; use crate::runtime_state::panic_recovery::lock_runtime; use anyhow::anyhow; @@ -37,7 +38,6 @@ use serde_json::json; use skippy_inference_api::InferenceError; use skippy_inference_api::InferenceResult; use skippy_inference_api::generation::GenerationRequest; -use skippy_protocol::binary::StageWireMessage; use skippy_protocol::binary::WireReplyKind; use skippy_protocol::binary::recv_reply; use skippy_protocol::binary::write_stage_message; @@ -856,6 +856,7 @@ impl StageOpenAiBackend { positions: chunk.positions.clone(), sampling: is_final_chunk.then_some(wire_sampling.clone()).flatten(), final_chunk: is_final_chunk, + request_class: request.ids.request_class(), })?; let forwarded = forwarded_stage_message_timed( &request.config, @@ -951,6 +952,7 @@ impl StageOpenAiBackend { sampling: wire_sampling.clone(), sideband_capacity: 1, native_mtp_draft_tokens: 0, + request_class: request.ids.request_class(), })?; while decoded_tokens < max_tokens as usize { @@ -1167,7 +1169,7 @@ impl StageOpenAiBackend { let stop_result = write_stage_message( &mut lane.stream, - &StageWireMessage::stop_with_identity(request_id, session_id), + &stop_message(request_id, session_id, request.ids.request_class()), ) .and_then(|_| recv_reply(&mut lane.stream).map(|reply| reply.kind)) .and_then(|kind| { diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs index 090c76c904..48564a5045 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs @@ -86,6 +86,8 @@ pub(crate) struct IterationScheduler { pub(super) struct ScheduledGenerationRequest<'a> { pub(super) id: &'a str, + /// Admission priority: the request tier's priority. + pub(super) priority: u64, pub(super) prompt_tokens: &'a [i32], pub(super) max_tokens: u32, pub(super) sampling: Option<&'a SamplingConfig>, @@ -95,6 +97,7 @@ pub(super) struct ScheduledGenerationRequest<'a> { pub(super) struct ScheduledResumeRequest<'a> { pub(super) id: &'a str, + pub(super) priority: u64, pub(super) prompt_tokens: &'a [i32], pub(super) generated_tokens: &'a [i32], pub(super) max_tokens: u32, @@ -136,6 +139,7 @@ struct IterationSchedulerShared { struct ScheduledRequest { id: String, + priority: u64, prompt_tokens: Vec, max_tokens: u32, sampling: Option, @@ -597,6 +601,7 @@ impl IterationScheduler { let _sequence = trace_context::bind_sequence(request.id); self.enqueue_command(SchedulerCommand::Submit(ScheduledRequest { id: request.id.to_string(), + priority: request.priority, prompt_tokens: request.prompt_tokens.to_vec(), max_tokens: request.max_tokens, sampling: request.sampling.cloned(), @@ -627,6 +632,7 @@ impl IterationScheduler { let _sequence = trace_context::bind_sequence(request.id); self.enqueue_command(SchedulerCommand::Submit(ScheduledRequest { id: request.id.to_string(), + priority: request.priority, prompt_tokens: request.prompt_tokens.to_vec(), max_tokens: request.max_tokens, sampling: request.sampling.cloned(), @@ -1148,7 +1154,7 @@ impl SchedulerWorker { request.prompt_tokens.clone(), request.max_tokens, request.sampling.clone(), - 0, + request.priority, ) .with_admission_tokens(admission_tokens); if !request.generated_tokens.is_empty() { diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_runtime.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_runtime.rs index 43c6ea3fc3..0fe3fda263 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_runtime.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_runtime.rs @@ -5,7 +5,9 @@ use super::{ use crate::kv_integration::scheduling::CacheSchedulingPolicy; use crate::runtime_state::RuntimeState; use skippy_inference_api::InferenceResult; -use skippy_scheduler::{CacheAffinity, CacheAwareCandidate, order_cache_aware_candidates}; +use skippy_scheduler::{ + CacheAffinity, CacheAwareCandidate, PriorityPassovers, order_cache_aware_candidates, +}; use std::sync::Arc; use std::time::Instant; @@ -18,6 +20,7 @@ pub(super) struct CacheAwareRuntimeOperation { priority: u64, enqueued_turn: u64, order: u64, + passover_mark: u64, scheduling: CacheSchedulingPolicy, refresh_affinity: Option, affinity_initialized: bool, @@ -44,6 +47,7 @@ pub(super) struct CacheRuntimeQueue { operations: Vec, order_dirty: bool, turn: u64, + passovers: PriorityPassovers, next_order: u64, aging_cost_per_turn: u64, group_waiting_prefixes: bool, @@ -61,6 +65,7 @@ impl CacheRuntimeQueue { operations: Vec::new(), order_dirty: false, turn: 0, + passovers: PriorityPassovers::default(), next_order: 0, aging_cost_per_turn, group_waiting_prefixes, @@ -154,6 +159,7 @@ impl CacheRuntimeQueue { priority, enqueued_turn: self.turn, order, + passover_mark: self.passovers.mark(priority), scheduling: state.scheduling, refresh_affinity: state.refresh_affinity, affinity_initialized: state.affinity_initialized, @@ -178,6 +184,12 @@ impl CacheRuntimeQueue { self.refresh_affinities(); self.reorder_if_dirty(); let queued = self.operations.pop()?; + self.passovers.record_selection(queued.priority); + // Passing lower priorities over can age them past another level. + self.order_dirty |= self + .operations + .iter() + .any(|operation| operation.priority < queued.priority); let affinity = &queued.affinity; let telemetry = CacheRuntimeTelemetry { matched_tokens: affinity.matched_tokens(), @@ -233,6 +245,9 @@ impl CacheRuntimeQueue { prompt_tokens: queued.prompt_tokens.as_ref(), enqueued_turn: queued.enqueued_turn, order: queued.order, + passed_over: self + .passovers + .passed_over(queued.priority, queued.passover_mark), }), self.turn, self.aging_cost_per_turn, diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs index 1669eee625..82ff84b27f 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs @@ -77,6 +77,7 @@ fn planned_work_reaches_runtime_admission_without_coalescing_an_empty_direct_que let (reply, events) = std_mpsc::channel(); worker.submit(ScheduledRequest { id: "planned".into(), + priority: 0, prompt_tokens: vec![1, 2], max_tokens: 1, sampling: None, diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs index ca3eddf9c0..d893e97762 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs @@ -286,6 +286,7 @@ fn server_scheduler_worker_batches_and_completes_default_generations() { let (reply_b, events_b) = std_mpsc::channel(); worker.submit(ScheduledRequest { id: "a".into(), + priority: 0, prompt_tokens: vec![1, 2], max_tokens: 1, sampling: None, @@ -297,6 +298,7 @@ fn server_scheduler_worker_batches_and_completes_default_generations() { }); worker.submit(ScheduledRequest { id: "b".into(), + priority: 0, prompt_tokens: vec![3, 4], max_tokens: 1, sampling: None, @@ -395,6 +397,7 @@ fn token_control_is_applied_without_blocking_the_scheduler_iteration() { let (reply, events) = std_mpsc::channel(); worker.submit(ScheduledRequest { id: "slow-consumer".into(), + priority: 0, prompt_tokens: vec![1], max_tokens: 2, sampling: None, @@ -925,6 +928,7 @@ fn worker_panic_is_contained_and_fails_active_requests() { commands .send(SchedulerCommand::Submit(ScheduledRequest { id: "panic-contained".into(), + priority: 0, prompt_tokens: vec![1], max_tokens: 1, sampling: None, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs index 301c1a8dee..1b62b260e4 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs @@ -230,8 +230,8 @@ fn loaded_runtime_admission_uses_aggregate_pool_across_frontends() -> Result<()> let mut runtime = backend.runtime.lock().unwrap(); let per_lane = runtime.context_tokens_per_lane() as usize; assert_eq!(runtime.kv_pool_tokens() as usize, per_lane * 2); - let first = GenerationTokenBudget::shared_for_runtime(&mut runtime, per_lane); - let second = GenerationTokenBudget::shared_for_runtime(&mut runtime, per_lane); + let first = GenerationTokenBudget::shared_for_runtime(&mut runtime, per_lane, 0); + let second = GenerationTokenBudget::shared_for_runtime(&mut runtime, per_lane, 0); assert!(Arc::ptr_eq(&first, &second)); let _reservation = first .try_reserve(GenerationTokenBudgetRequest::new(per_lane + 1, 0))? diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs index 6fb931e876..62197472e9 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs @@ -576,6 +576,7 @@ impl StageOpenAiBackend { let stats = self.iteration_scheduler.generate( ScheduledGenerationRequest { id: session_id, + priority: request.ids.request_tier().priority(), prompt_tokens: request.prompt_token_ids, max_tokens: request.max_tokens, sampling: request.sampling.enabled.then_some(request.sampling), @@ -967,6 +968,7 @@ impl StageOpenAiBackend { let stats = self.iteration_scheduler.resume_generation( ScheduledResumeRequest { id: session_id, + priority: request.ids.request_tier().priority(), prompt_tokens: request.prompt_token_ids, generated_tokens: &initial_generated_tokens, max_tokens: request.max_tokens, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs index 52ce3bef0c..be3768bcae 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs @@ -154,7 +154,7 @@ impl StageOpenAiBackend { deadline: cache_operation_deadline, cancellation: request.cancellation, prompt_tokens: Arc::clone(&prefill_tokens), - priority: 0, + priority: request.ids.request_tier().priority(), scheduling: cache_scheduling, refresh_affinity: refresh_cache_affinity, }, diff --git a/skippy/crates/skippy-serving/src/frontend/native_mtp/verify_window.rs b/skippy/crates/skippy-serving/src/frontend/native_mtp/verify_window.rs index 4ced09a5cf..a2b93b89f9 100644 --- a/skippy/crates/skippy-serving/src/frontend/native_mtp/verify_window.rs +++ b/skippy/crates/skippy-serving/src/frontend/native_mtp/verify_window.rs @@ -140,6 +140,7 @@ impl StageOpenAiBackend { tokens: &verify_inputs, sampling: wire_sampling.clone(), native_mtp_draft_tokens: request.native_mtp_draft_tokens(), + request_class: request.ids.request_class(), })?; message.state.set_split_dflash(request.split_dflash()); message diff --git a/skippy/crates/skippy-serving/src/frontend/prefix_cache.rs b/skippy/crates/skippy-serving/src/frontend/prefix_cache.rs index 7ab4b0984c..370c2261ab 100644 --- a/skippy/crates/skippy-serving/src/frontend/prefix_cache.rs +++ b/skippy/crates/skippy-serving/src/frontend/prefix_cache.rs @@ -35,7 +35,6 @@ use skippy_protocol::SCHEMA_VERSION; use skippy_protocol::StageConfig; use skippy_protocol::binary::StageReplyStats; use skippy_protocol::binary::StageSamplingConfig as WireSamplingConfig; -use skippy_protocol::binary::StageWireMessage; use skippy_protocol::binary::WireMessageKind; use skippy_protocol::binary::WireReplyKind; use skippy_protocol::binary::recv_reply; @@ -1001,6 +1000,7 @@ impl StageOpenAiBackend { current, sampling: wire_sampling.clone(), native_mtp_draft_tokens: request.native_mtp_draft_tokens(), + request_class: request.ids.request_class(), })?; let has_downstream = request.config.downstream.is_some(); let scheduler_kv = Arc::clone(kv); @@ -1086,6 +1086,7 @@ impl StageOpenAiBackend { sampling: wire_sampling, chat_sampling_metadata: request.chat_sampling_metadata, native_mtp_draft_tokens: request.native_mtp_draft_tokens(), + request_class: request.ids.request_class(), })?; let forwarded = forwarded_stage_message_timed( request.config, @@ -1194,8 +1195,11 @@ impl StageOpenAiBackend { .map_err(openai_backend_error) }, ); - let stop = - StageWireMessage::stop_with_identity(request.ids.request_id, request.ids.session_id); + let stop = crate::frontend::wire_messages::stop_message( + request.ids.request_id, + request.ids.session_id, + request.ids.request_class(), + ); if write_stage_message_conditioned( &mut *downstream, &stop, diff --git a/skippy/crates/skippy-serving/src/frontend/prefix_cache/split_restore.rs b/skippy/crates/skippy-serving/src/frontend/prefix_cache/split_restore.rs index 8072e3fda5..20479898c2 100644 --- a/skippy/crates/skippy-serving/src/frontend/prefix_cache/split_restore.rs +++ b/skippy/crates/skippy-serving/src/frontend/prefix_cache/split_restore.rs @@ -55,6 +55,7 @@ impl StageOpenAiBackend { &prefill_tokens[..restored_tokens], request.ids.request_id, request.ids.session_id, + request.ids.request_class(), )?; write_stage_message_conditioned( &mut *downstream, diff --git a/skippy/crates/skippy-serving/src/frontend/system_one/causal.rs b/skippy/crates/skippy-serving/src/frontend/system_one/causal.rs index d600bacd79..cf92cb5efe 100644 --- a/skippy/crates/skippy-serving/src/frontend/system_one/causal.rs +++ b/skippy/crates/skippy-serving/src/frontend/system_one/causal.rs @@ -69,6 +69,7 @@ impl StageOpenAiBackend { pub(in crate::frontend) async fn serve_system_one( &self, request: SystemOneRequest, + class: skippy_inference_api::InferenceRequestClass, ) -> InferenceResult { super::validate_request_fields(&request, &self.model_id)?; let decision = super::decision_request(&request)?; @@ -102,7 +103,7 @@ impl StageOpenAiBackend { }; validate_context(&plan, self.ctx_size)?; let guard = CancelOnDrop(CancellationToken::new()); - let preparation = self.warm_decision_prefixes(&plan, &guard.0).await?; + let preparation = self.warm_decision_prefixes(&plan, &guard.0, class).await?; let jobs = decision_jobs(&plan); let mut executor = self.clone(); if !preparation.reuse_cache { @@ -110,7 +111,7 @@ impl StageOpenAiBackend { // This affects only this request, not the shared backend or other users. executor.kv = None; } - let results = executor.run_readout_jobs(jobs, &guard.0).await?; + let results = executor.run_readout_jobs(jobs, &guard.0, class).await?; decision_response(request, &plan, results, preparation.usage) } @@ -119,10 +120,11 @@ impl StageOpenAiBackend { &self, jobs: Vec, cancellation: &CancellationToken, + class: skippy_inference_api::InferenceRequestClass, ) -> InferenceResult> { let width = self.generation_limit.current_limit().clamp(1, 64); let mut running = stream::iter(jobs.into_iter().map(|job| async move { - let result = self.run_readout_job(job.clone(), cancellation).await; + let result = self.run_readout_job(job.clone(), cancellation, class).await; (job, result) })) .buffer_unordered(width); @@ -145,6 +147,7 @@ impl StageOpenAiBackend { &self, job: ReadoutJob, cancellation: &CancellationToken, + class: skippy_inference_api::InferenceRequestClass, ) -> Result { job.validate()?; let ids = InferenceGenerationIds::new_with_trust( @@ -152,7 +155,8 @@ impl StageOpenAiBackend { None, false, None, - ); + ) + .with_request_class(class); let continuation = job.candidates.iter().map(Vec::len).max().unwrap_or(0); let work = GenerationAdmissionWork::new(job.prompt.len() + continuation.saturating_sub(1), 0); diff --git a/skippy/crates/skippy-serving/src/frontend/system_one/causal/cache.rs b/skippy/crates/skippy-serving/src/frontend/system_one/causal/cache.rs index 784960eff9..e8a792774b 100644 --- a/skippy/crates/skippy-serving/src/frontend/system_one/causal/cache.rs +++ b/skippy/crates/skippy-serving/src/frontend/system_one/causal/cache.rs @@ -78,6 +78,7 @@ impl DecisionSequence<'_> { tokens, self.ids.request_id, self.ids.session_id, + self.ids.request_class(), )?; write_stage_message_conditioned(&mut lane.stream, &message, *downstream_wire_condition) .map_err(openai_io_error)?; @@ -93,9 +94,10 @@ impl DecisionSequence<'_> { if !restored { // Reset every stage, including recurrent state that cannot safely // be truncated after a partial chain restore. - let stop = skippy_protocol::binary::StageWireMessage::stop_with_identity( + let stop = crate::frontend::wire_messages::stop_message( self.ids.request_id, self.ids.session_id, + self.ids.request_class(), ); write_stage_message_conditioned(&mut lane.stream, &stop, *downstream_wire_condition) .map_err(openai_io_error)?; diff --git a/skippy/crates/skippy-serving/src/frontend/system_one/causal/preparation.rs b/skippy/crates/skippy-serving/src/frontend/system_one/causal/preparation.rs index 28027bbcf4..cf9db5af53 100644 --- a/skippy/crates/skippy-serving/src/frontend/system_one/causal/preparation.rs +++ b/skippy/crates/skippy-serving/src/frontend/system_one/causal/preparation.rs @@ -14,6 +14,7 @@ impl StageOpenAiBackend { &self, plan: &DecisionPlan, cancellation: &CancellationToken, + class: skippy_inference_api::InferenceRequestClass, ) -> InferenceResult { let mut usage = DecisionReadoutUsage::default(); if !self @@ -28,7 +29,9 @@ impl StageOpenAiBackend { } if plan.questions.len() > 1 && plan.shared_prefix_tokens > 0 { let tokens = plan.questions[0].prompt[..plan.shared_prefix_tokens].to_vec(); - let result = self.run_readout_job(warmup_job(tokens), cancellation).await; + let result = self + .run_readout_job(warmup_job(tokens), cancellation, class) + .await; if !accumulate_preparation(stream::iter([result]), cancellation, &mut usage).await? { return Ok(PreparedPrefixes { usage, @@ -46,7 +49,7 @@ impl StageOpenAiBackend { let results = stream::iter( prompts .into_iter() - .map(|job| self.run_readout_job(job, cancellation)), + .map(|job| self.run_readout_job(job, cancellation, class)), ) .buffer_unordered(width); let reuse_cache = accumulate_preparation(results, cancellation, &mut usage).await?; diff --git a/skippy/crates/skippy-serving/src/frontend/system_one/causal/sequence.rs b/skippy/crates/skippy-serving/src/frontend/system_one/causal/sequence.rs index 03968ab1c0..775ab351ec 100644 --- a/skippy/crates/skippy-serving/src/frontend/system_one/causal/sequence.rs +++ b/skippy/crates/skippy-serving/src/frontend/system_one/causal/sequence.rs @@ -8,9 +8,7 @@ use crate::frontend::generation::{ use crate::frontend::iteration_scheduler::readout::ReadoutIteration; use crate::frontend::util::openai_io_error; use crate::frontend::wire_messages::{OpenAiPrefillChunk, embedded_prefill_message}; -use skippy_protocol::binary::{ - StageStateHeader, StageWireMessage, WireMessageKind, WireReplyKind, recv_reply, -}; +use skippy_protocol::binary::{StageStateHeader, WireMessageKind, WireReplyKind, recv_reply}; use std::net::Shutdown; pub(super) struct DecisionSequence<'a> { @@ -184,11 +182,16 @@ impl<'a> DecisionSequence<'a> { tokens, request_id: self.ids.request_id, session_id: self.ids.session_id, + request_class: self.ids.request_class(), })?; message.kind = WireMessageKind::PrefillReadout; message.state = StageStateHeader::new(message.kind); message.state.prompt_token_count = i32::try_from(self.prompt_tokens) .map_err(|_| InferenceError::invalid_request("decision prompt exceeds wire bounds"))?; + crate::stage_request_class::stamp_request_class( + &mut message.state, + self.ids.request_class(), + ); message.readout_tokens = selected.to_vec(); let forwarded = forwarded_stage_message(config, &message, activation, *activation_width) .map_err(openai_backend_error)?; @@ -210,8 +213,11 @@ impl<'a> DecisionSequence<'a> { /// Close the sequence's downstream connection and remove local session state. fn close(&mut self) -> InferenceResult<()> { if let Some((pool, mut lane)) = self.lane.take() { - let stop = - StageWireMessage::stop_with_identity(self.ids.request_id, self.ids.session_id); + let stop = crate::frontend::wire_messages::stop_message( + self.ids.request_id, + self.ids.session_id, + self.ids.request_class(), + ); skippy_protocol::binary::write_stage_message(&mut lane.stream, &stop) .map_err(openai_io_error)?; let reply = recv_reply(&mut lane.stream).map_err(openai_io_error)?; diff --git a/skippy/crates/skippy-serving/src/frontend/tests/enc_dec_lane_admission.rs b/skippy/crates/skippy-serving/src/frontend/tests/enc_dec_lane_admission.rs index 650b3a01d8..40feee1b0a 100644 --- a/skippy/crates/skippy-serving/src/frontend/tests/enc_dec_lane_admission.rs +++ b/skippy/crates/skippy-serving/src/frontend/tests/enc_dec_lane_admission.rs @@ -50,6 +50,7 @@ pub(in crate::frontend) fn modelless_stage_openai_args() -> EmbeddedOpenAiArgs { pipeline_decode_groups: None, adaptive_generation_min_concurrency: None, generation_queue_capacity: 8, + local_kv_reserve_percent: 0, generation_admission_timeout_secs: 1, prefill_chunk_size: 512, prefill_chunk_policy: "fixed".to_string(), diff --git a/skippy/crates/skippy-serving/src/frontend/tests/support.rs b/skippy/crates/skippy-serving/src/frontend/tests/support.rs index 66d5a0087d..0d138bca40 100644 --- a/skippy/crates/skippy-serving/src/frontend/tests/support.rs +++ b/skippy/crates/skippy-serving/src/frontend/tests/support.rs @@ -114,6 +114,7 @@ pub(super) fn seed_resident_prefix(kv: &KvStageIntegration, identity: &PrefillKv seq_id, token_count, recompute_cost: token_count, + retention_priority: 0, }, ) .expect("synthetic radix prefix should record"); diff --git a/skippy/crates/skippy-serving/src/frontend/tests/wire_messages.rs b/skippy/crates/skippy-serving/src/frontend/tests/wire_messages.rs index 5571ec3fea..23a024f311 100644 --- a/skippy/crates/skippy-serving/src/frontend/tests/wire_messages.rs +++ b/skippy/crates/skippy-serving/src/frontend/tests/wire_messages.rs @@ -18,6 +18,7 @@ fn multimodal_final_prefill_message_requests_downstream_prediction() { positions: Vec::new(), sampling: Some(sampling.clone()), final_chunk: true, + request_class: Default::default(), }) .unwrap(); @@ -49,6 +50,7 @@ fn restore_prefill_decode_message_carries_chat_sampling_metadata() { sampling: Some(sampling.clone()), chat_sampling_metadata: Some(metadata), native_mtp_draft_tokens: 0, + request_class: Default::default(), }) .unwrap(); @@ -82,6 +84,7 @@ fn reusable_decode_message_updates_hot_path_fields() { sampling: Some(sampling.clone()), sideband_capacity: 4, native_mtp_draft_tokens: 3, + request_class: skippy_inference_api::InferenceRequestClass::default(), }) .unwrap(); @@ -115,3 +118,99 @@ fn reusable_decode_message_updates_hot_path_fields() { assert!(second.activation.is_empty()); assert!(second.raw_bytes.is_empty()); } + +/// A downstream stage caches prompts from every prefill, restore, decode, +/// verify window and stop of a session, so each must carry the request's +/// class. +#[test] +fn decode_verify_and_stop_messages_carry_the_request_class() { + use skippy_inference_api::{InferenceRequestClass, InferenceRequestTier}; + let class = InferenceRequestClass::new(InferenceRequestTier::Mesh, true); + let served = |state| { + crate::stage_request_class::stage_request_class( + &skippy_protocol::StageConfig::default(), + state, + ) + }; + + let decode = embedded_decode_message(DecodeMessageArgs { + request_id: 11, + session_id: 13, + prompt_token_count: 4, + pos_start: 4, + decode_step: 0, + current: 104, + sampling: None, + native_mtp_draft_tokens: 0, + request_class: class, + }) + .unwrap(); + assert_eq!(served(decode.state), class); + + let verify = embedded_verify_window_message(VerifyWindowMessageArgs { + window_id: 1, + request_id: 11, + session_id: 13, + prompt_token_count: 4, + pos_start: 5, + decode_step: 1, + tokens: &[105, 106], + sampling: None, + native_mtp_draft_tokens: 0, + request_class: class, + }) + .unwrap(); + assert_eq!(served(verify.state), class); + + let stop = stop_message(11, 13, class); + assert_eq!(stop.kind, WireMessageKind::Stop); + assert_eq!(served(stop.state), class); + + let prefill = embedded_prefill_message(OpenAiPrefillChunk { + seq_id: 0, + pos_start: 0, + prefill_token_count: 2, + tokens: &[1, 2], + request_id: 11, + session_id: 13, + request_class: class, + }) + .unwrap(); + assert_eq!(served(prefill.state), class); + + let restore = + embedded_prefix_cache_message(WireMessageKind::TryRestorePrefill, &[1, 2], 11, 13, class) + .unwrap(); + assert_eq!(served(restore.state), class); + + let multimodal = multimodal_prefill_message(MultimodalPrefillArgs { + request_id: 11, + session_id: 13, + prompt_token_count: 2, + pos_start: 0, + token_count: 2, + tokens: vec![1, 2], + positions: Vec::new(), + sampling: None, + final_chunk: false, + request_class: class, + }) + .unwrap(); + assert_eq!(served(multimodal.state), class); + + let fused = embedded_restore_prefill_decode_message(RestorePrefillDecodeMessageArgs { + request_id: 11, + session_id: 13, + prompt_token_count: 3, + pos_start: 2, + decode_step: 0, + prefix_tokens: &[1, 2], + current: 3, + sampling: None, + chat_sampling_metadata: None, + native_mtp_draft_tokens: 0, + request_class: class, + }) + .unwrap(); + assert_eq!(served(fused.state), class); +} diff --git a/skippy/crates/skippy-serving/src/frontend/wire_messages.rs b/skippy/crates/skippy-serving/src/frontend/wire_messages.rs index 9c7e60571c..e14f389aa7 100644 --- a/skippy/crates/skippy-serving/src/frontend/wire_messages.rs +++ b/skippy/crates/skippy-serving/src/frontend/wire_messages.rs @@ -1,4 +1,5 @@ use skippy_inference_api::InferenceError; +use skippy_inference_api::InferenceRequestClass; use skippy_inference_api::InferenceResult; use skippy_protocol::binary::LLAMA_TOKEN_NULL; use skippy_protocol::binary::StageSamplingConfig as WireSamplingConfig; @@ -16,6 +17,8 @@ pub(super) struct DecodeMessageArgs { pub(super) sampling: Option, /// Native MTP drafts the final stage should propose; zero asks for none. pub(super) native_mtp_draft_tokens: usize, + /// The tier and cache partition of the request this decode serves. + pub(super) request_class: InferenceRequestClass, } pub(super) fn embedded_decode_message( @@ -29,6 +32,7 @@ pub(super) fn embedded_decode_message( sampling: args.sampling, sideband_capacity: 1, native_mtp_draft_tokens: args.native_mtp_draft_tokens, + request_class: args.request_class, })?; message.update_at_pos( args.decode_step, @@ -47,6 +51,9 @@ pub(super) struct ReusableDecodeMessageArgs { pub(super) sampling: Option, pub(super) sideband_capacity: usize, pub(super) native_mtp_draft_tokens: usize, + /// Stamped on every decode, since a downstream stage records the prompt + /// on the first one. + pub(super) request_class: InferenceRequestClass, } pub(super) struct ReusableDecodeMessage { @@ -63,6 +70,7 @@ impl ReusableDecodeMessage { state.prompt_token_count = i32::try_from(args.prompt_token_count) .map_err(|_| InferenceError::backend("prompt token count exceeds i32"))?; state.source_stage_index = -1; + crate::stage_request_class::stamp_request_class(&mut state, args.request_class); Ok(Self { message: StageWireMessage { kind: WireMessageKind::DecodeEmbd, @@ -143,6 +151,7 @@ pub(super) struct VerifyWindowMessageArgs<'a> { pub(super) tokens: &'a [i32], pub(super) sampling: Option, pub(super) native_mtp_draft_tokens: usize, + pub(super) request_class: InferenceRequestClass, } /// Construct a verification-window request with coordinator-owned identity. @@ -166,6 +175,7 @@ pub(super) fn embedded_verify_window_message( .map_err(|_| InferenceError::backend("decode step exceeds i32"))?; state.current_token = args.tokens[0]; state.source_stage_index = -1; + crate::stage_request_class::stamp_request_class(&mut state, args.request_class); Ok(StageWireMessage { kind: WireMessageKind::VerifyWindow, pos_start: i32::try_from(args.pos_start) @@ -185,6 +195,18 @@ pub(super) fn embedded_verify_window_message( }) } +/// Ends a request's stage session. It carries the request's class because a +/// downstream stage records the prompt it accumulated when the session stops. +pub(super) fn stop_message( + request_id: u64, + session_id: u64, + request_class: InferenceRequestClass, +) -> StageWireMessage { + let mut message = StageWireMessage::stop_with_identity(request_id, session_id); + crate::stage_request_class::stamp_request_class(&mut message.state, request_class); + message +} + /// Invalidates verify windows `min_window_id..=max_window_id` for a request /// after divergence. The downstream records the range at receive time so /// buffered stale windows are answered with an empty reply instead of being @@ -270,6 +292,7 @@ pub(super) struct OpenAiPrefillChunk<'a> { pub(super) tokens: &'a [i32], pub(super) request_id: u64, pub(super) session_id: u64, + pub(super) request_class: InferenceRequestClass, } /// Construct a prefill request with its prompt, activation and sampling metadata. @@ -286,6 +309,7 @@ pub(super) fn embedded_prefill_message( .last() .ok_or_else(|| InferenceError::backend("prefill chunk is empty"))?; state.source_stage_index = -1; + crate::stage_request_class::stamp_request_class(&mut state, chunk.request_class); Ok(StageWireMessage { kind: WireMessageKind::PrefillEmbd, pos_start: i32::try_from(chunk.pos_start) @@ -311,12 +335,14 @@ pub(super) fn embedded_prefix_cache_message( tokens: &[i32], request_id: u64, session_id: u64, + request_class: InferenceRequestClass, ) -> InferenceResult { let mut state = StageStateHeader::new(kind); state.prompt_token_count = i32::try_from(tokens.len()) .map_err(|_| InferenceError::backend("prefix token count exceeds i32"))?; state.current_token = tokens.last().copied().unwrap_or(LLAMA_TOKEN_NULL); state.source_stage_index = -1; + crate::stage_request_class::stamp_request_class(&mut state, request_class); Ok(StageWireMessage { kind, pos_start: 0, @@ -346,6 +372,7 @@ pub(super) struct RestorePrefillDecodeMessageArgs<'a> { pub(super) sampling: Option, pub(super) chat_sampling_metadata: Option<&'a str>, pub(super) native_mtp_draft_tokens: usize, + pub(super) request_class: InferenceRequestClass, } /// Construct a fused restore/prefill/decode request preserving generation metadata. @@ -364,6 +391,7 @@ pub(super) fn embedded_restore_prefill_decode_message( let mut tokens = Vec::with_capacity(args.prefix_tokens.len().saturating_add(1)); tokens.extend_from_slice(args.prefix_tokens); tokens.push(args.current); + crate::stage_request_class::stamp_request_class(&mut state, args.request_class); Ok(StageWireMessage { kind: WireMessageKind::TryRestorePrefillDecode, pos_start: i32::try_from(args.pos_start) @@ -400,6 +428,7 @@ pub(super) struct MultimodalPrefillArgs { pub(super) positions: Vec, pub(super) sampling: Option, pub(super) final_chunk: bool, + pub(super) request_class: InferenceRequestClass, } /// Construct a prefill request carrying multimodal positions and activation data. @@ -417,6 +446,7 @@ pub(super) fn multimodal_prefill_message( .map_err(|_| InferenceError::backend("multimodal prefill token count exceeds i32"))?; state.current_token = LLAMA_TOKEN_NULL; state.source_stage_index = -1; + crate::stage_request_class::stamp_request_class(&mut state, args.request_class); Ok(StageWireMessage { kind, pos_start: i32::try_from(args.pos_start) diff --git a/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs b/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs index 6a8331b38c..5a1216b1bd 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs @@ -238,6 +238,7 @@ mod checkpoint_matching_tests { seq_id: seq, token_count: identity.token_ids.len() as u64, recompute_cost: 1, + retention_priority: 0, }, ) .unwrap(); diff --git a/skippy/crates/skippy-serving/src/kv_integration/config.rs b/skippy/crates/skippy-serving/src/kv_integration/config.rs index 7adf07e680..3f1b23f3e9 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config.rs @@ -744,6 +744,7 @@ fn store_exact_radix_record_with_codec( payload, extra, namespace, + retention_priority, token_ids, l3_fill_claim: _, write_through_l3, @@ -774,7 +775,8 @@ fn store_exact_radix_record_with_codec( payload.clone(), extra.clone(), write_through_l3, - ), + ) + .with_retention_priority(retention_priority), ); match insert_result { Err(error) => Err(error), @@ -783,7 +785,9 @@ fn store_exact_radix_record_with_codec( released.push(replaced.payload); } while radix.stats().recurrent_entries > max_entries { - let Some(evicted) = radix.evict_lru_recurrent() else { + let Some(evicted) = + radix.evict_recurrent_by_retention(RadixExactEntry::retention_priority) + else { break; }; released.push(evicted.value.payload); @@ -930,7 +934,7 @@ fn evict_exact_entries_over( let evicted = radix .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) - .evict_lru_recurrent(); + .evict_recurrent_by_retention(RadixExactEntry::retention_priority); let Some(evicted) = evicted else { break; }; @@ -1024,6 +1028,7 @@ mod tests { mod cache_admission; mod durable_spill; + mod reserved_admission; mod runtime_admission; fn limits(soft_bytes: u64, hard_bytes: u64) -> ExactStateByteLimits { @@ -1072,6 +1077,7 @@ mod tests { payload: skippy_cache::ExactStatePayload::full_state(bytes.to_vec()), extra: super::super::ExactStateExtra::default(), namespace: "model".to_string(), + retention_priority: 0, token_ids: tokens.to_vec(), l3_fill_claim: None, write_through_l3: true, @@ -1124,6 +1130,7 @@ mod tests { kv_desc: Some(desc), }, namespace: "model".to_string(), + retention_priority: 0, token_ids: tokens.to_vec(), l3_fill_claim: None, write_through_l3: true, @@ -1673,460 +1680,3 @@ mod tests { config } } - -#[cfg(test)] -mod reserved_admission_harness { - use super::*; - use crate::kv_integration::exact_state::{CaptureAdmission, ExactStateAdmissionCredit}; - use crate::kv_integration::{ExactStateExtra, ExactStateRecordAdmission}; - use crate::runtime_state::RuntimeState; - use skippy_cache::ExactStatePayload; - use skippy_protocol::MessageBase; - use std::sync::atomic::Ordering as AtomicOrdering; - - const NAMESPACE: &str = "reserved-admission-test"; - const SESSION: &str = "harness-session"; - const WAIT: std::time::Duration = std::time::Duration::from_secs(30); - - fn harness_config() -> StageConfig { - StageConfig { - stage_id: "stage-0".to_string(), - model_id: NAMESPACE.to_string(), - kv_cache: Some(StageKvCacheConfig { - exact_max_bytes: None, - mode: StageKvCacheMode::LookupRecord, - max_entries: 8, - max_bytes: 0, - l2_max_bytes: 0, - codec: skippy_protocol::StageKvCacheCodec::Native, - min_tokens: 1, - shared_prefix_stride_tokens: 1, - shared_prefix_record_limit: 0, - prefill_admission: Default::default(), - retention: Default::default(), - }), - ..StageConfig::default() - } - } - - fn harness() -> (Arc, StageConfig) { - let config = harness_config(); - let kv = KvStageIntegration::from_test_state(&config, ModelStateKind::Recurrent) - .expect("kv integration init") - .expect("kv integration must be enabled for LookupRecord/KvRecurrent"); - (Arc::new(kv), config) - } - - fn message_base() -> MessageBase { - MessageBase { - schema_version: skippy_protocol::SCHEMA_VERSION, - run_id: NAMESPACE.to_string(), - request_id: "harness-request".to_string(), - session_id: SESSION.to_string(), - stage_id: "stage-0".to_string(), - stage_index: 0, - topology_id: NAMESPACE.to_string(), - model_id: Some(NAMESPACE.to_string()), - tokenizer_id: None, - chat_template_id: None, - seq: None, - } - } - - fn identity( - kv: &KvStageIntegration, - config: &StageConfig, - token_ids: &[i32], - ) -> crate::kv_integration::PrefillKvIdentity { - kv.prefill_identity(config, &message_base(), 0, token_ids) - } - - fn record( - page_id: &str, - token_ids: Vec, - admission_credit: ExactStateAdmissionCredit, - ) -> PendingExactStateRecord { - PendingExactStateRecord { - page_id: page_id.to_string(), - payload: ExactStatePayload::full_state(vec![1, 2, 3]), - extra: ExactStateExtra::default(), - namespace: NAMESPACE.to_string(), - token_ids, - l3_fill_claim: None, - write_through_l3: true, - l2_promotion_digest: None, - l3_cost: None, - admission_credit, - } - } - - fn acquire( - kv: &KvStageIntegration, - class: CaptureAdmission, - ) -> Option { - ExactStateAdmissionCredit::acquire( - &kv.admission_outstanding, - &kv.admission_best_effort_outstanding, - class, - ) - } - - fn outstanding(kv: &KvStageIntegration) -> usize { - kv.admission_outstanding.load(AtomicOrdering::Acquire) - } - - fn best_effort_outstanding(kv: &KvStageIntegration) -> usize { - kv.admission_best_effort_outstanding - .load(AtomicOrdering::Acquire) - } - - fn stored(kv: &KvStageIntegration, token_ids: &[i32]) -> bool { - kv.radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .recurrent_exact(NAMESPACE, token_ids) - .is_some() - } - - /// Reserved-credit delivery end-to-end under an EXPLICITLY paused - /// recorder worker (no radix contention): the BestEffort payload is - /// received worker-side and paused BEFORE storage, the Continuation - /// payload is actually ENQUEUED behind it, both classes decline overflow, - /// and unpausing stores BOTH identities and drains every real credit; the - /// budget then admits and stores a recovery record. - #[test] - fn reserved_credits_deliver_continuation_payloads_and_recover_after_drain() { - let (kv, _config) = harness(); - kv.exact_state_worker_pause - .store(true, AtomicOrdering::Release); - - let be1 = acquire(&kv, CaptureAdmission::BestEffort).expect("first BestEffort admitted"); - assert_eq!( - kv.enqueue_exact_state_record(record("be1", vec![1, 2, 3], be1)), - ExactStateRecordAdmission::Queued, - ); - kv.wait_for_exact_state_worker_received(1, WAIT) - .expect("worker received the BestEffort record before storage"); - assert_eq!(outstanding(&kv), 1, "credit held by the paused worker"); - assert!( - !stored(&kv, &[1, 2, 3]), - "paused worker must not have stored yet" - ); - - assert!( - acquire(&kv, CaptureAdmission::BestEffort).is_none(), - "second BestEffort declined at the reserved cap" - ); - assert_eq!(best_effort_outstanding(&kv), 1); - - let pd1 = acquire(&kv, CaptureAdmission::Continuation) - .expect("Continuation admitted into the reserved share"); - assert_eq!( - kv.enqueue_exact_state_record(record("pd1", vec![4, 5, 6], pd1)), - ExactStateRecordAdmission::Queued, - "the Continuation payload must be enqueued, never dropped by the harness" - ); - assert_eq!(outstanding(&kv), 2); - assert!( - acquire(&kv, CaptureAdmission::Continuation).is_none(), - "total budget exhausted" - ); - - kv.exact_state_worker_pause - .store(false, AtomicOrdering::Release); - kv.wait_for_exact_state_recording(WAIT) - .expect("recorder drained both records without drops or panics"); - assert_eq!( - outstanding(&kv), - 0, - "credits released by real worker completion" - ); - assert_eq!(best_effort_outstanding(&kv), 0); - assert!(stored(&kv, &[1, 2, 3]), "BestEffort identity stored"); - assert!(stored(&kv, &[4, 5, 6]), "Continuation identity stored"); - - let recovered = - acquire(&kv, CaptureAdmission::Continuation).expect("budget recovers after the drain"); - assert_eq!( - kv.enqueue_exact_state_record(record("recovered", vec![7, 8], recovered)), - ExactStateRecordAdmission::Queued, - ); - kv.wait_for_exact_state_recording(WAIT) - .expect("recovered record stored"); - assert_eq!(outstanding(&kv), 0); - assert!(stored(&kv, &[7, 8]), "recovered identity stored"); - } - - /// Unhealthy recorder releases real credits on BOTH release paths: the - /// enqueue-level WorkerStopped drop, and the record_exact_state - /// try_begin_record decline that happens after acquisition. - #[test] - fn unhealthy_worker_releases_credits_on_both_release_paths() { - let (kv, config) = harness(); - kv.exact_state_record_worker_healthy - .store(false, AtomicOrdering::Release); - - let credit = acquire(&kv, CaptureAdmission::BestEffort) - .expect("budget admits before the health gate"); - assert_eq!( - kv.enqueue_exact_state_record(record("stopped", vec![1], credit)), - ExactStateRecordAdmission::WorkerStopped, - ); - assert_eq!( - outstanding(&kv), - 0, - "enqueue-level WorkerStopped released the real credit" - ); - - let mut runtime = RuntimeState::new_modelless_for_test(1); - let chat_identity = identity(&kv, &config, &[1, 2, 3]); - let begin_record = crate::frontend::capture_trace::POST_DECODE_NONE_BEGIN_RECORD - .load(AtomicOrdering::Acquire); - let result = kv.record_exact_state( - &mut runtime, - SESSION, - &chat_identity, - CaptureAdmission::BestEffort, - ); - assert!( - matches!(result, Ok(None)), - "unhealthy worker must decline recording" - ); - assert_eq!( - crate::frontend::capture_trace::POST_DECODE_NONE_BEGIN_RECORD - .load(AtomicOrdering::Acquire), - begin_record + 1, - "the decline happened at try_begin_record, i.e. after acquisition" - ); - assert_eq!( - outstanding(&kv), - 0, - "record_exact_state released the credit on the try_begin_record decline" - ); - } - - /// record_exact_state releases its real credit when the radix lock is - /// busy: the capture is skipped without waiting and the inflight page is - /// released. - /// A sliding-window cache can reuse rows below the boundary before the - /// session ends, so its stage copies them with the recurrent state. - #[test] - fn a_sliding_window_stage_does_not_defer_its_kv_copy() { - let (kv, _) = harness(); - assert_eq!( - kv.exact_state_payload(), - Some(StagePrefixCachePayload::KvRecurrent) - ); - let mut runtime = RuntimeState::new_modelless_for_test(1); - assert!(kv.defers_kv_copy(&mut runtime, SESSION, 3)); - - runtime.sliding_window_kv_for_test = true; - assert!(!kv.defers_kv_copy(&mut runtime, SESSION, 3)); - } - - #[test] - fn record_exact_state_releases_credit_when_radix_is_busy() { - let (kv, config) = harness(); - let mut runtime = RuntimeState::new_modelless_for_test(1); - let chat_identity = identity(&kv, &config, &[1, 2, 3]); - let radix_guard = kv.radix.lock().unwrap(); - let result = kv.record_exact_state( - &mut runtime, - SESSION, - &chat_identity, - CaptureAdmission::BestEffort, - ); - drop(radix_guard); - assert!( - matches!(result, Ok(None)), - "busy radix skips without waiting" - ); - assert_eq!(outstanding(&kv), 0, "credit released on the busy skip"); - assert!( - kv.inflight_records.lock().unwrap().is_empty(), - "inflight page released on the busy skip" - ); - } - - /// retained_exact_identity requires the EXACT radix node: a retained - /// shorter entry must not certify a longer identity, and a longer entry - /// must not certify its own prefix. - #[test] - fn retained_exact_identity_requires_the_exact_radix_node() { - let (kv, config) = harness(); - let chat_identity = identity(&kv, &config, &[1, 2, 3]); - kv.radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert_recurrent( - chat_identity.namespace.clone(), - &chat_identity.token_ids, - 32, - RadixExactEntry::new( - "exact".to_string(), - ExactStatePayload::full_state(vec![9]), - ExactStateExtra::default(), - true, - ), - ) - .expect("seeding the radix must succeed"); - - assert!( - kv.retained_exact_identity(&chat_identity.namespace, &[1, 2, 3]), - "the exact node is retained" - ); - assert!( - !kv.retained_exact_identity(&chat_identity.namespace, &[1, 2]), - "a shorter query must not be certified by the longer retained entry" - ); - assert!( - !kv.retained_exact_identity(&chat_identity.namespace, &[1, 2, 3, 4]), - "a longer identity must not be certified by a retained shorter prefix" - ); - assert!( - !kv.retained_exact_identity(&chat_identity.namespace, &[9, 9, 9]), - "an unrelated identity is absent" - ); - } - - /// record_exact_state releases its real credit when the identity is - /// already recorded. - #[test] - fn record_exact_state_releases_credit_when_already_recorded() { - let (kv, config) = harness(); - let mut runtime = RuntimeState::new_modelless_for_test(1); - let chat_identity = identity(&kv, &config, &[1, 2, 3]); - kv.radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert_recurrent( - chat_identity.namespace.clone(), - &chat_identity.token_ids, - 32, - RadixExactEntry::new( - "pre-existing".to_string(), - ExactStatePayload::full_state(vec![9]), - ExactStateExtra::default(), - true, - ), - ) - .expect("pre-seeding the radix must succeed"); - let result = kv.record_exact_state( - &mut runtime, - SESSION, - &chat_identity, - CaptureAdmission::BestEffort, - ); - assert!( - matches!(result, Ok(None)), - "already-recorded identity skips" - ); - assert_eq!( - outstanding(&kv), - 0, - "credit released on the already-recorded skip" - ); - assert!(kv.inflight_records.lock().unwrap().is_empty()); - } - - fn seed_exact_state( - kv: &KvStageIntegration, - identity: &crate::kv_integration::PrefillKvIdentity, - ) { - kv.radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert_recurrent( - identity.namespace.clone(), - &identity.token_ids, - 32, - RadixExactEntry::new( - "pre-existing".to_string(), - ExactStatePayload::full_state(vec![9]), - ExactStateExtra::default(), - true, - ), - ) - .expect("pre-seeding the radix must succeed"); - } - - fn record_at_session_end( - kv: &Arc, - runtime: &mut RuntimeState, - identity: &crate::kv_integration::PrefillKvIdentity, - ) -> anyhow::Result { - kv.record_exact_state_at_session_end( - runtime, - SESSION, - identity, - CaptureAdmission::BestEffort, - None, - true, - ) - } - - /// A deferred capture of a checkpoint the cache already holds copies - /// nothing at registration. (The modelless runtime fails any export, so - /// reaching one would return an error.) - #[test] - fn a_deferred_capture_of_a_cached_checkpoint_skips_at_registration() { - let (kv, config) = harness(); - let mut runtime = RuntimeState::new_modelless_for_test(1); - let chat_identity = identity(&kv, &config, &[1, 2, 3]); - seed_exact_state(&kv, &chat_identity); - - let captured = record_at_session_end(&kv, &mut runtime, &chat_identity); - - assert!( - matches!( - captured, - Ok(crate::kv_integration::SessionEndCapture::Skipped) - ), - "{captured:?}" - ); - assert_eq!(outstanding(&kv), 0); - assert!(kv.inflight_records.lock().unwrap().is_empty()); - } - - /// A miss, and a radix too busy to say, both go on to copy the - /// recurrent state; session-end admission checks the radix again. - #[test] - fn a_deferred_capture_goes_ahead_on_a_miss_or_a_busy_radix() { - let (kv, config) = harness(); - let mut runtime = RuntimeState::new_modelless_for_test(1); - let chat_identity = identity(&kv, &config, &[1, 2, 3]); - - assert!( - record_at_session_end(&kv, &mut runtime, &chat_identity).is_err(), - "a miss reaches the recurrent export" - ); - - seed_exact_state(&kv, &chat_identity); - let radix_guard = kv.radix.lock().unwrap(); - let captured = record_at_session_end(&kv, &mut runtime, &chat_identity); - drop(radix_guard); - assert!( - captured.is_err(), - "a busy radix reaches the recurrent export" - ); - assert_eq!(outstanding(&kv), 0); - } - - /// record_exact_state releases its real credit when the payload export - /// fails (unknown session here), and nothing is enqueued. - #[test] - fn record_exact_state_releases_credit_when_export_fails() { - let (kv, config) = harness(); - let mut runtime = RuntimeState::new_modelless_for_test(1); - let chat_identity = identity(&kv, &config, &[1, 2, 3]); - let result = kv.record_exact_state( - &mut runtime, - "missing-session", - &chat_identity, - CaptureAdmission::BestEffort, - ); - assert!(result.is_err(), "exporting an unknown session must fail"); - assert_eq!(outstanding(&kv), 0, "credit released when the export fails"); - assert!(kv.inflight_records.lock().unwrap().is_empty()); - } -} diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/tests/reserved_admission.rs b/skippy/crates/skippy-serving/src/kv_integration/config/tests/reserved_admission.rs new file mode 100644 index 0000000000..a540f65795 --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/config/tests/reserved_admission.rs @@ -0,0 +1,490 @@ +//! Exact-state record admission end to end, on a modelless runtime. +use super::*; +use crate::kv_integration::exact_state::{CaptureAdmission, ExactStateAdmissionCredit}; +use crate::kv_integration::{ExactStateExtra, ExactStateRecordAdmission}; +use crate::runtime_state::RuntimeState; +use skippy_cache::ExactStatePayload; +use skippy_protocol::MessageBase; +use std::sync::atomic::Ordering as AtomicOrdering; + +const NAMESPACE: &str = "reserved-admission-test"; +const SESSION: &str = "harness-session"; +const WAIT: std::time::Duration = std::time::Duration::from_secs(30); + +fn harness_config() -> StageConfig { + StageConfig { + stage_id: "stage-0".to_string(), + model_id: NAMESPACE.to_string(), + kv_cache: Some(StageKvCacheConfig { + exact_max_bytes: None, + mode: StageKvCacheMode::LookupRecord, + max_entries: 8, + max_bytes: 0, + l2_max_bytes: 0, + codec: skippy_protocol::StageKvCacheCodec::Native, + min_tokens: 1, + shared_prefix_stride_tokens: 1, + shared_prefix_record_limit: 0, + prefill_admission: Default::default(), + retention: Default::default(), + }), + ..StageConfig::default() + } +} + +fn harness() -> (Arc, StageConfig) { + let config = harness_config(); + let kv = KvStageIntegration::from_test_state(&config, ModelStateKind::Recurrent) + .expect("kv integration init") + .expect("kv integration must be enabled for LookupRecord/KvRecurrent"); + (Arc::new(kv), config) +} + +fn message_base() -> MessageBase { + MessageBase { + schema_version: skippy_protocol::SCHEMA_VERSION, + run_id: NAMESPACE.to_string(), + request_id: "harness-request".to_string(), + session_id: SESSION.to_string(), + stage_id: "stage-0".to_string(), + stage_index: 0, + topology_id: NAMESPACE.to_string(), + model_id: Some(NAMESPACE.to_string()), + tokenizer_id: None, + chat_template_id: None, + seq: None, + } +} + +fn identity( + kv: &KvStageIntegration, + config: &StageConfig, + token_ids: &[i32], +) -> crate::kv_integration::PrefillKvIdentity { + kv.prefill_identity(config, &message_base(), 0, token_ids) +} + +fn record( + page_id: &str, + token_ids: Vec, + admission_credit: ExactStateAdmissionCredit, +) -> PendingExactStateRecord { + PendingExactStateRecord { + page_id: page_id.to_string(), + payload: ExactStatePayload::full_state(vec![1, 2, 3]), + extra: ExactStateExtra::default(), + namespace: NAMESPACE.to_string(), + retention_priority: 0, + token_ids, + l3_fill_claim: None, + write_through_l3: true, + l2_promotion_digest: None, + l3_cost: None, + admission_credit, + } +} + +fn acquire(kv: &KvStageIntegration, class: CaptureAdmission) -> Option { + ExactStateAdmissionCredit::acquire( + &kv.admission_outstanding, + &kv.admission_best_effort_outstanding, + class, + ) +} + +fn outstanding(kv: &KvStageIntegration) -> usize { + kv.admission_outstanding.load(AtomicOrdering::Acquire) +} + +fn best_effort_outstanding(kv: &KvStageIntegration) -> usize { + kv.admission_best_effort_outstanding + .load(AtomicOrdering::Acquire) +} + +fn stored(kv: &KvStageIntegration, token_ids: &[i32]) -> bool { + kv.radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .recurrent_exact(NAMESPACE, token_ids) + .is_some() +} + +/// Reserved-credit delivery end-to-end under an EXPLICITLY paused +/// recorder worker (no radix contention): the BestEffort payload is +/// received worker-side and paused BEFORE storage, the Continuation +/// payload is actually ENQUEUED behind it, both classes decline overflow, +/// and unpausing stores BOTH identities and drains every real credit; the +/// budget then admits and stores a recovery record. +#[test] +fn reserved_credits_deliver_continuation_payloads_and_recover_after_drain() { + let (kv, _config) = harness(); + kv.exact_state_worker_pause + .store(true, AtomicOrdering::Release); + + let be1 = acquire(&kv, CaptureAdmission::BestEffort).expect("first BestEffort admitted"); + assert_eq!( + kv.enqueue_exact_state_record(record("be1", vec![1, 2, 3], be1)), + ExactStateRecordAdmission::Queued, + ); + kv.wait_for_exact_state_worker_received(1, WAIT) + .expect("worker received the BestEffort record before storage"); + assert_eq!(outstanding(&kv), 1, "credit held by the paused worker"); + assert!( + !stored(&kv, &[1, 2, 3]), + "paused worker must not have stored yet" + ); + + assert!( + acquire(&kv, CaptureAdmission::BestEffort).is_none(), + "second BestEffort declined at the reserved cap" + ); + assert_eq!(best_effort_outstanding(&kv), 1); + + let pd1 = acquire(&kv, CaptureAdmission::Continuation) + .expect("Continuation admitted into the reserved share"); + assert_eq!( + kv.enqueue_exact_state_record(record("pd1", vec![4, 5, 6], pd1)), + ExactStateRecordAdmission::Queued, + "the Continuation payload must be enqueued, never dropped by the harness" + ); + assert_eq!(outstanding(&kv), 2); + assert!( + acquire(&kv, CaptureAdmission::Continuation).is_none(), + "total budget exhausted" + ); + + kv.exact_state_worker_pause + .store(false, AtomicOrdering::Release); + kv.wait_for_exact_state_recording(WAIT) + .expect("recorder drained both records without drops or panics"); + assert_eq!( + outstanding(&kv), + 0, + "credits released by real worker completion" + ); + assert_eq!(best_effort_outstanding(&kv), 0); + assert!(stored(&kv, &[1, 2, 3]), "BestEffort identity stored"); + assert!(stored(&kv, &[4, 5, 6]), "Continuation identity stored"); + + let recovered = + acquire(&kv, CaptureAdmission::Continuation).expect("budget recovers after the drain"); + assert_eq!( + kv.enqueue_exact_state_record(record("recovered", vec![7, 8], recovered)), + ExactStateRecordAdmission::Queued, + ); + kv.wait_for_exact_state_recording(WAIT) + .expect("recovered record stored"); + assert_eq!(outstanding(&kv), 0); + assert!(stored(&kv, &[7, 8]), "recovered identity stored"); +} + +/// Unhealthy recorder releases real credits on BOTH release paths: the +/// enqueue-level WorkerStopped drop, and the record_exact_state +/// try_begin_record decline that happens after acquisition. +#[test] +fn unhealthy_worker_releases_credits_on_both_release_paths() { + let (kv, config) = harness(); + kv.exact_state_record_worker_healthy + .store(false, AtomicOrdering::Release); + + let credit = + acquire(&kv, CaptureAdmission::BestEffort).expect("budget admits before the health gate"); + assert_eq!( + kv.enqueue_exact_state_record(record("stopped", vec![1], credit)), + ExactStateRecordAdmission::WorkerStopped, + ); + assert_eq!( + outstanding(&kv), + 0, + "enqueue-level WorkerStopped released the real credit" + ); + + let mut runtime = RuntimeState::new_modelless_for_test(1); + let chat_identity = identity(&kv, &config, &[1, 2, 3]); + let begin_record = + crate::frontend::capture_trace::POST_DECODE_NONE_BEGIN_RECORD.load(AtomicOrdering::Acquire); + let result = kv.record_exact_state( + &mut runtime, + SESSION, + &chat_identity, + CaptureAdmission::BestEffort, + ); + assert!( + matches!(result, Ok(None)), + "unhealthy worker must decline recording" + ); + assert_eq!( + crate::frontend::capture_trace::POST_DECODE_NONE_BEGIN_RECORD.load(AtomicOrdering::Acquire), + begin_record + 1, + "the decline happened at try_begin_record, i.e. after acquisition" + ); + assert_eq!( + outstanding(&kv), + 0, + "record_exact_state released the credit on the try_begin_record decline" + ); +} + +/// record_exact_state releases its real credit when the radix lock is +/// busy: the capture is skipped without waiting and the inflight page is +/// released. +/// A sliding-window cache can reuse rows below the boundary before the +/// session ends, so its stage copies them with the recurrent state. +#[test] +fn a_sliding_window_stage_does_not_defer_its_kv_copy() { + let (kv, _) = harness(); + assert_eq!( + kv.exact_state_payload(), + Some(StagePrefixCachePayload::KvRecurrent) + ); + let mut runtime = RuntimeState::new_modelless_for_test(1); + assert!(kv.defers_kv_copy(&mut runtime, SESSION, 3)); + + runtime.sliding_window_kv_for_test = true; + assert!(!kv.defers_kv_copy(&mut runtime, SESSION, 3)); +} + +#[test] +fn record_exact_state_releases_credit_when_radix_is_busy() { + let (kv, config) = harness(); + let mut runtime = RuntimeState::new_modelless_for_test(1); + let chat_identity = identity(&kv, &config, &[1, 2, 3]); + let radix_guard = kv.radix.lock().unwrap(); + let result = kv.record_exact_state( + &mut runtime, + SESSION, + &chat_identity, + CaptureAdmission::BestEffort, + ); + drop(radix_guard); + assert!( + matches!(result, Ok(None)), + "busy radix skips without waiting" + ); + assert_eq!(outstanding(&kv), 0, "credit released on the busy skip"); + assert!( + kv.inflight_records.lock().unwrap().is_empty(), + "inflight page released on the busy skip" + ); +} + +/// retained_exact_identity requires the EXACT radix node: a retained +/// shorter entry must not certify a longer identity, and a longer entry +/// must not certify its own prefix. +#[test] +fn retained_exact_identity_requires_the_exact_radix_node() { + let (kv, config) = harness(); + let chat_identity = identity(&kv, &config, &[1, 2, 3]); + kv.radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert_recurrent( + chat_identity.namespace.clone(), + &chat_identity.token_ids, + 32, + RadixExactEntry::new( + "exact".to_string(), + ExactStatePayload::full_state(vec![9]), + ExactStateExtra::default(), + true, + ), + ) + .expect("seeding the radix must succeed"); + + assert!( + kv.retained_exact_identity(&chat_identity.namespace, &[1, 2, 3]), + "the exact node is retained" + ); + assert!( + !kv.retained_exact_identity(&chat_identity.namespace, &[1, 2]), + "a shorter query must not be certified by the longer retained entry" + ); + assert!( + !kv.retained_exact_identity(&chat_identity.namespace, &[1, 2, 3, 4]), + "a longer identity must not be certified by a retained shorter prefix" + ); + assert!( + !kv.retained_exact_identity(&chat_identity.namespace, &[9, 9, 9]), + "an unrelated identity is absent" + ); +} + +/// record_exact_state releases its real credit when the identity is +/// already recorded. +#[test] +fn record_exact_state_releases_credit_when_already_recorded() { + let (kv, config) = harness(); + let mut runtime = RuntimeState::new_modelless_for_test(1); + let chat_identity = identity(&kv, &config, &[1, 2, 3]); + kv.radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert_recurrent( + chat_identity.namespace.clone(), + &chat_identity.token_ids, + 32, + RadixExactEntry::new( + "pre-existing".to_string(), + ExactStatePayload::full_state(vec![9]), + ExactStateExtra::default(), + true, + ), + ) + .expect("pre-seeding the radix must succeed"); + let result = kv.record_exact_state( + &mut runtime, + SESSION, + &chat_identity, + CaptureAdmission::BestEffort, + ); + assert!( + matches!(result, Ok(None)), + "already-recorded identity skips" + ); + assert_eq!( + outstanding(&kv), + 0, + "credit released on the already-recorded skip" + ); + assert!(kv.inflight_records.lock().unwrap().is_empty()); +} + +fn seed_exact_state(kv: &KvStageIntegration, identity: &crate::kv_integration::PrefillKvIdentity) { + kv.radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert_recurrent( + identity.namespace.clone(), + &identity.token_ids, + 32, + RadixExactEntry::new( + "pre-existing".to_string(), + ExactStatePayload::full_state(vec![9]), + ExactStateExtra::default(), + true, + ), + ) + .expect("pre-seeding the radix must succeed"); +} + +fn record_at_session_end( + kv: &Arc, + runtime: &mut RuntimeState, + identity: &crate::kv_integration::PrefillKvIdentity, +) -> anyhow::Result { + kv.record_exact_state_at_session_end( + runtime, + SESSION, + identity, + CaptureAdmission::BestEffort, + None, + true, + ) +} + +/// A deferred capture of a checkpoint the cache already holds copies +/// nothing at registration. (The modelless runtime fails any export, so +/// reaching one would return an error.) +#[test] +fn a_deferred_capture_of_a_cached_checkpoint_skips_at_registration() { + let (kv, config) = harness(); + let mut runtime = RuntimeState::new_modelless_for_test(1); + let chat_identity = identity(&kv, &config, &[1, 2, 3]); + seed_exact_state(&kv, &chat_identity); + + let captured = record_at_session_end(&kv, &mut runtime, &chat_identity); + + assert!( + matches!( + captured, + Ok(crate::kv_integration::SessionEndCapture::Skipped) + ), + "{captured:?}" + ); + assert_eq!(outstanding(&kv), 0); + assert!(kv.inflight_records.lock().unwrap().is_empty()); +} + +/// A miss, and a radix too busy to say, both go on to copy the +/// recurrent state; session-end admission checks the radix again. +#[test] +fn a_deferred_capture_goes_ahead_on_a_miss_or_a_busy_radix() { + let (kv, config) = harness(); + let mut runtime = RuntimeState::new_modelless_for_test(1); + let chat_identity = identity(&kv, &config, &[1, 2, 3]); + + assert!( + record_at_session_end(&kv, &mut runtime, &chat_identity).is_err(), + "a miss reaches the recurrent export" + ); + + seed_exact_state(&kv, &chat_identity); + let radix_guard = kv.radix.lock().unwrap(); + let captured = record_at_session_end(&kv, &mut runtime, &chat_identity); + drop(radix_guard); + assert!( + captured.is_err(), + "a busy radix reaches the recurrent export" + ); + assert_eq!(outstanding(&kv), 0); +} + +/// record_exact_state releases its real credit when the payload export +/// fails (unknown session here), and nothing is enqueued. +#[test] +fn record_exact_state_releases_credit_when_export_fails() { + let (kv, config) = harness(); + let mut runtime = RuntimeState::new_modelless_for_test(1); + let chat_identity = identity(&kv, &config, &[1, 2, 3]); + let result = kv.record_exact_state( + &mut runtime, + "missing-session", + &chat_identity, + CaptureAdmission::BestEffort, + ); + assert!(result.is_err(), "exporting an unknown session must fail"); + assert_eq!(outstanding(&kv), 0, "credit released when the export fails"); + assert!(kv.inflight_records.lock().unwrap().is_empty()); +} + +/// Without L3, a snapshot that every stored entry outranks would be evicted +/// as soon as it is stored, so it is not exported at all. A snapshot at the +/// stored entries' tier still goes ahead (and here fails to export, as the +/// session does not exist). +#[test] +fn a_crowded_out_snapshot_is_not_exported_without_l3() { + let (kv, config) = harness(); + assert!(kv.l3.is_none()); + for token in 0..kv.exact_max_entries { + let token = i32::try_from(token).unwrap() + 100; + seed_exact_state(&kv, &identity(&kv, &config, &[token])); + } + let mut runtime = RuntimeState::new_modelless_for_test(1); + let mut mesh = identity(&kv, &config, &[1, 2, 3]); + mesh.identity.chat_template_id = skippy_inference_api::InferenceRequestClass::new( + skippy_inference_api::InferenceRequestTier::Mesh, + false, + ) + .cache_namespace(None) + .unwrap(); + assert!(mesh.retention_priority() < identity(&kv, &config, &[1]).retention_priority()); + + let skipped = kv.record_exact_state( + &mut runtime, + "missing-session", + &mesh, + CaptureAdmission::BestEffort, + ); + assert!(matches!(skipped, Ok(None)), "{skipped:?}"); + assert_eq!(outstanding(&kv), 0); + + let local = identity(&kv, &config, &[1, 2, 3]); + let exported = kv.record_exact_state( + &mut runtime, + "missing-session", + &local, + CaptureAdmission::BestEffort, + ); + assert!(exported.is_err(), "a local snapshot is exported"); + assert_eq!(outstanding(&kv), 0); +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs index 78783234e4..e1bbdd4946 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs @@ -424,6 +424,7 @@ impl KvStageIntegration { payload, extra, namespace: identity.namespace.clone(), + retention_priority: identity.retention_priority(), token_ids: stored_tokens, l3_fill_claim: None, write_through_l3: true, @@ -794,6 +795,18 @@ impl KvStageIntegration { self.finish_record(&identity.page_id); return Ok(None); } + // Without L3 there is nowhere for a crowded-out snapshot to spill. + if !already_recorded + && (!write_through_l3 || self.l3.is_none()) + && exact_state_crowded_out( + &self.radix, + self.exact_max_entries, + identity.retention_priority(), + ) + { + self.finish_record(&identity.page_id); + return Ok(None); + } let Some(reservation) = self.reserve_snapshot_host_memory( runtime, session_id, @@ -851,6 +864,7 @@ impl KvStageIntegration { payload, extra, namespace: identity.namespace.clone(), + retention_priority: identity.retention_priority(), token_ids: identity.token_ids.clone(), l3_fill_claim: None, write_through_l3, @@ -1180,6 +1194,7 @@ impl KvStageIntegration { payload: fill.payload, extra: ExactStateExtra { kv_desc }, namespace: identity.namespace.clone(), + retention_priority: identity.retention_priority(), token_ids: identity.token_ids[..token_count as usize].to_vec(), l3_fill_claim: Some(l3_fill_claim_key(l3, location)), write_through_l3: false, @@ -1255,6 +1270,25 @@ fn try_touch_exact_state( } } +/// Whether a new entry kept at `retention` would be evicted again as soon as +/// it is stored: the cache is full and every entry it could evict outranks +/// it (a higher request tier's). Exporting it would only cost the copy. +fn exact_state_crowded_out( + radix: &std::sync::Mutex< + skippy_cache::UnifiedRadixCache, + >, + max_entries: usize, + retention: u64, +) -> bool { + let Ok(radix) = radix.try_lock() else { + return false; + }; + radix.stats().recurrent_entries >= max_entries + && radix + .recurrent_victim_retention(super::RadixExactEntry::retention_priority) + .is_none_or(|victim| victim > retention) +} + fn is_native_kv_unavailable(error: &anyhow::Error) -> bool { error.chain().any(|cause| { let message = cause.to_string(); @@ -1309,7 +1343,10 @@ mod tests { use skippy_cache::{L3Location, UnifiedRadixCache}; - use super::{is_native_kv_unavailable, preflight_l3_kv_location, try_touch_exact_state}; + use super::{ + exact_state_crowded_out, is_native_kv_unavailable, preflight_l3_kv_location, + try_touch_exact_state, + }; type TestRadix = UnifiedRadixCache< crate::kv_integration::RadixResidentEntry, @@ -1322,6 +1359,35 @@ mod tests { assert!(is_native_kv_unavailable(&error)); } + #[test] + fn a_snapshot_every_stored_entry_outranks_is_not_exported_into_a_full_cache() { + let cache = Mutex::new(TestRadix::new()); + for (index, retention) in [(1, 2), (2, 2)] { + cache + .lock() + .unwrap() + .insert_recurrent( + "namespace", + &[index], + 32, + crate::kv_integration::RadixExactEntry::new( + format!("page-{index}"), + crate::kv_integration::ExactStatePayload::full_state(vec![1]), + crate::kv_integration::ExactStateExtra::default(), + false, + ) + .with_retention_priority(retention), + ) + .unwrap(); + } + // Full of entries kept at 2: a 0 would evict itself; a 2 evicts the + // older of its peers. + assert!(exact_state_crowded_out(&cache, 2, 0)); + assert!(!exact_state_crowded_out(&cache, 2, 2)); + // With room to spare, any snapshot is kept. + assert!(!exact_state_crowded_out(&cache, 3, 0)); + } + #[test] fn busy_exact_state_lock_skips_touch_without_waiting() { let cache = Arc::new(Mutex::new(TestRadix::new())); diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs index 32f22f0c33..cd2a83dd65 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs @@ -83,6 +83,7 @@ fn resident(kv: &KvStageIntegration, identity: &PrefillKvIdentity, count: usize, seq_id: seq, token_count: count as u64, recompute_cost: 1, + retention_priority: 0, }, ) .unwrap(); diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state_record_queue_tests.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state_record_queue_tests.rs new file mode 100644 index 0000000000..8e20ade36a --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state_record_queue_tests.rs @@ -0,0 +1,516 @@ +//! Tests for the bounded exact-state record queue and its worker. + +use skippy_cache::ExactStatePayload; +use std::sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, + mpsc::sync_channel, +}; + +use super::{ + BTreeSet, EXACT_STATE_RECORD_CAPACITY, ExactStateExtra, ExactStateRecordAdmission, + ExactStateRecordWorker, ExactStateWorkerHandles, KvLifecycleEvent, KvLifecycleObserver, + PendingExactStateRecord, enqueue_exact_state_record, run_exact_state_record_job, +}; +use crate::kv_integration::exact_state::{CaptureAdmission, ExactStateAdmissionCredit}; + +/// A fresh, observable budget: the SAME counters back every credit a test +/// creates, so release paths are asserted on real accounting, not on +/// throwaway stubs. +fn budget() -> (Arc, Arc) { + (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))) +} + +fn credit( + total: &Arc, + best_effort: &Arc, + class: CaptureAdmission, +) -> ExactStateAdmissionCredit { + ExactStateAdmissionCredit::acquire(total, best_effort, class) + .expect("a fresh budget must admit") +} + +struct RecordingObserver(Arc>>); + +impl KvLifecycleObserver for RecordingObserver { + fn observe(&self, event: KvLifecycleEvent) { + self.0.lock().unwrap().push(event); + } +} + +fn pending(page_id: &str, admission_credit: ExactStateAdmissionCredit) -> PendingExactStateRecord { + PendingExactStateRecord { + page_id: page_id.to_string(), + payload: ExactStatePayload::full_state(vec![1]), + extra: ExactStateExtra::default(), + namespace: "test".to_string(), + retention_priority: 0, + token_ids: vec![1], + l3_fill_claim: None, + write_through_l3: true, + l2_promotion_digest: None, + l3_cost: None, + admission_credit, + } +} + +fn pending_with_bytes(page_id: &str, bytes: usize) -> PendingExactStateRecord { + let (total, best_effort) = budget(); + PendingExactStateRecord { + payload: ExactStatePayload::full_state(vec![1; bytes]), + ..pending( + page_id, + credit(&total, &best_effort, CaptureAdmission::BestEffort), + ) + } +} + +const CAP: u64 = 1024; + +#[test] +fn final_worker_owner_drains_queued_records_before_drop_returns() { + let (sender, receiver) = sync_channel(2); + let completed = Arc::new(AtomicUsize::new(0)); + let worker_completed = completed.clone(); + let task = std::thread::spawn(move || { + while receiver.recv().is_ok() { + worker_completed.fetch_add(1, Ordering::Release); + } + }); + let worker = Arc::new(ExactStateRecordWorker::new(sender, task, None, None)); + let (total, best_effort) = budget(); + worker.with_sender(|sender| { + sender + .unwrap() + .send(pending( + "latest", + credit(&total, &best_effort, CaptureAdmission::BestEffort), + )) + .unwrap() + }); + + drop(worker); + + assert_eq!(completed.load(Ordering::Acquire), 1); +} + +#[test] +fn queue_is_bounded_in_bytes_not_entries() { + let (sender, _receiver) = sync_channel(EXACT_STATE_RECORD_CAPACITY); + let inflight = Mutex::new(BTreeSet::from(["a".to_string(), "b".to_string()])); + let queued = AtomicU64::new(0); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(0); + let queue_bytes = AtomicU64::new(0); + let worker_healthy = AtomicBool::new(true); + + assert_eq!( + enqueue_exact_state_record( + &sender, + &inflight, + &queued, + &dropped, + &pending_count, + &queue_bytes, + CAP, + &worker_healthy, + pending_with_bytes("a", 700), + ), + ExactStateRecordAdmission::Queued + ); + assert_eq!(queue_bytes.load(Ordering::Relaxed), 700); + + // Plenty of entry slots left; the bytes are what is full. + assert_eq!( + enqueue_exact_state_record( + &sender, + &inflight, + &queued, + &dropped, + &pending_count, + &queue_bytes, + CAP, + &worker_healthy, + pending_with_bytes("b", 700), + ), + ExactStateRecordAdmission::DroppedFull + ); + assert_eq!( + queue_bytes.load(Ordering::Relaxed), + 700, + "a dropped record left bytes claimed" + ); + assert!(!inflight.lock().unwrap().contains("b")); + assert_eq!(dropped.load(Ordering::Relaxed), 1); + assert_eq!(pending_count.load(Ordering::Relaxed), 1); +} + +#[test] +fn one_oversized_record_is_admitted_into_an_empty_queue() { + let (sender, _receiver) = sync_channel(EXACT_STATE_RECORD_CAPACITY); + let inflight = Mutex::new(BTreeSet::from(["huge".to_string()])); + let queued = AtomicU64::new(0); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(0); + let queue_bytes = AtomicU64::new(0); + let worker_healthy = AtomicBool::new(true); + + assert_eq!( + enqueue_exact_state_record( + &sender, + &inflight, + &queued, + &dropped, + &pending_count, + &queue_bytes, + CAP, + &worker_healthy, + pending_with_bytes("huge", 4096), + ), + ExactStateRecordAdmission::Queued, + "a large model could never record if one export over the cap were refused" + ); + assert_eq!(queue_bytes.load(Ordering::Relaxed), 4096); + assert!(queue_bytes.load(Ordering::Acquire) >= CAP); +} + +#[test] +fn finishing_a_record_releases_its_bytes() { + let inflight = Mutex::new(BTreeSet::from(["done".to_string()])); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(1); + let queue_bytes = AtomicU64::new(300); + let worker_healthy = AtomicBool::new(true); + let worker_panics = AtomicU64::new(0); + + run_exact_state_record_job( + ExactStateWorkerHandles { + inflight_records: &inflight, + dropped: &dropped, + pending_count: &pending_count, + queue_bytes: &queue_bytes, + worker_healthy: &worker_healthy, + worker_panics: &worker_panics, + }, + None, + pending_with_bytes("done", 300), + |_| Ok(()), + ); + + assert_eq!(queue_bytes.load(Ordering::Relaxed), 0); + assert_eq!(pending_count.load(Ordering::Relaxed), 0); + assert!(inflight.lock().unwrap().is_empty()); + assert_eq!(dropped.load(Ordering::Relaxed), 0); +} + +#[test] +fn full_queue_drops_optional_record_and_releases_inflight_page() { + let (total, best_effort) = budget(); + let (sender, receiver) = sync_channel(1); + // One BestEffort record occupies the channel buffer; its credit stays + // observable in `total`. + sender + .send(pending( + "queued", + credit(&total, &best_effort, CaptureAdmission::BestEffort), + )) + .unwrap(); + let inflight = Mutex::new(BTreeSet::from(["dropped".to_string()])); + let queued = AtomicU64::new(0); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(0); + let queue_bytes = AtomicU64::new(0); + let worker_healthy = AtomicBool::new(true); + + assert_eq!( + enqueue_exact_state_record( + &sender, + &inflight, + &queued, + &dropped, + &pending_count, + &queue_bytes, + CAP, + &worker_healthy, + pending( + "dropped", + credit(&total, &best_effort, CaptureAdmission::Continuation) + ), + ), + ExactStateRecordAdmission::DroppedFull + ); + assert!(!inflight.lock().unwrap().contains("dropped")); + assert_eq!(queued.load(Ordering::Relaxed), 0); + assert_eq!(dropped.load(Ordering::Relaxed), 1); + assert_eq!(pending_count.load(Ordering::Relaxed), 0); + assert_eq!( + total.load(Ordering::Acquire), + 1, + "the Full rejection must release the dropped record's credit; the buffered one stays" + ); + assert_eq!( + best_effort.load(Ordering::Acquire), + 1, + "the buffered BestEffort credit is still outstanding" + ); + + // Receiver drop: discarding the channel drops the buffered record and + // releases its credit too. + drop(sender); + drop(receiver); + assert_eq!( + total.load(Ordering::Acquire), + 0, + "receiver drop released the buffered credit" + ); + assert_eq!(best_effort.load(Ordering::Acquire), 0); +} + +#[test] +fn disconnected_worker_releases_inflight_page() { + let (total, best_effort) = budget(); + let (sender, receiver) = sync_channel(1); + drop(receiver); + let inflight = Mutex::new(BTreeSet::from(["orphaned".to_string()])); + let queued = AtomicU64::new(0); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(0); + let queue_bytes = AtomicU64::new(0); + let worker_healthy = AtomicBool::new(true); + + assert_eq!( + enqueue_exact_state_record( + &sender, + &inflight, + &queued, + &dropped, + &pending_count, + &queue_bytes, + CAP, + &worker_healthy, + pending( + "orphaned", + credit(&total, &best_effort, CaptureAdmission::Continuation) + ), + ), + ExactStateRecordAdmission::WorkerStopped + ); + assert!(!inflight.lock().unwrap().contains("orphaned")); + assert_eq!(dropped.load(Ordering::Relaxed), 1); + assert_eq!(pending_count.load(Ordering::Relaxed), 0); + assert_eq!( + total.load(Ordering::Acquire), + 0, + "the disconnected channel must release the orphaned credit" + ); + assert_eq!(best_effort.load(Ordering::Acquire), 0); +} + +#[test] +fn worker_keeps_page_inflight_until_record_finishes() { + let (total, best_effort) = budget(); + let (sender, receiver) = sync_channel(1); + let inflight = Arc::new(Mutex::new(BTreeSet::from(["page".to_string()]))); + let worker_inflight = inflight.clone(); + let queued = AtomicU64::new(0); + let dropped = AtomicU64::new(0); + let pending_count = Arc::new(AtomicUsize::new(0)); + let worker_pending_count = pending_count.clone(); + let queue_bytes = AtomicU64::new(0); + let worker_healthy = AtomicBool::new(true); + + assert_eq!( + enqueue_exact_state_record( + &sender, + &inflight, + &queued, + &dropped, + &pending_count, + &queue_bytes, + CAP, + &worker_healthy, + pending( + "page", + credit(&total, &best_effort, CaptureAdmission::Continuation) + ), + ), + ExactStateRecordAdmission::Queued + ); + assert!(inflight.lock().unwrap().contains("page")); + assert_eq!( + total.load(Ordering::Acquire), + 1, + "the credit is outstanding while the record sits in the channel" + ); + + let worker = std::thread::spawn(move || { + let pending = receiver.recv().unwrap(); + assert!(worker_inflight.lock().unwrap().contains(&pending.page_id)); + worker_inflight.lock().unwrap().remove(&pending.page_id); + worker_pending_count.fetch_sub(1, Ordering::Relaxed); + // `pending` (and its credit) drops when this closure returns. + }); + worker.join().unwrap(); + + assert!(!inflight.lock().unwrap().contains("page")); + assert_eq!(queued.load(Ordering::Relaxed), 1); + assert_eq!(dropped.load(Ordering::Relaxed), 0); + assert_eq!(pending_count.load(Ordering::Relaxed), 0); + assert_eq!( + total.load(Ordering::Acquire), + 0, + "the credit released when the record dropped after processing" + ); +} + +#[test] +fn worker_success_notifies_completed_not_mere_admission() { + let inflight = Mutex::new(BTreeSet::from(["written".to_string()])); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(1); + let queue_bytes = AtomicU64::new(1); + let worker_healthy = AtomicBool::new(true); + let worker_panics = AtomicU64::new(0); + let events: Arc>> = Arc::default(); + let observer: Arc = Arc::new(RecordingObserver(events.clone())); + let (total, best_effort) = budget(); + + run_exact_state_record_job( + ExactStateWorkerHandles { + inflight_records: &inflight, + dropped: &dropped, + pending_count: &pending_count, + queue_bytes: &queue_bytes, + worker_healthy: &worker_healthy, + worker_panics: &worker_panics, + }, + Some(&observer), + pending( + "written", + credit(&total, &best_effort, CaptureAdmission::Continuation), + ), + |_| Ok(()), + ); + + assert_eq!( + *events.lock().unwrap(), + vec![KvLifecycleEvent::ExactStateRecordCompleted] + ); + assert_eq!(dropped.load(Ordering::Relaxed), 0); + assert_eq!( + total.load(Ordering::Acquire), + 0, + "successful completion released the real credit" + ); +} + +#[test] +fn worker_write_error_notifies_failed_not_completed() { + let inflight = Mutex::new(BTreeSet::from(["broken".to_string()])); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(1); + let queue_bytes = AtomicU64::new(1); + let worker_healthy = AtomicBool::new(true); + let worker_panics = AtomicU64::new(0); + let events: Arc>> = Arc::default(); + let observer: Arc = Arc::new(RecordingObserver(events.clone())); + let (total, best_effort) = budget(); + + run_exact_state_record_job( + ExactStateWorkerHandles { + inflight_records: &inflight, + dropped: &dropped, + pending_count: &pending_count, + queue_bytes: &queue_bytes, + worker_healthy: &worker_healthy, + worker_panics: &worker_panics, + }, + Some(&observer), + pending( + "broken", + credit(&total, &best_effort, CaptureAdmission::Continuation), + ), + |_| anyhow::bail!("simulated write failure"), + ); + + assert_eq!( + *events.lock().unwrap(), + vec![KvLifecycleEvent::ExactStateRecordFailed] + ); + assert_eq!(dropped.load(Ordering::Relaxed), 1); + assert_eq!( + total.load(Ordering::Acquire), + 0, + "the worker error path released the real credit" + ); + assert_eq!(best_effort.load(Ordering::Acquire), 0); +} + +#[test] +fn worker_panic_fails_closed_and_releases_all_record_bookkeeping() { + let (sender, _receiver) = sync_channel(1); + let inflight = Mutex::new(BTreeSet::from(["panicked".to_string()])); + let queued = AtomicU64::new(0); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(1); + let queue_bytes = AtomicU64::new(1); + let worker_healthy = AtomicBool::new(true); + let worker_panics = AtomicU64::new(0); + let (total, best_effort) = budget(); + + run_exact_state_record_job( + ExactStateWorkerHandles { + inflight_records: &inflight, + dropped: &dropped, + pending_count: &pending_count, + queue_bytes: &queue_bytes, + worker_healthy: &worker_healthy, + worker_panics: &worker_panics, + }, + None, + pending( + "panicked", + credit(&total, &best_effort, CaptureAdmission::Continuation), + ), + |_| panic!("injected exact-record worker failure"), + ); + + assert!(!worker_healthy.load(Ordering::Acquire)); + assert_eq!(worker_panics.load(Ordering::Relaxed), 1); + assert_eq!(dropped.load(Ordering::Relaxed), 1); + assert_eq!(pending_count.load(Ordering::Acquire), 0); + assert!(inflight.lock().unwrap().is_empty()); + assert_eq!( + total.load(Ordering::Acquire), + 0, + "the unwind dropped the record and released its real credit" + ); + assert_eq!(best_effort.load(Ordering::Acquire), 0); + + inflight.lock().unwrap().insert("later".to_string()); + assert_eq!( + enqueue_exact_state_record( + &sender, + &inflight, + &queued, + &dropped, + &pending_count, + &queue_bytes, + CAP, + &worker_healthy, + pending( + "later", + credit(&total, &best_effort, CaptureAdmission::Continuation) + ), + ), + ExactStateRecordAdmission::WorkerStopped + ); + assert!(inflight.lock().unwrap().is_empty()); + assert_eq!(dropped.load(Ordering::Relaxed), 2); + assert_eq!(pending_count.load(Ordering::Acquire), 0); + assert_eq!( + total.load(Ordering::Acquire), + 0, + "the WorkerStopped follow-up also released its real credit" + ); +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs b/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs index 3bb264da91..8f3215ee15 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs @@ -338,6 +338,7 @@ impl KvStageIntegration { payload, extra: ExactStateExtra { kv_desc }, namespace: identity.namespace.clone(), + retention_priority: identity.retention_priority(), token_ids: identity.token_ids[..token_count as usize].to_vec(), l3_fill_claim: None, write_through_l3: false, diff --git a/skippy/crates/skippy-serving/src/kv_integration/mod.rs b/skippy/crates/skippy-serving/src/kv_integration/mod.rs index a5fccc69dd..51716bee8a 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/mod.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/mod.rs @@ -283,6 +283,9 @@ pub(crate) struct PendingExactStateRecord { pub(crate) payload: ExactStatePayload, pub(crate) extra: ExactStateExtra, pub(crate) namespace: String, + /// Eviction order: lower values are evicted first. See + /// [`PrefillKvIdentity::retention_priority`]. + pub(crate) retention_priority: u64, pub(crate) token_ids: Vec, /// When this record re-warms the radix after an L3 fill, the fill's /// claim key. The worker releases it only once the radix insert lands, @@ -313,6 +316,9 @@ pub(crate) struct RadixResidentEntry { /// Deterministic first-order estimate of work needed to recreate this /// entry: cached tokens multiplied by stage-local layer count. pub(crate) recompute_cost: u64, + /// Eviction order: entries with a lower value are evicted first. See + /// [`PrefillKvIdentity::retention_priority`]. + pub(crate) retention_priority: u64, } #[derive(Debug, Clone)] @@ -322,6 +328,8 @@ pub(crate) struct RadixExactEntry { pub(crate) extra: ExactStateExtra, /// Whether a later resident hit may promote this entry into durable L3. pub(crate) l3_promotion_eligible: bool, + /// Eviction order; see [`RadixResidentEntry::retention_priority`]. + retention_priority: u64, } impl RadixExactEntry { @@ -336,8 +344,20 @@ impl RadixExactEntry { payload, extra, l3_promotion_eligible, + retention_priority: skippy_inference_api::InferenceRequestTier::Local.priority(), } } + + /// Record the tier priority of the request that produced this state. + pub(crate) fn with_retention_priority(mut self, retention_priority: u64) -> Self { + self.retention_priority = retention_priority; + self + } + + /// Eviction order: lower values are evicted first. + pub(crate) fn retention_priority(&self) -> u64 { + self.retention_priority + } } #[derive(Debug)] @@ -1393,524 +1413,7 @@ fn local_trust_checksum(page_id: &str, byte_size: u64) -> Checksum { } #[cfg(test)] -mod exact_state_record_queue_tests { - use skippy_cache::ExactStatePayload; - use std::sync::{ - Arc, Mutex, - atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, - mpsc::sync_channel, - }; - - use super::{ - BTreeSet, EXACT_STATE_RECORD_CAPACITY, ExactStateExtra, ExactStateRecordAdmission, - ExactStateRecordWorker, ExactStateWorkerHandles, KvLifecycleEvent, KvLifecycleObserver, - PendingExactStateRecord, enqueue_exact_state_record, run_exact_state_record_job, - }; - use crate::kv_integration::exact_state::{CaptureAdmission, ExactStateAdmissionCredit}; - - /// A fresh, observable budget: the SAME counters back every credit a test - /// creates, so release paths are asserted on real accounting, not on - /// throwaway stubs. - fn budget() -> (Arc, Arc) { - (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))) - } - - fn credit( - total: &Arc, - best_effort: &Arc, - class: CaptureAdmission, - ) -> ExactStateAdmissionCredit { - ExactStateAdmissionCredit::acquire(total, best_effort, class) - .expect("a fresh budget must admit") - } - - struct RecordingObserver(Arc>>); - - impl KvLifecycleObserver for RecordingObserver { - fn observe(&self, event: KvLifecycleEvent) { - self.0.lock().unwrap().push(event); - } - } - - fn pending( - page_id: &str, - admission_credit: ExactStateAdmissionCredit, - ) -> PendingExactStateRecord { - PendingExactStateRecord { - page_id: page_id.to_string(), - payload: ExactStatePayload::full_state(vec![1]), - extra: ExactStateExtra::default(), - namespace: "test".to_string(), - token_ids: vec![1], - l3_fill_claim: None, - write_through_l3: true, - l2_promotion_digest: None, - l3_cost: None, - admission_credit, - } - } - - fn pending_with_bytes(page_id: &str, bytes: usize) -> PendingExactStateRecord { - let (total, best_effort) = budget(); - PendingExactStateRecord { - payload: ExactStatePayload::full_state(vec![1; bytes]), - ..pending( - page_id, - credit(&total, &best_effort, CaptureAdmission::BestEffort), - ) - } - } - - const CAP: u64 = 1024; - - #[test] - fn final_worker_owner_drains_queued_records_before_drop_returns() { - let (sender, receiver) = sync_channel(2); - let completed = Arc::new(AtomicUsize::new(0)); - let worker_completed = completed.clone(); - let task = std::thread::spawn(move || { - while receiver.recv().is_ok() { - worker_completed.fetch_add(1, Ordering::Release); - } - }); - let worker = Arc::new(ExactStateRecordWorker::new(sender, task, None, None)); - let (total, best_effort) = budget(); - worker.with_sender(|sender| { - sender - .unwrap() - .send(pending( - "latest", - credit(&total, &best_effort, CaptureAdmission::BestEffort), - )) - .unwrap() - }); - - drop(worker); - - assert_eq!(completed.load(Ordering::Acquire), 1); - } - - #[test] - fn queue_is_bounded_in_bytes_not_entries() { - let (sender, _receiver) = sync_channel(EXACT_STATE_RECORD_CAPACITY); - let inflight = Mutex::new(BTreeSet::from(["a".to_string(), "b".to_string()])); - let queued = AtomicU64::new(0); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(0); - let queue_bytes = AtomicU64::new(0); - let worker_healthy = AtomicBool::new(true); - - assert_eq!( - enqueue_exact_state_record( - &sender, - &inflight, - &queued, - &dropped, - &pending_count, - &queue_bytes, - CAP, - &worker_healthy, - pending_with_bytes("a", 700), - ), - ExactStateRecordAdmission::Queued - ); - assert_eq!(queue_bytes.load(Ordering::Relaxed), 700); - - // Plenty of entry slots left; the bytes are what is full. - assert_eq!( - enqueue_exact_state_record( - &sender, - &inflight, - &queued, - &dropped, - &pending_count, - &queue_bytes, - CAP, - &worker_healthy, - pending_with_bytes("b", 700), - ), - ExactStateRecordAdmission::DroppedFull - ); - assert_eq!( - queue_bytes.load(Ordering::Relaxed), - 700, - "a dropped record left bytes claimed" - ); - assert!(!inflight.lock().unwrap().contains("b")); - assert_eq!(dropped.load(Ordering::Relaxed), 1); - assert_eq!(pending_count.load(Ordering::Relaxed), 1); - } - - #[test] - fn one_oversized_record_is_admitted_into_an_empty_queue() { - let (sender, _receiver) = sync_channel(EXACT_STATE_RECORD_CAPACITY); - let inflight = Mutex::new(BTreeSet::from(["huge".to_string()])); - let queued = AtomicU64::new(0); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(0); - let queue_bytes = AtomicU64::new(0); - let worker_healthy = AtomicBool::new(true); - - assert_eq!( - enqueue_exact_state_record( - &sender, - &inflight, - &queued, - &dropped, - &pending_count, - &queue_bytes, - CAP, - &worker_healthy, - pending_with_bytes("huge", 4096), - ), - ExactStateRecordAdmission::Queued, - "a large model could never record if one export over the cap were refused" - ); - assert_eq!(queue_bytes.load(Ordering::Relaxed), 4096); - assert!(queue_bytes.load(Ordering::Acquire) >= CAP); - } - - #[test] - fn finishing_a_record_releases_its_bytes() { - let inflight = Mutex::new(BTreeSet::from(["done".to_string()])); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(1); - let queue_bytes = AtomicU64::new(300); - let worker_healthy = AtomicBool::new(true); - let worker_panics = AtomicU64::new(0); - - run_exact_state_record_job( - ExactStateWorkerHandles { - inflight_records: &inflight, - dropped: &dropped, - pending_count: &pending_count, - queue_bytes: &queue_bytes, - worker_healthy: &worker_healthy, - worker_panics: &worker_panics, - }, - None, - pending_with_bytes("done", 300), - |_| Ok(()), - ); - - assert_eq!(queue_bytes.load(Ordering::Relaxed), 0); - assert_eq!(pending_count.load(Ordering::Relaxed), 0); - assert!(inflight.lock().unwrap().is_empty()); - assert_eq!(dropped.load(Ordering::Relaxed), 0); - } - - #[test] - fn full_queue_drops_optional_record_and_releases_inflight_page() { - let (total, best_effort) = budget(); - let (sender, receiver) = sync_channel(1); - // One BestEffort record occupies the channel buffer; its credit stays - // observable in `total`. - sender - .send(pending( - "queued", - credit(&total, &best_effort, CaptureAdmission::BestEffort), - )) - .unwrap(); - let inflight = Mutex::new(BTreeSet::from(["dropped".to_string()])); - let queued = AtomicU64::new(0); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(0); - let queue_bytes = AtomicU64::new(0); - let worker_healthy = AtomicBool::new(true); - - assert_eq!( - enqueue_exact_state_record( - &sender, - &inflight, - &queued, - &dropped, - &pending_count, - &queue_bytes, - CAP, - &worker_healthy, - pending( - "dropped", - credit(&total, &best_effort, CaptureAdmission::Continuation) - ), - ), - ExactStateRecordAdmission::DroppedFull - ); - assert!(!inflight.lock().unwrap().contains("dropped")); - assert_eq!(queued.load(Ordering::Relaxed), 0); - assert_eq!(dropped.load(Ordering::Relaxed), 1); - assert_eq!(pending_count.load(Ordering::Relaxed), 0); - assert_eq!( - total.load(Ordering::Acquire), - 1, - "the Full rejection must release the dropped record's credit; the buffered one stays" - ); - assert_eq!( - best_effort.load(Ordering::Acquire), - 1, - "the buffered BestEffort credit is still outstanding" - ); - - // Receiver drop: discarding the channel drops the buffered record and - // releases its credit too. - drop(sender); - drop(receiver); - assert_eq!( - total.load(Ordering::Acquire), - 0, - "receiver drop released the buffered credit" - ); - assert_eq!(best_effort.load(Ordering::Acquire), 0); - } - - #[test] - fn disconnected_worker_releases_inflight_page() { - let (total, best_effort) = budget(); - let (sender, receiver) = sync_channel(1); - drop(receiver); - let inflight = Mutex::new(BTreeSet::from(["orphaned".to_string()])); - let queued = AtomicU64::new(0); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(0); - let queue_bytes = AtomicU64::new(0); - let worker_healthy = AtomicBool::new(true); - - assert_eq!( - enqueue_exact_state_record( - &sender, - &inflight, - &queued, - &dropped, - &pending_count, - &queue_bytes, - CAP, - &worker_healthy, - pending( - "orphaned", - credit(&total, &best_effort, CaptureAdmission::Continuation) - ), - ), - ExactStateRecordAdmission::WorkerStopped - ); - assert!(!inflight.lock().unwrap().contains("orphaned")); - assert_eq!(dropped.load(Ordering::Relaxed), 1); - assert_eq!(pending_count.load(Ordering::Relaxed), 0); - assert_eq!( - total.load(Ordering::Acquire), - 0, - "the disconnected channel must release the orphaned credit" - ); - assert_eq!(best_effort.load(Ordering::Acquire), 0); - } - - #[test] - fn worker_keeps_page_inflight_until_record_finishes() { - let (total, best_effort) = budget(); - let (sender, receiver) = sync_channel(1); - let inflight = Arc::new(Mutex::new(BTreeSet::from(["page".to_string()]))); - let worker_inflight = inflight.clone(); - let queued = AtomicU64::new(0); - let dropped = AtomicU64::new(0); - let pending_count = Arc::new(AtomicUsize::new(0)); - let worker_pending_count = pending_count.clone(); - let queue_bytes = AtomicU64::new(0); - let worker_healthy = AtomicBool::new(true); - - assert_eq!( - enqueue_exact_state_record( - &sender, - &inflight, - &queued, - &dropped, - &pending_count, - &queue_bytes, - CAP, - &worker_healthy, - pending( - "page", - credit(&total, &best_effort, CaptureAdmission::Continuation) - ), - ), - ExactStateRecordAdmission::Queued - ); - assert!(inflight.lock().unwrap().contains("page")); - assert_eq!( - total.load(Ordering::Acquire), - 1, - "the credit is outstanding while the record sits in the channel" - ); - - let worker = std::thread::spawn(move || { - let pending = receiver.recv().unwrap(); - assert!(worker_inflight.lock().unwrap().contains(&pending.page_id)); - worker_inflight.lock().unwrap().remove(&pending.page_id); - worker_pending_count.fetch_sub(1, Ordering::Relaxed); - // `pending` (and its credit) drops when this closure returns. - }); - worker.join().unwrap(); - - assert!(!inflight.lock().unwrap().contains("page")); - assert_eq!(queued.load(Ordering::Relaxed), 1); - assert_eq!(dropped.load(Ordering::Relaxed), 0); - assert_eq!(pending_count.load(Ordering::Relaxed), 0); - assert_eq!( - total.load(Ordering::Acquire), - 0, - "the credit released when the record dropped after processing" - ); - } - - #[test] - fn worker_success_notifies_completed_not_mere_admission() { - let inflight = Mutex::new(BTreeSet::from(["written".to_string()])); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(1); - let queue_bytes = AtomicU64::new(1); - let worker_healthy = AtomicBool::new(true); - let worker_panics = AtomicU64::new(0); - let events: Arc>> = Arc::default(); - let observer: Arc = Arc::new(RecordingObserver(events.clone())); - let (total, best_effort) = budget(); - - run_exact_state_record_job( - ExactStateWorkerHandles { - inflight_records: &inflight, - dropped: &dropped, - pending_count: &pending_count, - queue_bytes: &queue_bytes, - worker_healthy: &worker_healthy, - worker_panics: &worker_panics, - }, - Some(&observer), - pending( - "written", - credit(&total, &best_effort, CaptureAdmission::Continuation), - ), - |_| Ok(()), - ); - - assert_eq!( - *events.lock().unwrap(), - vec![KvLifecycleEvent::ExactStateRecordCompleted] - ); - assert_eq!(dropped.load(Ordering::Relaxed), 0); - assert_eq!( - total.load(Ordering::Acquire), - 0, - "successful completion released the real credit" - ); - } - - #[test] - fn worker_write_error_notifies_failed_not_completed() { - let inflight = Mutex::new(BTreeSet::from(["broken".to_string()])); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(1); - let queue_bytes = AtomicU64::new(1); - let worker_healthy = AtomicBool::new(true); - let worker_panics = AtomicU64::new(0); - let events: Arc>> = Arc::default(); - let observer: Arc = Arc::new(RecordingObserver(events.clone())); - let (total, best_effort) = budget(); - - run_exact_state_record_job( - ExactStateWorkerHandles { - inflight_records: &inflight, - dropped: &dropped, - pending_count: &pending_count, - queue_bytes: &queue_bytes, - worker_healthy: &worker_healthy, - worker_panics: &worker_panics, - }, - Some(&observer), - pending( - "broken", - credit(&total, &best_effort, CaptureAdmission::Continuation), - ), - |_| anyhow::bail!("simulated write failure"), - ); - - assert_eq!( - *events.lock().unwrap(), - vec![KvLifecycleEvent::ExactStateRecordFailed] - ); - assert_eq!(dropped.load(Ordering::Relaxed), 1); - assert_eq!( - total.load(Ordering::Acquire), - 0, - "the worker error path released the real credit" - ); - assert_eq!(best_effort.load(Ordering::Acquire), 0); - } - - #[test] - fn worker_panic_fails_closed_and_releases_all_record_bookkeeping() { - let (sender, _receiver) = sync_channel(1); - let inflight = Mutex::new(BTreeSet::from(["panicked".to_string()])); - let queued = AtomicU64::new(0); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(1); - let queue_bytes = AtomicU64::new(1); - let worker_healthy = AtomicBool::new(true); - let worker_panics = AtomicU64::new(0); - let (total, best_effort) = budget(); - - run_exact_state_record_job( - ExactStateWorkerHandles { - inflight_records: &inflight, - dropped: &dropped, - pending_count: &pending_count, - queue_bytes: &queue_bytes, - worker_healthy: &worker_healthy, - worker_panics: &worker_panics, - }, - None, - pending( - "panicked", - credit(&total, &best_effort, CaptureAdmission::Continuation), - ), - |_| panic!("injected exact-record worker failure"), - ); - - assert!(!worker_healthy.load(Ordering::Acquire)); - assert_eq!(worker_panics.load(Ordering::Relaxed), 1); - assert_eq!(dropped.load(Ordering::Relaxed), 1); - assert_eq!(pending_count.load(Ordering::Acquire), 0); - assert!(inflight.lock().unwrap().is_empty()); - assert_eq!( - total.load(Ordering::Acquire), - 0, - "the unwind dropped the record and released its real credit" - ); - assert_eq!(best_effort.load(Ordering::Acquire), 0); - - inflight.lock().unwrap().insert("later".to_string()); - assert_eq!( - enqueue_exact_state_record( - &sender, - &inflight, - &queued, - &dropped, - &pending_count, - &queue_bytes, - CAP, - &worker_healthy, - pending( - "later", - credit(&total, &best_effort, CaptureAdmission::Continuation) - ), - ), - ExactStateRecordAdmission::WorkerStopped - ); - assert!(inflight.lock().unwrap().is_empty()); - assert_eq!(dropped.load(Ordering::Relaxed), 2); - assert_eq!(pending_count.load(Ordering::Acquire), 0); - assert_eq!( - total.load(Ordering::Acquire), - 0, - "the WorkerStopped follow-up also released its real credit" - ); - } -} +mod exact_state_record_queue_tests; #[cfg(test)] mod telemetry_error_class_tests { diff --git a/skippy/crates/skippy-serving/src/kv_integration/records.rs b/skippy/crates/skippy-serving/src/kv_integration/records.rs index 4354a05dd3..fe9114ae3b 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/records.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/records.rs @@ -11,6 +11,17 @@ pub struct PrefillKvIdentity { pub token_ids: Vec, } +impl PrefillKvIdentity { + /// Eviction order for entries recorded under this identity: the tier + /// priority of the request class its cache namespace was built for. + pub fn retention_priority(&self) -> u64 { + let namespace = Some(self.identity.chat_template_id.as_str()).filter(|ns| !ns.is_empty()); + skippy_inference_api::InferenceRequestClass::from_cache_namespace(namespace) + .tier() + .priority() + } +} + #[derive(Debug, Clone)] pub struct LookupBatchOutcome { pub pages: Vec, diff --git a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs index 259b8079a4..c159a05ba1 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs @@ -262,6 +262,7 @@ impl KvStageIntegration { units: resident_candidate_units(candidate), recompute_cost: candidate.value.recompute_cost, last_used: candidate.last_used, + retention_priority: candidate.value.retention_priority, }) .collect::>(); rank_eviction_candidates(&mut ranked); @@ -486,9 +487,11 @@ impl KvStageIntegration { let mut evicted_entries = 0usize; let mut evicted_tokens = 0u64; while evicted_tokens < target_tokens { - let Some(removed) = evict_one_resident(&mut radix, &mut sequences, |victim| { - self.release_native_prefix(runtime, session_id, victim) - })? + // Live requests need the KV now, whichever tier stored it. + let Some(removed) = + evict_one_resident(&mut radix, &mut sequences, u64::MAX, |victim| { + self.release_native_prefix(runtime, session_id, victim) + })? else { break; }; @@ -547,12 +550,16 @@ impl KvStageIntegration { } } +/// Evict the best resident victim whose retention is at most +/// `max_victim_retention`, so a record never displaces a higher tier's entry. fn evict_one_resident( radix: &mut skippy_cache::UnifiedRadixCache, sequences: &mut ResidentSequencePool, + max_victim_retention: u64, mut drop_native: impl FnMut(&skippy_cache::RadixEvictionCandidate) -> Result<()>, ) -> Result>> { - let candidates = radix.resident_eviction_candidates(); + let mut candidates = radix.resident_eviction_candidates(); + candidates.retain(|candidate| candidate.value.retention_priority <= max_victim_retention); if candidates.is_empty() { return Ok(None); } @@ -572,6 +579,7 @@ fn evict_one_resident( units: resident_candidate_units(candidate), recompute_cost: candidate.value.recompute_cost, last_used: candidate.last_used, + retention_priority: candidate.value.retention_priority, }) .collect(), }, @@ -734,6 +742,7 @@ mod proactive_eviction_tests { seq_id, token_count: 8, recompute_cost: 8, + retention_priority: 0, }, ) .unwrap(); @@ -810,6 +819,7 @@ mod proactive_eviction_tests { seq_id, token_count: tokens, recompute_cost: tokens, + retention_priority: 0, }, ) .unwrap(); @@ -855,11 +865,12 @@ mod proactive_eviction_tests { seq_id, token_count: 3, recompute_cost: 3, + retention_priority: 0, }, ) .unwrap(); - let error = evict_one_resident(&mut radix, &mut sequences, |_| { + let error = evict_one_resident(&mut radix, &mut sequences, u64::MAX, |_| { anyhow::bail!("native drop failed") }) .unwrap_err(); @@ -884,13 +895,14 @@ mod proactive_eviction_tests { seq_id, token_count: 3, recompute_cost: 3, + retention_priority: 0, }, ) .unwrap(); radix.acquire_resident("stage", &[1, 2, 3]).unwrap(); let mut dropped = false; - let removed = evict_one_resident(&mut radix, &mut sequences, |_| { + let removed = evict_one_resident(&mut radix, &mut sequences, u64::MAX, |_| { dropped = true; Ok(()) }) @@ -916,12 +928,13 @@ mod proactive_eviction_tests { seq_id, token_count: 0, recompute_cost: 0, + retention_priority: 0, }, ) .unwrap(); let mut dropped = None; - let removed = evict_one_resident(&mut radix, &mut sequences, |victim| { + let removed = evict_one_resident(&mut radix, &mut sequences, u64::MAX, |victim| { let seq_id = victim.value.seq_id; dropped = Some(seq_id); Ok(()) @@ -950,6 +963,7 @@ mod proactive_eviction_tests { seq_id: 1, token_count: 3, recompute_cost: 3, + retention_priority: 0, }, ) .unwrap(); @@ -990,6 +1004,7 @@ mod proactive_eviction_tests { seq_id: expensive_seq_id, token_count: 3, recompute_cost: 300, + retention_priority: 0, }, ) .unwrap(); @@ -1004,12 +1019,13 @@ mod proactive_eviction_tests { seq_id: cheap_seq_id, token_count: 3, recompute_cost: 3, + retention_priority: 0, }, ) .unwrap(); let mut dropped = None; - let removed = evict_one_resident(&mut radix, &mut sequences, |victim| { + let removed = evict_one_resident(&mut radix, &mut sequences, u64::MAX, |victim| { let seq_id = victim.value.seq_id; dropped = Some(seq_id); Ok(()) @@ -1040,6 +1056,7 @@ mod proactive_eviction_tests { seq_id, token_count: 0, recompute_cost: 0, + retention_priority: 0, }, |seq_id| { dropped = Some(seq_id); @@ -1074,6 +1091,7 @@ mod proactive_eviction_tests { seq_id, token_count: 0, recompute_cost: 0, + retention_priority: 0, }, |_| anyhow::bail!("native drop failed"), ) @@ -1116,6 +1134,7 @@ mod proactive_eviction_tests { seq_id: existing_seq_id, token_count: 3, recompute_cost: 3, + retention_priority: 0, }, ) .unwrap(); @@ -1133,6 +1152,7 @@ mod proactive_eviction_tests { seq_id: duplicate_seq_id, token_count: 3, recompute_cost: 3, + retention_priority: 0, }, |seq_id| { dropped = Some(seq_id); diff --git a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs index 93a95db62e..c5a961ed12 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs @@ -56,11 +56,13 @@ impl KvStageIntegration { }, )); } + let retention = identity.retention_priority(); if !make_record_room( self.resident_config, &mut radix, &mut sequences, checkpoint_bytes, + retention, &mut evicted, |victim| self.release_native_prefix(runtime, session_id, victim), )? { @@ -87,10 +89,21 @@ impl KvStageIntegration { let seq_id = match sequences.allocate() { Ok(sequence) => sequence, Err(error) => { - let removed = evict_one_resident(&mut radix, &mut sequences, |victim| { - self.release_native_prefix(runtime, session_id, victim) - })?; + let removed = + evict_one_resident(&mut radix, &mut sequences, retention, |victim| { + self.release_native_prefix(runtime, session_id, victim) + })?; let Some(removed) = removed else { + // The evictable sequences hold higher tiers' prefixes: keep them. + if radix + .resident_eviction_candidates() + .iter() + .any(|candidate| candidate.value.retention_priority > retention) + { + return Ok(ResidentRecordOutcome::Skipped(ResidentRecordSkip::NoRoom { + bytes: checkpoint_bytes, + })); + } return Err(error); }; evicted.0 += 1; @@ -112,6 +125,7 @@ impl KvStageIntegration { seq_id, token_count: token_count as u64, recompute_cost: (token_count as u64).saturating_mul(u64::from(layers)), + retention_priority: identity.retention_priority(), }; let candidate = skippy_cache::RadixEvictionCandidate { namespace: identity.namespace.clone(), @@ -138,6 +152,7 @@ impl KvStageIntegration { &mut radix, &mut sequences, bytes, + retention, &mut evicted, |victim| self.release_native_prefix(runtime, session_id, victim), ) @@ -257,11 +272,14 @@ fn make_record_room( radix: &mut skippy_cache::UnifiedRadixCache, sequences: &mut ResidentSequencePool, bytes: u64, + incoming_retention: u64, evicted: &mut (usize, u64), mut drop_native: impl FnMut(&skippy_cache::RadixEvictionCandidate) -> Result<()>, ) -> Result { while resident_index_over_capacity(config, radix.stats(), bytes) { - let Some(removed) = evict_one_resident(radix, sequences, &mut drop_native)? else { + let Some(removed) = + evict_one_resident(radix, sequences, incoming_retention, &mut drop_native)? + else { return Ok(false); }; evicted.0 = evicted.0.saturating_add(1); @@ -348,6 +366,7 @@ mod resident_record_cap_tests { seq_id, token_count: 100, recompute_cost: 100, + retention_priority: 0, }, ) .unwrap(); @@ -363,6 +382,97 @@ mod resident_record_cap_tests { mod checkpoint_budget_tests { use super::*; + /// A cache holding one resident entry per `(tokens, retention)` pair. + fn tiered_cache( + entries: &[(&[i32], u64)], + ) -> ( + skippy_cache::UnifiedRadixCache, + ResidentSequencePool, + ) { + let mut radix = skippy_cache::UnifiedRadixCache::new(); + let mut sequences = ResidentSequencePool::new(4); + for (tokens, retention) in entries { + let seq = sequences.allocate().unwrap(); + radix + .insert_resident( + "model", + tokens, + 10, + RadixResidentEntry { + page_id: seq.to_string(), + seq_id: seq, + token_count: tokens.len() as u64, + recompute_cost: 1, + retention_priority: *retention, + }, + ) + .unwrap(); + } + (radix, sequences) + } + + #[test] + fn a_record_evicts_only_entries_at_or_below_its_tier() { + let config = skippy_cache::ResidentCacheConfig { + max_entries: 2, + max_bytes: 0, + min_tokens: 1, + reserved_seq_count: 4, + max_resident_tokens: 0, + }; + let (mut radix, mut sequences) = tiered_cache(&[(&[1], 2), (&[2], 2)]); + assert!( + !make_record_room( + config, + &mut radix, + &mut sequences, + 0, + 0, + &mut (0, 0), + |_| { panic!("a lower tier's record must not evict a higher tier's prefix") } + ) + .unwrap() + ); + assert_eq!(radix.stats().resident_entries, 2); + + let mut dropped = Vec::new(); + assert!( + make_record_room( + config, + &mut radix, + &mut sequences, + 0, + 2, + &mut (0, 0), + |victim| { + dropped.push(victim.value.retention_priority); + Ok(()) + } + ) + .unwrap() + ); + assert_eq!(dropped, [2]); + + let (mut radix, mut sequences) = tiered_cache(&[(&[1], 2), (&[2], 0)]); + let mut dropped = Vec::new(); + assert!( + make_record_room( + config, + &mut radix, + &mut sequences, + 0, + 0, + &mut (0, 0), + |victim| { + dropped.push(victim.tokens.clone()); + Ok(()) + } + ) + .unwrap() + ); + assert_eq!(dropped, [vec![2]]); + } + #[test] fn native_host_bytes_evict_unpinned_owner_without_summing_shared_kv() { let mut radix = skippy_cache::UnifiedRadixCache::new(); @@ -380,6 +490,7 @@ mod checkpoint_budget_tests { seq_id: seq, token_count: tokens.len() as u64, recompute_cost: 1, + retention_priority: 0, }, ) .unwrap(); @@ -400,6 +511,7 @@ mod checkpoint_budget_tests { &mut radix, &mut sequences, 30, + 0, &mut evicted, |seq| { dropped.push(seq.value.seq_id); @@ -429,6 +541,7 @@ mod checkpoint_budget_tests { seq_id: seq, token_count: 2, recompute_cost: 1, + retention_priority: 0, }, ) .unwrap(); @@ -448,6 +561,7 @@ mod checkpoint_budget_tests { &mut radix, &mut sequences, 30, + 0, &mut (0, 0), |_| panic!("pinned checkpoint must not be dropped") ) diff --git a/skippy/crates/skippy-serving/src/kv_integration/tier_metrics.rs b/skippy/crates/skippy-serving/src/kv_integration/tier_metrics.rs index 3251ab025f..89a168913d 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/tier_metrics.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/tier_metrics.rs @@ -264,6 +264,7 @@ mod tests { seq_id: 0, token_count: 3, recompute_cost: 1, + retention_priority: 0, }, ) .expect("resident checkpoint"); diff --git a/skippy/crates/skippy-serving/src/lib.rs b/skippy/crates/skippy-serving/src/lib.rs index 77c424c440..cf9a6697a0 100644 --- a/skippy/crates/skippy-serving/src/lib.rs +++ b/skippy/crates/skippy-serving/src/lib.rs @@ -40,6 +40,7 @@ mod legacy_scheduler_absence_tests { pub mod serving_hooks; pub mod settings; pub mod split_dflash; +mod stage_request_class; pub mod telemetry; pub mod thinking_probe; pub mod tokenizer; diff --git a/skippy/crates/skippy-serving/src/stage_request_class.rs b/skippy/crates/skippy-serving/src/stage_request_class.rs new file mode 100644 index 0000000000..c7eeac764d --- /dev/null +++ b/skippy/crates/skippy-serving/src/stage_request_class.rs @@ -0,0 +1,161 @@ +//! A request's tier and cache partition on the binary stage wire. +//! +//! Stage 0 stamps the class of each request on the cache-bearing messages it +//! sends downstream. A downstream stage lowers that claim to the highest tier +//! its host assigned to the stage and evicts by the result. It partitions its +//! caches by both, so the claims it merges into one tier still never share a +//! prefix: every stage keeps the same isolation as stage 0. + +use skippy_inference_api::{InferenceRequestClass, InferenceRequestTier}; +use skippy_protocol::StageConfig; +use skippy_protocol::binary::StageStateHeader; + +/// Stamp `class` on an outgoing stage message header. +pub(crate) fn stamp_request_class(state: &mut StageStateHeader, class: InferenceRequestClass) { + state.set_request_tier_demotion(tier_demotion(class.tier())); + state.set_private_cache_partition(class.is_private()); +} + +/// The class a stage serves a message at: the stamped claim, lowered to the +/// stage's configured maximum tier. +pub(crate) fn stage_request_class( + config: &StageConfig, + state: StageStateHeader, +) -> InferenceRequestClass { + claimed_request_class(state).limited_to(max_request_tier(config)) +} + +/// The cache namespace a stage records and looks up a message's prefixes in: +/// the served class's partition, which sets eviction order, and within it the +/// claimed one when the stage's cap lowered it. +pub(crate) fn stage_cache_namespace( + config: &StageConfig, + state: StageStateHeader, +) -> Option { + let served = stage_request_class(config, state); + let claimed = claimed_request_class(state); + if served == claimed { + return served.cache_namespace(None); + } + let claimed_partition = claimed + .cache_partition() + .unwrap_or_else(|| InferenceRequestTier::Local.as_str().to_owned()); + served.cache_namespace(Some(format!("claimed-{claimed_partition}"))) +} + +fn claimed_request_class(state: StageStateHeader) -> InferenceRequestClass { + InferenceRequestClass::new( + tier_from_demotion(state.request_tier_demotion()), + state.private_cache_partition(), + ) +} + +/// The highest tier this stage serves. An unrecognized name is `mesh`, so a +/// malformed cap fails low. +fn max_request_tier(config: &StageConfig) -> InferenceRequestTier { + config + .max_request_tier + .as_deref() + .map_or(InferenceRequestTier::Local, |tier| { + InferenceRequestTier::parse(tier).unwrap_or(InferenceRequestTier::Mesh) + }) +} + +fn tier_demotion(tier: InferenceRequestTier) -> u8 { + InferenceRequestTier::Local.code() - tier.code() +} + +fn tier_from_demotion(demotion: u8) -> InferenceRequestTier { + InferenceRequestTier::Local + .code() + .checked_sub(demotion) + .and_then(InferenceRequestTier::from_code) + .unwrap_or(InferenceRequestTier::Mesh) +} + +#[cfg(test)] +mod tests { + use super::*; + use skippy_protocol::binary::WireMessageKind; + + fn header(class: InferenceRequestClass) -> StageStateHeader { + let mut state = StageStateHeader::new(WireMessageKind::PrefillEmbd); + stamp_request_class(&mut state, class); + state + } + + #[test] + fn unstamped_messages_are_local_and_unpartitioned() { + let state = StageStateHeader::new(WireMessageKind::PrefillEmbd); + let config = StageConfig::default(); + assert_eq!( + stage_request_class(&config, state), + InferenceRequestClass::default() + ); + assert_eq!(stage_cache_namespace(&config, state), None); + } + + #[test] + fn every_class_round_trips_through_the_header() { + let config = StageConfig::default(); + for tier in InferenceRequestTier::ALL { + for private in [false, true] { + let class = InferenceRequestClass::new(tier, private); + assert_eq!(stage_request_class(&config, header(class)), class); + } + } + } + + #[test] + fn the_stage_cap_lowers_but_never_raises_a_claim() { + let config = StageConfig { + max_request_tier: Some("trusted".into()), + ..StageConfig::default() + }; + let local = InferenceRequestClass::new(InferenceRequestTier::Local, true); + let mesh = InferenceRequestClass::new(InferenceRequestTier::Mesh, false); + assert_eq!( + stage_request_class(&config, header(local)), + InferenceRequestClass::new(InferenceRequestTier::Trusted, true) + ); + assert_eq!(stage_request_class(&config, header(mesh)), mesh); + let malformed = StageConfig { + max_request_tier: Some("owner".into()), + ..StageConfig::default() + }; + assert_eq!( + stage_request_class(&malformed, header(local)).tier(), + InferenceRequestTier::Mesh + ); + } + + #[test] + fn claims_a_cap_merges_keep_separate_partitions_and_evict_at_the_cap() { + let config = StageConfig { + max_request_tier: Some("mesh".into()), + ..StageConfig::default() + }; + let namespaces = [ + InferenceRequestClass::new(InferenceRequestTier::Local, false), + InferenceRequestClass::new(InferenceRequestTier::Trusted, false), + InferenceRequestClass::new(InferenceRequestTier::Mesh, false), + InferenceRequestClass::new(InferenceRequestTier::Local, true), + InferenceRequestClass::new(InferenceRequestTier::Mesh, true), + ] + .map(|class| stage_cache_namespace(&config, header(class))); + let distinct = namespaces + .iter() + .collect::>() + .len(); + assert_eq!(distinct, namespaces.len(), "{namespaces:?}"); + for namespace in &namespaces { + assert_eq!( + InferenceRequestClass::from_cache_namespace(namespace.as_deref()).tier(), + InferenceRequestTier::Mesh, + "{namespace:?}" + ); + } + // A claim the cap leaves alone keeps the plain partition. + assert_eq!(namespaces[2].as_deref(), Some("tier:mesh:")); + } +} diff --git a/skippy/docs/CAUSAL_DECISIONS.md b/skippy/docs/CAUSAL_DECISIONS.md index fb5033e56d..3feae18cf4 100644 --- a/skippy/docs/CAUSAL_DECISIONS.md +++ b/skippy/docs/CAUSAL_DECISIONS.md @@ -111,8 +111,8 @@ fallback. In split execution, the terminal worker computes scores and returns only a bounded selected-token vector. Full vocabulary logits remain inside the native -runtime. All workers must support stage protocol generation 16, wire header -version 17 and Skippy ABI 0.1.74. Upgrade the whole chain together; older stage +runtime. All workers must support stage protocol generation 17, wire header +version 18 and Skippy ABI 0.1.74. Upgrade the whole chain together; older stage peers fail negotiation. Additive `system_one` discovery does not grant this ability to an older runtime. No persisted-data migration is required. diff --git a/skippy/docs/DATA_FLOW.md b/skippy/docs/DATA_FLOW.md index 738b1c3b5d..80d4c34f5e 100644 --- a/skippy/docs/DATA_FLOW.md +++ b/skippy/docs/DATA_FLOW.md @@ -43,9 +43,9 @@ chain alone makes the hot path six hops, or about 60 ms before compute. ## Current Stage Admission and Readout Transport Generation 7 introduced direct prediction return, and generation 9 added -canonical stage-admission descriptors. Generation 16 is the current +canonical stage-admission descriptors. Generation 17 is the current compatibility-breaking cutover: a peer is stage compatible only when it -advertises both `skippy-stage/2` and the complete `stage-generation-16` bundle. +advertises both `skippy-stage/2` and the complete `stage-generation-17` bundle. Every load carries a canonical admission descriptor. The ready response echoes that descriptor exactly before topology publication. Prediction-bearing messages return directly from the final/readout stage to the