Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
1 change: 1 addition & 0 deletions mesh/crates/mesh-llm-host-runtime/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1033,6 +1033,7 @@ impl MeshApi {
};
payload.logging =
crate::logging_runtime_state().map(|state| LoggingStatusPayload::from(state.status()));
payload.plugin_status = runtime_data_collector.plugin_status_payloads();
payload
}

Expand Down
108 changes: 108 additions & 0 deletions mesh/crates/mesh-llm-host-runtime/src/api/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub(crate) use mesh_llm_control_api::status::metrics::{
pub(crate) use mesh_llm_control_api::status::runtime::*;
use serde::Serialize;
use skippy_serving::InferenceGuardrailsStatus;
use std::collections::BTreeMap;

pub(crate) fn current_runtime_events_summary() -> Option<RuntimeEventsStatusSummary> {
let engine = crate::runtime_events::runtime_event_engine()?;
Expand Down Expand Up @@ -391,6 +392,89 @@ pub(crate) struct StatusPayload {
/// state has been initialized so older consumers retain their prior shape.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) logging: Option<LoggingStatusPayload>,
/// Snapshots plugins published over their local connections, each as a
/// top-level field named by the host's name for the plugin; see
/// [`PluginStatusPayload`]. Local-only, and absent while no plugin
/// contributes, so the shape is unchanged. A plugin named like one of
/// [`CORE_STATUS_FIELDS`] cannot contribute.
#[serde(flatten)]
pub(crate) plugin_status: BTreeMap<String, PluginStatusPayload>,
}

/// The fields of [`StatusPayload`] besides the plugins' contributions. A
/// plugin by one of these names is refused, so it never shadows a core field.
pub(crate) const CORE_STATUS_FIELDS: &[&str] = &[
"version",
"latest_version",
"node_id",
"owner",
"release_attestation",
"token",
"node_state",
"node_status",
"is_host",
"is_client",
"llama_ready",
"runtime",
"model_name",
"models",
"available_models",
"requested_models",
"wanted_model_refs",
"serving_models",
"hosted_models",
"draft_name",
"api_port",
"my_vram_gb",
"model_size_gb",
"peers",
"wakeable_nodes",
"local_instances",
"launch_pi",
"launch_goose",
"inflight_requests",
"mesh_id",
"mesh_name",
"mesh_discovery_mode",
"discovery_scope",
"discovery_source",
"nostr_discovery",
"publication_state",
"my_hostname",
"my_is_soc",
"my_memory",
"gpus",
"routing_affinity",
"routing_metrics",
"first_joined_mesh_ts",
"mesh_requirements",
"recent_mesh_rejections",
"plugin_frame_telemetry",
"logging",
];

/// One plugin's contribution to `/api/status`. The host owns everything but
/// `data`, which is the plugin's own, in version `schema_version` of its own
/// schema. The state and timestamps say when the host last heard from the
/// plugin, not how old the plugin's readings are.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub(crate) struct PluginStatusPayload {
pub(crate) schema_version: u32,
pub(crate) state: PluginStatusState,
pub(crate) received_at_unix_ms: u64,
pub(crate) fresh_until_unix_ms: u64,
pub(crate) data: serde_json::Value,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum PluginStatusState {
/// Published within the freshness the plugin asked for.
Ready,
/// Its freshness ran out before the plugin published again.
Stale,
/// The plugin connection that published it is gone.
Unavailable,
}

/// Local-only plugin-mesh frame telemetry.
Expand Down Expand Up @@ -891,6 +975,26 @@ mod tests {
use super::*;
use crate::ReleaseAttestationSummary;

#[test]
fn core_status_fields_name_every_field_but_the_plugins() {
// Read from the struct itself, so a new field cannot be left out and
// let a plugin of that name shadow it.
let fields = include_str!("status.rs")
.lines()
.skip_while(|line| !line.starts_with("pub(crate) struct StatusPayload {"))
.skip(1)
.take_while(|line| *line != "}")
.filter_map(|line| line.trim().strip_prefix("pub(crate) "))
.filter_map(|field| field.split_once(':').map(|(name, _)| name))
.filter(|name| *name != "plugin_status")
.collect::<std::collections::BTreeSet<_>>();
assert_eq!(
fields,
CORE_STATUS_FIELDS.iter().copied().collect(),
"CORE_STATUS_FIELDS must list StatusPayload's fields"
);
}

fn test_owner_payload() -> OwnershipPayload {
OwnershipPayload {
owner_id: None,
Expand Down Expand Up @@ -1059,6 +1163,7 @@ mod tests {
recent_mesh_rejections: vec![],
plugin_frame_telemetry: PluginFrameTelemetryPayload::default(),
logging: None,
plugin_status: Default::default(),
};

let json = serde_json::to_string(&status).expect("serialization failed");
Expand Down Expand Up @@ -1134,6 +1239,7 @@ mod tests {
recent_mesh_rejections: vec![],
plugin_frame_telemetry: PluginFrameTelemetryPayload::default(),
logging: None,
plugin_status: Default::default(),
};

let json = serde_json::to_string(&status).expect("serialization failed");
Expand Down Expand Up @@ -1209,6 +1315,7 @@ mod tests {
recent_mesh_rejections: vec![],
plugin_frame_telemetry: PluginFrameTelemetryPayload::default(),
logging: None,
plugin_status: Default::default(),
};

let json = serde_json::to_value(&status).expect("serialization failed");
Expand Down Expand Up @@ -1279,6 +1386,7 @@ mod tests {
recent_mesh_rejections: vec![],
plugin_frame_telemetry: PluginFrameTelemetryPayload::default(),
logging: None,
plugin_status: Default::default(),
};

let json = serde_json::to_value(&status).expect("serialization failed");
Expand Down
120 changes: 120 additions & 0 deletions mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,126 @@ async fn runtime_data_sse_bridge_delivers_initial_and_incremental_updates() {
handle.abort();
}

async fn publish_test_plugin_status(
node: &mesh::Node,
plugin_id: &str,
data_json: &str,
) -> Result<plugin::proto::PublishPluginStatusResponse, plugin::proto::ErrorResponse> {
let (response_tx, response_rx) = oneshot::channel();
node.forward_plugin_event(plugin::PluginMeshEvent::PluginStatus {
plugin_id: plugin_id.into(),
generation: 1,
schema_version: 1,
request: plugin::proto::PublishPluginStatusRequest {
data_json: data_json.into(),
fresh_for_ms: 0,
},
response_tx,
})
.await
.unwrap();
response_rx.await.unwrap()
}

#[tokio::test]
async fn status_shows_plugin_contributions_and_keeps_its_shape_without_them() {
let state = build_test_mesh_api().await;
let node = state.inner.lock().await.node.clone();
let (addr, handle) = spawn_management_test_server(state.clone()).await;

let status_body = request_management_json(state.clone(), "/api/status").await;
assert!(
status_body.get("powermetrics").is_none(),
"no contribution, no field"
);

let mut events = TcpStream::connect(addr).await.unwrap();
events
.write_all(b"GET /api/events HTTP/1.1\r\nHost: localhost\r\n\r\n")
.await
.unwrap();
read_until_contains(&mut events, b"data: {", Duration::from_secs(2)).await;

publish_test_plugin_status(&node, "powermetrics", r#"{"idle_watts":8.2}"#)
.await
.expect("the snapshot is accepted");
publish_test_plugin_status(&node, "other", r#"{"ok":true}"#)
.await
.expect("the snapshot is accepted");
let pushed = read_until_contains(&mut events, b"\"idle_watts\":8.2", Duration::from_secs(2)).await;
assert!(String::from_utf8_lossy(&pushed).contains("\"powermetrics\":{"));

let status_body = request_management_json(state.clone(), "/api/status").await;
let contribution = &status_body["powermetrics"];
assert_eq!(contribution["schema_version"], json!(1));
assert_eq!(contribution["state"], json!("ready"));
assert_eq!(contribution["data"], json!({"idle_watts": 8.2}));
assert!(contribution["fresh_until_unix_ms"].as_u64() > contribution["received_at_unix_ms"].as_u64());
assert_eq!(status_body["other"]["data"], json!({"ok": true}));

node.forward_plugin_event(plugin::PluginMeshEvent::PluginDisconnected {
plugin_id: "powermetrics".into(),
generation: 1,
})
.await
.unwrap();
read_until_contains(&mut events, b"\"state\":\"unavailable\"", Duration::from_secs(2)).await;
let status_body = request_management_json(state.clone(), "/api/status").await;
assert_eq!(
status_body["powermetrics"]["state"],
json!("unavailable")
);
assert_eq!(
status_body["powermetrics"]["data"],
json!({"idle_watts": 8.2}),
"the last snapshot stays, shown as unavailable"
);

for plugin_id in ["powermetrics", "other"] {
node.forward_plugin_event(plugin::PluginMeshEvent::PluginStopped {
plugin_id: plugin_id.into(),
})
.await
.unwrap();
}
let status_body = request_management_json(state.clone(), "/api/status").await;
assert!(status_body.get("powermetrics").is_none());
assert!(status_body.get("other").is_none());

drop(events);
handle.abort();
}

#[tokio::test]
async fn a_refused_plugin_status_says_why_and_changes_nothing() {
let state = build_test_mesh_api().await;
let node = state.inner.lock().await.node.clone();

let error = publish_test_plugin_status(&node, "powermetrics", "[1, 2]")
.await
.unwrap_err();
assert_eq!(error.code, ErrorCode::INVALID_PARAMS.0);
assert!(error.message.contains("must be a JSON object"), "{}", error.message);

let oversized = format!(
r#"{{"pad":"{}"}}"#,
"x".repeat(mesh_llm_plugin::plugin_status::MAX_DATA_BYTES)
);
let error = publish_test_plugin_status(&node, "powermetrics", &oversized)
.await
.unwrap_err();
assert!(error.message.contains("the limit is 16384"), "{}", error.message);

let error = publish_test_plugin_status(&node, "peers", r#"{"n":1}"#)
.await
.unwrap_err();
assert!(error.message.contains("core /api/status field"), "{}", error.message);

let status_body = request_management_json(state, "/api/status").await;
assert!(status_body.get("powermetrics").is_none());
assert!(status_body["peers"].is_array(), "the core field is untouched");
}

#[tokio::test]
async fn api_runtime_reads_from_collector_snapshot() {
let state = build_test_mesh_api().await;
Expand Down
30 changes: 29 additions & 1 deletion mesh/crates/mesh-llm-host-runtime/src/mesh/plugin_mesh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,10 +246,38 @@ impl Node {
let _ = response_tx.send(self.apply_plugin_key_request(&plugin_id, request));
Ok(())
}
crate::plugin::PluginMeshEvent::PluginStatus {
plugin_id,
generation,
schema_version,
request,
response_tx,
} => {
let response = self
.runtime_data_collector()
.publish_plugin_status(&plugin_id, generation, schema_version, &request)
.map_err(|rejection| crate::plugin::proto::ErrorResponse {
code: rmcp::model::ErrorCode::INVALID_PARAMS.0,
message: rejection.message(&plugin_id),
data_json: String::new(),
});
let _ = response_tx.send(response);
Ok(())
}
crate::plugin::PluginMeshEvent::PluginDisconnected {
plugin_id,
generation,
} => {
self.runtime_data_collector()
.mark_plugin_status_unavailable(&plugin_id, generation);
Ok(())
}
crate::plugin::PluginMeshEvent::PluginStopped { plugin_id } => {
// A disabled or removed plugin no longer runs here, so this
// node stops vouching for its key.
// node stops vouching for its key and showing its status.
self.plugin_keys.remove_own(&plugin_id);
self.runtime_data_collector()
.remove_plugin_status(&plugin_id);
Ok(())
}
}
Expand Down
2 changes: 2 additions & 0 deletions mesh/crates/mesh-llm-host-runtime/src/plugin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1736,5 +1736,7 @@ pub async fn run_plugin_process(name: String, args: Vec<String>) -> Result<()> {
}
}

#[cfg(test)]
mod status_contribution_tests;
#[cfg(test)]
mod tests;
Loading
Loading