Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions mesh/crates/mesh-llm-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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",
Expand Down
8 changes: 8 additions & 0 deletions mesh/crates/mesh-llm-config/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ mod built_in_schema;
mod multimodal;
mod private;
mod profile;
mod request_tiers;
mod runtime;
mod schema_types;
mod updates;
Expand All @@ -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,
Expand Down Expand Up @@ -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)]
Expand Down Expand Up @@ -1231,6 +1236,8 @@ struct RawMeshConfig {
#[serde(default)]
private: PrivateConfig,
#[serde(default)]
request_tiers: RequestTiersConfig,
#[serde(default)]
telemetry: TelemetryConfig,
#[serde(default)]
analytics: AnalyticsConfig,
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,21 @@ fn process_setting_presentation(rendered: &str) -> Option<SettingPresentation> {
)
.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.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down
126 changes: 126 additions & 0 deletions mesh/crates/mesh-llm-config/src/model/request_tiers.rs
Original file line number Diff line number Diff line change
@@ -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<String, RequestTierName>,
/// 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}");
}
}
33 changes: 33 additions & 0 deletions mesh/crates/mesh-llm-config/src/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ConfigDiagnostic> {
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<ConfigDiagnostic> {
let mut diagnostics = Vec::new();

Expand Down Expand Up @@ -98,6 +130,7 @@ pub fn validate_config_diagnostics(config: &MeshConfig) -> Vec<ConfigDiagnostic>
),
));
}
diagnostics.extend(validate_request_tiers_config(&config.request_tiers));
if let Err(diagnostic) = validate_telemetry_config(&config.telemetry) {
diagnostics.push(diagnostic);
}
Expand Down
14 changes: 14 additions & 0 deletions mesh/crates/mesh-llm-config/src/wiring_status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
22 changes: 16 additions & 6 deletions mesh/crates/mesh-llm-host-runtime/src/inference/consult.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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?;
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ pub(crate) fn remote_stage_load_request(
load_mode: LoadMode::LayerPackage,
upstream: None,
downstream,
max_request_tier: None,
}
}

Expand Down Expand Up @@ -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(),
Expand Down
Loading
Loading