Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
34 changes: 34 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,35 @@ 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, by the
/// host's name for each plugin; see [`PluginStatusPayload`]. Local-only,
/// and omitted while no plugin contributes, so the shape is unchanged.
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub(crate) plugin_status: BTreeMap<String, PluginStatusPayload>,
}

/// 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 @@ -1059,6 +1089,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 +1165,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 +1241,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 +1312,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
113 changes: 113 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,119 @@ 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("plugin_status").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("\"plugin_status\""));

let status_body = request_management_json(state.clone(), "/api/status").await;
let contribution = &status_body["plugin_status"]["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["plugin_status"]["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["plugin_status"]["powermetrics"]["state"],
json!("unavailable")
);
assert_eq!(
status_body["plugin_status"]["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("plugin_status").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 status_body = request_management_json(state, "/api/status").await;
assert!(status_body.get("plugin_status").is_none());
}

#[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;
15 changes: 13 additions & 2 deletions mesh/crates/mesh-llm-host-runtime/src/plugin/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,10 @@ mod identity_artifact;
mod lifecycle_readiness;
mod shutdown;
mod socket_auth;
pub(crate) mod status_publication;

use self::default_plugin_policy::restrict_default_plugin;
use self::status_publication::StatusDeclaration;

/// How long a stopping plugin waits to tell the node to withdraw its key.
const PLUGIN_STOPPED_SEND_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1);
Expand Down Expand Up @@ -65,6 +67,8 @@ pub(crate) struct PluginRuntime {
pub(crate) generation: u64,
pub(crate) authenticated_peer: bool,
pub(crate) initialized_lifecycle: Option<Box<proto::OpenAiExchangeHookManifest>>,
/// What this generation's manifest says about `/api/status`.
pub(crate) status_declaration: StatusDeclaration,
pub(crate) _child: Option<Child>,
connection_task: tokio::task::JoinHandle<()>,
pub(crate) outbound_tx: mpsc::Sender<proto::Envelope>,
Expand Down Expand Up @@ -318,6 +322,7 @@ impl ExternalPlugin {
generation,
authenticated_peer,
initialized_lifecycle: None,
status_declaration: StatusDeclaration::Pending,
_child: child,
connection_task,
outbound_tx,
Expand Down Expand Up @@ -347,6 +352,7 @@ impl ExternalPlugin {
mesh_llm_plugin::host_capabilities::PEER_BLOCKS.to_string(),
mesh_llm_plugin::host_capabilities::OPENAI_EXCHANGE.to_string(),
mesh_llm_plugin::host_capabilities::PLUGIN_KEYS.to_string(),
mesh_llm_plugin::host_capabilities::PLUGIN_STATUS.to_string(),
],
}),
Some(self.spec.startup.init_timeout()),
Expand Down Expand Up @@ -434,6 +440,7 @@ impl ExternalPlugin {
manifest.openai_exchange_hook.as_deref(),
self.spec.openai_exchange_grant.as_deref(),
)?;
status_publication::validate_declaration(&self.spec.name, manifest)?;
}
Ok(())
}
Expand Down Expand Up @@ -918,7 +925,9 @@ impl ExternalPlugin {
failed_runtime
};
if let Some(runtime) = failed_runtime {
let generation = runtime.generation;
stop_runtime(runtime, &reason).await;
status_publication::announce_disconnected(&self.mesh_tx, &self.spec.name, generation);
}
self.publish_summary().await;
}
Expand Down Expand Up @@ -1209,7 +1218,7 @@ pub(crate) mod tests {
plugin_for_spec_with_mesh_tx(spec, mesh_tx)
}

fn plugin_for_spec_with_mesh_tx(
pub(super) fn plugin_for_spec_with_mesh_tx(
spec: ExternalPluginSpec,
mesh_tx: mpsc::Sender<PluginMeshEvent>,
) -> (ExternalPlugin, RuntimeDataCollector) {
Expand Down Expand Up @@ -1292,7 +1301,7 @@ pub(crate) mod tests {
command
}

async fn mark_plugin_running(plugin: &ExternalPlugin, generation: u64) {
pub(super) async fn mark_plugin_running(plugin: &ExternalPlugin, generation: u64) {
let child = sleeping_test_command()
.kill_on_drop(true)
.spawn()
Expand All @@ -1303,6 +1312,7 @@ pub(crate) mod tests {
generation,
authenticated_peer: true,
initialized_lifecycle: None,
status_declaration: StatusDeclaration::Pending,
_child: Some(child),
connection_task: tokio::spawn(std::future::pending::<()>()),
outbound_tx,
Expand Down Expand Up @@ -1871,6 +1881,7 @@ pub(crate) mod tests {
generation: 1,
authenticated_peer: true,
initialized_lifecycle: None,
status_declaration: StatusDeclaration::Pending,
_child: Some(child),
connection_task: tokio::spawn(std::future::pending::<()>()),
outbound_tx: outbound_tx.clone(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ pub(super) fn restrict_default_plugin(
if !may(Surface::OpenAiExchangeHook) && manifest.openai_exchange_hook.take().is_some() {
removed.push(Surface::OpenAiExchangeHook.name());
}
if !may(Surface::StatusContributions) && manifest.plugin_status.take().is_some() {
removed.push(Surface::StatusContributions.name());
}
}
if capabilities_removed {
removed.push("capabilities");
Expand Down Expand Up @@ -163,6 +166,35 @@ mod tests {
assert_eq!(removed, ["OpenAI exchange hook"]);
}

#[test]
fn a_default_keeps_its_status_contribution_only_when_its_entry_allows_it() {
let with_status = || proto::InitializeResponse {
manifest: Some(proto::PluginManifest {
plugin_status: Some(proto::PluginStatusManifest {
schema_version: 1,
required: false,
}),
..Default::default()
}),
..Default::default()
};

let mut init = with_status();
let removed = restrict_default_plugin(&mut init, &[Surface::WebUi], &[]);
assert_eq!(removed, ["status contributions"]);
assert!(init.manifest.unwrap().plugin_status.is_none());

let mut init = with_status();
let removed = restrict_default_plugin(&mut init, &[Surface::StatusContributions], &[]);
assert!(removed.is_empty());
assert!(init.manifest.unwrap().plugin_status.is_some());

// Unlike the exchange hook, it shows only the plugin's own data, so an
// unlisted default keeps it.
let mut init = with_status();
assert!(restrict_default_plugin(&mut init, UNLISTED_DEFAULT_ALLOWS, &[]).is_empty());
}

#[test]
fn a_default_within_its_allowlist_loses_nothing_and_warns_of_nothing() {
let mut init = proto::InitializeResponse {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ async fn running_observer() -> (Arc<ExternalPlugin>, mpsc::Receiver<super::proto
initialized_lifecycle: Some(Box::new(
mesh_llm_plugin::openai_exchange::openai_exchange_hook("observe"),
)),
status_declaration: Default::default(),
_child: None,
connection_task: tokio::spawn(std::future::pending()),
outbound_tx,
Expand Down
Loading
Loading