diff --git a/mesh/crates/mesh-llm-host-runtime/src/api/mod.rs b/mesh/crates/mesh-llm-host-runtime/src/api/mod.rs index dce5895765..4a83038b82 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/api/mod.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/api/mod.rs @@ -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 } diff --git a/mesh/crates/mesh-llm-host-runtime/src/api/status.rs b/mesh/crates/mesh-llm-host-runtime/src/api/status.rs index c56f901559..d853e4c7ba 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/api/status.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/api/status.rs @@ -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 { let engine = crate::runtime_events::runtime_event_engine()?; @@ -391,6 +392,36 @@ 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, + /// `plugins`: 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(rename = "plugins", skip_serializing_if = "BTreeMap::is_empty")] + pub(crate) plugin_status: BTreeMap, +} + +/// 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. @@ -1059,6 +1090,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"); @@ -1134,6 +1166,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"); @@ -1209,6 +1242,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"); @@ -1279,6 +1313,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"); diff --git a/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs b/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs index 3f027a7f8c..37f63ebc4a 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/api/tests/runtime_data.rs @@ -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 { + 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("plugins").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("\"plugins\"")); + + let status_body = request_management_json(state.clone(), "/api/status").await; + let contribution = &status_body["plugins"]["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["plugins"]["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["plugins"]["powermetrics"]["state"], + json!("unavailable") + ); + assert_eq!( + status_body["plugins"]["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("plugins").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("plugins").is_none()); +} + #[tokio::test] async fn api_runtime_reads_from_collector_snapshot() { let state = build_test_mesh_api().await; diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/plugin_mesh.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/plugin_mesh.rs index 6dac6af4d1..e2c6b22d76 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/plugin_mesh.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/plugin_mesh.rs @@ -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(()) } } 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 1f149d9ad8..c1b8b1219f 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/mod.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/mod.rs @@ -1736,5 +1736,7 @@ pub async fn run_plugin_process(name: String, args: Vec) -> Result<()> { } } +#[cfg(test)] +mod status_contribution_tests; #[cfg(test)] mod tests; diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime.rs index 7075abd59d..2de055d568 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime.rs @@ -34,8 +34,10 @@ mod lifecycle_readiness; mod restart_tests; 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); @@ -67,6 +69,8 @@ pub(crate) struct PluginRuntime { pub(crate) generation: u64, pub(crate) authenticated_peer: bool, pub(crate) initialized_lifecycle: Option>, + /// What this generation's manifest says about `/api/status`. + pub(crate) status_declaration: StatusDeclaration, pub(crate) _child: Option, connection_task: tokio::task::JoinHandle<()>, pub(crate) outbound_tx: mpsc::Sender, @@ -320,6 +324,7 @@ impl ExternalPlugin { generation, authenticated_peer, initialized_lifecycle: None, + status_declaration: StatusDeclaration::Pending, _child: child, connection_task, outbound_tx, @@ -349,6 +354,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()), @@ -436,6 +442,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(()) } @@ -920,7 +927,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; } @@ -1211,7 +1220,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, ) -> (ExternalPlugin, RuntimeDataCollector) { @@ -1294,7 +1303,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() @@ -1305,6 +1314,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, @@ -1873,6 +1883,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(), diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/default_plugin_policy.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/default_plugin_policy.rs index da79e2f4fb..2eb1d6d149 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/default_plugin_policy.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/default_plugin_policy.rs @@ -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"); @@ -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 { diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/exchange_request_tests.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/exchange_request_tests.rs index ff752ce808..dcd00dcab4 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/exchange_request_tests.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/exchange_request_tests.rs @@ -24,6 +24,7 @@ async fn running_observer() -> (Arc, mpsc::Receiver) -> Self { + match manifest.and_then(|manifest| manifest.plugin_status.as_ref()) { + Some(status) => Self::Declared { + schema_version: status.schema_version, + }, + None => Self::Undeclared, + } + } +} + +/// Tell the node that connection `generation` of `plugin_name` is gone, so what +/// it published to `/api/status` shows as unavailable. The notice waits for +/// room in the node's queue on its own task rather than giving up after a +/// deadline, since a lost notice would leave the snapshot `ready`; it ends at +/// once if the node is gone. The node marks only a snapshot from this +/// generation, so a late notice never touches a newer connection's. +pub(crate) fn announce_disconnected( + mesh_tx: &mpsc::Sender, + plugin_name: &str, + generation: u64, +) { + let mesh_tx = mesh_tx.clone(); + let event = PluginMeshEvent::PluginDisconnected { + plugin_id: plugin_name.to_string(), + generation, + }; + tokio::spawn(async move { + let _ = mesh_tx.send(event).await; + }); +} + +/// Refuse a declaration whose schema version is 0: versions start at 1. +pub(crate) fn validate_declaration( + plugin_name: &str, + manifest: &proto::PluginManifest, +) -> anyhow::Result<()> { + if manifest + .plugin_status + .as_ref() + .is_some_and(|status| status.schema_version == 0) + { + anyhow::bail!( + "Plugin '{plugin_name}' declares a status contribution with schema_version 0; it starts at 1" + ); + } + Ok(()) +} + +/// Publications a lane holds before it answers new ones as busy. The host +/// accepts one a second, so a well-behaved plugin never has more than one. +const LANE_CAPACITY: usize = 4; +/// How long a publication waits for its connection to finish initializing, +/// and then for the node to answer. +const PUBLICATION_TIMEOUT: Duration = Duration::from_secs(crate::plugin::REQUEST_TIMEOUT_SECS); +const INITIALIZATION_POLL: Duration = Duration::from_millis(10); + +type Publication = (u64, proto::PublishPluginStatusRequest); + +pub(crate) struct StatusLane { + plugin_name: String, + tx: mpsc::Sender, + outbound_tx: mpsc::Sender, +} + +impl StatusLane { + /// Start the lane for connection `generation` of `plugin_name`. It ends + /// when the lane is dropped and its queue is drained. + pub(crate) fn spawn( + plugin_name: String, + generation: u64, + runtime: Arc>>, + mesh_tx: mpsc::Sender, + outbound_tx: mpsc::Sender, + ) -> Self { + let (tx, mut rx) = mpsc::channel::(LANE_CAPACITY); + let lane = Self { + plugin_name: plugin_name.clone(), + tx, + outbound_tx: outbound_tx.clone(), + }; + tokio::spawn(async move { + while let Some((request_id, request)) = rx.recv().await { + let payload = match publish(&plugin_name, generation, &runtime, &mesh_tx, request) + .await + { + Ok(response) => proto::envelope::Payload::PublishPluginStatusResponse(response), + Err(error) => proto::envelope::Payload::ErrorResponse(error), + }; + let _ = outbound_tx + .send(envelope(&plugin_name, request_id, payload)) + .await; + } + }); + lane + } + + /// Queue a publication without waiting; a full lane answers it at once. + pub(crate) fn push(&self, request_id: u64, request: proto::PublishPluginStatusRequest) { + if let Err(mpsc::error::TrySendError::Full(_)) = self.tx.try_send((request_id, request)) { + let outbound_tx = self.outbound_tx.clone(); + let reply = envelope( + &self.plugin_name, + request_id, + proto::envelope::Payload::ErrorResponse(error( + ErrorCode::INVALID_REQUEST, + format!( + "plugin `{}` has {LANE_CAPACITY} status publications waiting; retry later", + self.plugin_name + ), + )), + ); + tokio::spawn(async move { + let _ = outbound_tx.send(reply).await; + }); + } + } +} + +async fn publish( + plugin_name: &str, + generation: u64, + runtime: &Mutex>, + mesh_tx: &mpsc::Sender, + request: proto::PublishPluginStatusRequest, +) -> Result { + let deadline = tokio::time::Instant::now() + PUBLICATION_TIMEOUT; + let response_rx = + hand_over(plugin_name, generation, runtime, mesh_tx, request, deadline).await?; + match tokio::time::timeout_at(deadline, response_rx).await { + Ok(Ok(response)) => response, + Ok(Err(_)) => Err(error( + ErrorCode::INTERNAL_ERROR, + "status publication handler dropped the response", + )), + Err(_) => Err(error( + ErrorCode::INTERNAL_ERROR, + "status publication timed out", + )), + } +} + +type PublicationResponse = + oneshot::Receiver>; + +async fn hand_over( + plugin_name: &str, + generation: u64, + runtime: &Mutex>, + mesh_tx: &mpsc::Sender, + request: proto::PublishPluginStatusRequest, + deadline: tokio::time::Instant, +) -> Result { + loop { + { + let runtime = runtime.lock().await; + let Some(current) = runtime + .as_ref() + .filter(|runtime| runtime.generation == generation) + else { + return Err(error( + ErrorCode::INVALID_REQUEST, + format!( + "plugin `{plugin_name}` published its status from a connection that is no longer current" + ), + )); + }; + match current.status_declaration { + StatusDeclaration::Pending => {} + StatusDeclaration::Undeclared => { + return Err(error( + ErrorCode::INVALID_REQUEST, + format!( + "plugin `{plugin_name}` does not declare `plugin_status` in its manifest" + ), + )); + } + StatusDeclaration::Declared { schema_version } => { + let (response_tx, response_rx) = oneshot::channel(); + // Still under the runtime lock: see the module docs. + return match mesh_tx.try_send(PluginMeshEvent::PluginStatus { + plugin_id: plugin_name.to_string(), + generation, + schema_version, + request, + response_tx, + }) { + Ok(()) => Ok(response_rx), + Err(mpsc::error::TrySendError::Full(_)) => Err(error( + ErrorCode::INTERNAL_ERROR, + "the node is busy; retry the status publication later", + )), + Err(mpsc::error::TrySendError::Closed(_)) => Err(error( + ErrorCode::INTERNAL_ERROR, + "status publication handler is unavailable", + )), + }; + } + } + } + if tokio::time::Instant::now() >= deadline { + return Err(error( + ErrorCode::INVALID_REQUEST, + format!( + "plugin `{plugin_name}` published its status before it finished initializing" + ), + )); + } + tokio::time::sleep(INITIALIZATION_POLL).await; + } +} + +fn envelope( + plugin_name: &str, + request_id: u64, + payload: proto::envelope::Payload, +) -> proto::Envelope { + proto::Envelope { + protocol_version: PROTOCOL_VERSION, + plugin_id: plugin_name.to_string(), + request_id, + payload: Some(payload), + } +} + +fn error(code: ErrorCode, message: impl Into) -> proto::ErrorResponse { + proto::ErrorResponse { + code: code.0, + message: message.into(), + data_json: String::new(), + } +} + +#[cfg(test)] +#[path = "status_publication_tests.rs"] +mod tests; diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication_tests.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication_tests.rs new file mode 100644 index 0000000000..7427a0e52c --- /dev/null +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/runtime/status_publication_tests.rs @@ -0,0 +1,274 @@ +use super::super::tests as runtime_tests; +use super::*; +use std::collections::HashMap; + +fn runtime_with(generation: u64, declaration: StatusDeclaration) -> PluginRuntime { + let (outbound_tx, _outbound_rx) = mpsc::channel(4); + PluginRuntime { + generation, + authenticated_peer: false, + initialized_lifecycle: None, + status_declaration: declaration, + _child: None, + connection_task: tokio::spawn(std::future::pending()), + outbound_tx, + pending: Arc::new(Mutex::new(HashMap::new())), + } +} + +struct Harness { + runtime: Arc>>, + lane: StatusLane, + mesh_rx: mpsc::Receiver, + outbound_rx: mpsc::Receiver, +} + +fn harness(lane_generation: u64, runtime: Option) -> Harness { + let runtime = Arc::new(Mutex::new(runtime)); + let (mesh_tx, mesh_rx) = mpsc::channel(8); + let (outbound_tx, outbound_rx) = mpsc::channel(8); + let lane = StatusLane::spawn( + "demo".into(), + lane_generation, + runtime.clone(), + mesh_tx, + outbound_tx, + ); + Harness { + runtime, + lane, + mesh_rx, + outbound_rx, + } +} + +fn publication(data_json: &str) -> proto::PublishPluginStatusRequest { + proto::PublishPluginStatusRequest { + data_json: data_json.into(), + fresh_for_ms: 0, + } +} + +async fn reply(outbound_rx: &mut mpsc::Receiver) -> proto::Envelope { + tokio::time::timeout(Duration::from_secs(5), outbound_rx.recv()) + .await + .expect("the lane answers") + .expect("the lane is open") +} + +fn error_message(envelope: proto::Envelope) -> String { + match envelope.payload { + Some(proto::envelope::Payload::ErrorResponse(error)) => error.message, + other => panic!("expected an error, got {other:?}"), + } +} + +#[tokio::test] +async fn a_publication_sent_before_initialization_finishes_waits_for_it() { + let mut h = harness(3, Some(runtime_with(3, StatusDeclaration::Pending))); + h.lane.push(11, publication(r#"{"watts":8.2}"#)); + + tokio::time::sleep(Duration::from_millis(50)).await; + assert!( + h.mesh_rx.try_recv().is_err(), + "nothing before initialization" + ); + h.runtime.lock().await.as_mut().unwrap().status_declaration = + StatusDeclaration::Declared { schema_version: 2 }; + + let event = tokio::time::timeout(Duration::from_secs(5), h.mesh_rx.recv()) + .await + .unwrap() + .unwrap(); + let PluginMeshEvent::PluginStatus { + plugin_id, + generation, + schema_version, + request, + response_tx, + } = event + else { + panic!("expected a status publication"); + }; + assert_eq!(plugin_id, "demo", "the host's name for the connection"); + assert_eq!((generation, schema_version), (3, 2)); + assert_eq!(request.data_json, r#"{"watts":8.2}"#); + response_tx + .send(Ok(proto::PublishPluginStatusResponse { + received_at_unix_ms: 1, + fresh_until_unix_ms: 2, + })) + .unwrap(); + + let answer = reply(&mut h.outbound_rx).await; + assert_eq!(answer.request_id, 11); + assert_eq!(answer.plugin_id, "demo"); + assert!(matches!( + answer.payload, + Some(proto::envelope::Payload::PublishPluginStatusResponse(ref response)) + if response.fresh_until_unix_ms == 2 + )); +} + +#[tokio::test] +async fn a_plugin_that_does_not_declare_it_is_refused() { + let mut h = harness(3, Some(runtime_with(3, StatusDeclaration::Undeclared))); + h.lane.push(1, publication("{}")); + let message = error_message(reply(&mut h.outbound_rx).await); + assert!( + message.contains("does not declare `plugin_status`"), + "{message}" + ); + assert!(h.mesh_rx.try_recv().is_err()); +} + +#[tokio::test] +async fn a_connection_that_is_no_longer_current_is_refused() { + let declared = StatusDeclaration::Declared { schema_version: 1 }; + // The plugin restarted: the runtime is a later connection's. + let mut h = harness(3, Some(runtime_with(4, declared))); + h.lane.push(1, publication("{}")); + let message = error_message(reply(&mut h.outbound_rx).await); + assert!(message.contains("no longer current"), "{message}"); + + // The connection is gone, and the runtime with it. + let mut h = harness(3, None); + h.lane.push(1, publication("{}")); + let message = error_message(reply(&mut h.outbound_rx).await); + assert!(message.contains("no longer current"), "{message}"); + assert!(h.mesh_rx.try_recv().is_err()); +} + +#[tokio::test] +async fn publications_reach_the_node_in_the_order_they_were_sent() { + let declared = StatusDeclaration::Declared { schema_version: 1 }; + let mut h = harness(3, Some(runtime_with(3, declared))); + for (id, data) in [(1, r#"{"n":1}"#), (2, r#"{"n":2}"#), (3, r#"{"n":3}"#)] { + h.lane.push(id, publication(data)); + } + for expected in [r#"{"n":1}"#, r#"{"n":2}"#, r#"{"n":3}"#] { + let Some(PluginMeshEvent::PluginStatus { + request, + response_tx, + .. + }) = h.mesh_rx.recv().await + else { + panic!("expected a status publication"); + }; + assert_eq!(request.data_json, expected); + response_tx + .send(Ok(proto::PublishPluginStatusResponse::default())) + .unwrap(); + } + let ids = [ + reply(&mut h.outbound_rx).await.request_id, + reply(&mut h.outbound_rx).await.request_id, + reply(&mut h.outbound_rx).await.request_id, + ]; + assert_eq!(ids, [1, 2, 3]); +} + +#[tokio::test] +async fn a_full_lane_answers_busy_at_once() { + // The first publication waits for initialization, so the next ones queue. + let mut h = harness(3, Some(runtime_with(3, StatusDeclaration::Pending))); + h.lane.push(1, publication("{}")); + tokio::time::sleep(Duration::from_millis(20)).await; + for id in 2..=(LANE_CAPACITY as u64 + 1) { + h.lane.push(id, publication("{}")); + } + h.lane.push(99, publication("{}")); + let answer = reply(&mut h.outbound_rx).await; + assert_eq!(answer.request_id, 99); + let message = error_message(answer); + assert!(message.contains("retry later"), "{message}"); +} + +#[tokio::test] +async fn a_failed_connection_tells_the_node_its_status_is_unavailable() { + let temp = tempfile::tempdir().unwrap(); + let (mesh_tx, mut mesh_rx) = mpsc::channel(8); + let (plugin, _runtime_data) = runtime_tests::plugin_for_spec_with_mesh_tx( + runtime_tests::plugin_spec( + &temp, + None, + mesh_llm_plugin_manager::store::InstalledPluginWebUiValidationStatus::Valid, + None, + ), + mesh_tx, + ); + runtime_tests::mark_plugin_running(&plugin, 4).await; + + plugin + .handle_runtime_failure(Some(4), "plugin exited".into()) + .await; + let disconnected = tokio::time::timeout(Duration::from_secs(5), async { + loop { + if let Some(PluginMeshEvent::PluginDisconnected { + plugin_id, + generation, + }) = mesh_rx.recv().await + { + break (plugin_id, generation); + } + } + }) + .await + .expect("the node is told"); + assert_eq!(disconnected, ("demo".to_string(), 4)); + + // No runtime, nothing to announce. + plugin + .handle_runtime_failure(None, "plugin exited".into()) + .await; + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(mesh_rx.try_recv().is_err()); +} + +#[tokio::test(start_paused = true)] +async fn a_disconnect_notice_waits_for_a_full_node_queue_instead_of_being_lost() { + let (mesh_tx, mut mesh_rx) = mpsc::channel(1); + mesh_tx + .try_send(PluginMeshEvent::PluginStopped { + plugin_id: "other".into(), + }) + .unwrap(); + announce_disconnected(&mesh_tx, "demo", 7); + + // Far longer than any deadline a bounded send would have given it. + tokio::time::sleep(Duration::from_secs(60)).await; + assert!(matches!( + mesh_rx.recv().await, + Some(PluginMeshEvent::PluginStopped { .. }) + )); + let notice = tokio::time::timeout(Duration::from_secs(1), mesh_rx.recv()) + .await + .expect("the notice is delivered once there is room"); + assert!(matches!( + notice, + Some(PluginMeshEvent::PluginDisconnected { ref plugin_id, generation: 7 }) if plugin_id == "demo" + )); +} + +#[test] +fn a_declaration_must_name_a_schema_version() { + let manifest = |schema_version| proto::PluginManifest { + plugin_status: Some(proto::PluginStatusManifest { + schema_version, + required: false, + }), + ..Default::default() + }; + let error = validate_declaration("demo", &manifest(0)).unwrap_err(); + assert!(error.to_string().contains("schema_version 0"), "{error}"); + validate_declaration("demo", &manifest(1)).unwrap(); + validate_declaration("demo", &proto::PluginManifest::default()).unwrap(); + assert_eq!( + StatusDeclaration::from_manifest(Some(&manifest(3))), + StatusDeclaration::Declared { schema_version: 3 } + ); + assert_eq!( + StatusDeclaration::from_manifest(Some(&proto::PluginManifest::default())), + StatusDeclaration::Undeclared + ); +} diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/status_contribution_tests.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/status_contribution_tests.rs new file mode 100644 index 0000000000..f6f027b769 --- /dev/null +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/status_contribution_tests.rs @@ -0,0 +1,141 @@ +//! Status contributions over the real plugin protocol: from an SDK plugin +//! publishing in `on_initialized` to the node's `/api/status` data. + +use super::*; +use crate::api::status::PluginStatusState; +use crate::plugin::{InProcessPluginRunner, InProcessPlugins, config}; +use mesh_llm_plugin::{PluginMetadata, PluginRuntime, SimplePlugin}; +use std::time::Duration; + +type PublishResults = mpsc::Sender<(String, std::result::Result<(), String>)>; + +/// A plugin that publishes `{"from": }` as soon as it is initialized and +/// reports how that went. +fn publisher(name: &'static str, declares: bool, results: PublishResults) -> InProcessPluginRunner { + Arc::new(move |stream| { + let mut manifest = mesh_llm_plugin::plugin_manifest(); + if declares { + manifest = manifest.item(mesh_llm_plugin::plugin_status::plugin_status(1)); + } + let results = results.clone(); + let plugin = SimplePlugin::new( + PluginMetadata::new( + name, + "1.0.0", + mesh_llm_plugin::plugin_server_info( + name, + "1.0.0", + "Publisher", + "Publishes its status", + None::, + ), + ) + .with_manifest(manifest.build()), + ) + .on_initialized(move |context| { + let results = results.clone(); + Box::pin(async move { + let published = context + .publish_status(&serde_json::json!({"from": name}), Duration::from_secs(30)) + .await + .map(|_| ()) + .map_err(|error| error.to_string()); + let _ = results.send((name.to_string(), published)).await; + Ok(()) + }) + }); + Box::pin(PluginRuntime::run_with_stream(plugin, stream)) + }) +} + +async fn start( + plugins: &[(&'static str, bool)], +) -> ( + PluginManager, + crate::mesh::Node, + mpsc::Receiver<(String, std::result::Result<(), String>)>, +) { + let node = crate::mesh::Node::new_for_tests(crate::mesh::NodeRole::Worker) + .await + .unwrap(); + let (mesh_tx, mesh_rx) = mpsc::channel(16); + node.start_plugin_channel_forwarder(mesh_rx); + let (results_tx, results_rx) = mpsc::channel(8); + let mut in_process = InProcessPlugins::default(); + let mut externals = Vec::new(); + for &(name, declares) in plugins { + in_process = in_process.with(name, publisher(name, declares, results_tx.clone())); + let mut spec = config::in_process_builtin_spec(name); + spec.startup.optional = false; + externals.push(spec); + } + let manager = PluginManager::start_with_in_process( + &config::ResolvedPlugins { + externals, + inactive: Vec::new(), + }, + config::PluginHostMode { + mesh_visibility: mesh_llm_plugin::MeshVisibility::Private, + }, + mesh_tx, + in_process, + ) + .await + .unwrap(); + (manager, node, results_rx) +} + +async fn results( + rx: &mut mpsc::Receiver<(String, std::result::Result<(), String>)>, + count: usize, +) -> BTreeMap> { + let mut out = BTreeMap::new(); + while out.len() < count { + let (name, result) = tokio::time::timeout(Duration::from_secs(10), rx.recv()) + .await + .expect("every plugin reports its publication") + .unwrap(); + out.insert(name, result); + } + out +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn plugins_publishing_on_initialization_show_up_in_the_node_status() { + let (manager, node, mut results_rx) = + start(&[("alpha", true), ("beta", true), ("gamma", false)]).await; + + let results = results(&mut results_rx, 3).await; + assert_eq!(results["alpha"], Ok(())); + assert_eq!(results["beta"], Ok(())); + let refused = results["gamma"].as_ref().unwrap_err(); + assert!( + refused.contains("does not declare `plugin_status`"), + "{refused}" + ); + + let payloads = node.runtime_data_collector().plugin_status_payloads(); + assert_eq!( + payloads.keys().collect::>(), + ["alpha", "beta"], + "a plugin that does not declare it contributes nothing" + ); + for name in ["alpha", "beta"] { + assert_eq!(payloads[name].state, PluginStatusState::Ready); + assert_eq!(payloads[name].data, serde_json::json!({"from": name})); + } + + // Shutting the plugins down removes what they contributed. + manager.shutdown().await; + tokio::time::timeout(Duration::from_secs(5), async { + while !node + .runtime_data_collector() + .plugin_status_payloads() + .is_empty() + { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("stopped plugins no longer contribute"); +} diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/transport.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/transport.rs index 6ac2115c82..4f12ed8b2b 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/transport.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/transport.rs @@ -90,6 +90,8 @@ pub(crate) const CONNECTION_LOOP: ConnectionLoopFn = let authenticated_peer = peer_state.load(Ordering::Acquire); Box::pin(async move { let result: Result<()> = async { + // Started by the first status publication, if any. + let mut status_lane = None; loop { tokio::select! { maybe_outbound = outbound_rx.recv() => { @@ -163,6 +165,21 @@ pub(crate) const CONNECTION_LOOP: ConnectionLoopFn = outbound_tx.clone(), ); } + Some(super::proto::envelope::Payload::PublishPluginStatusRequest(request)) => { + // Shown under the connection's own name, + // so one plugin cannot publish as another. + status_lane + .get_or_insert_with(|| { + super::runtime::status_publication::StatusLane::spawn( + plugin_name.clone(), + generation, + runtime.clone(), + mesh_tx.clone(), + outbound_tx.clone(), + ) + }) + .push(request_id, request); + } Some(super::proto::envelope::Payload::RpcRequest(request)) => { forward_plugin_request( plugin_name.clone(), @@ -238,6 +255,12 @@ pub(crate) const CONNECTION_LOOP: ConnectionLoopFn = summary.pid = None; summary.error = Some(format!("Plugin '{}' disconnected", plugin_name)); } + drop(summary); + super::runtime::status_publication::announce_disconnected( + &mesh_tx, + &plugin_name, + generation, + ); } let mut pending = pending.lock().await; diff --git a/mesh/crates/mesh-llm-host-runtime/src/plugin/types.rs b/mesh/crates/mesh-llm-host-runtime/src/plugin/types.rs index 3e86bd6663..7ef0ee60f0 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/plugin/types.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/plugin/types.rs @@ -42,6 +42,21 @@ pub enum PluginMeshEvent { request: proto::PluginKeyRequest, response_tx: oneshot::Sender>, }, + /// A snapshot for `/api/status`, from the plugin's current initialized + /// connection `generation`, whose manifest declares `schema_version`. + /// `plugin_id` is the host's name for the plugin connection. + PluginStatus { + plugin_id: String, + generation: u64, + schema_version: u32, + request: proto::PublishPluginStatusRequest, + response_tx: + oneshot::Sender>, + }, + /// The plugin connection `generation` is gone (it closed, or failed and + /// the plugin restarts): what it published to `/api/status` is shown as + /// unavailable until a later connection publishes. + PluginDisconnected { plugin_id: String, generation: u64 }, /// The plugin stopped for good (disabled, or shut down): the host /// withdraws what it announced for it. Not sent when the plugin restarts /// after a failure, so its key stays announced across a restart. diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/api_views.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/api_views.rs index dab517c2d8..f9b610f10c 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/api_views.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/api_views.rs @@ -85,6 +85,7 @@ pub(crate) fn status_payload(snapshot: StatusViewSnapshot) -> StatusPayload { recent_mesh_rejections: vec![], plugin_frame_telemetry: PluginFrameTelemetryPayload::default(), logging: None, + plugin_status: Default::default(), } } @@ -253,6 +254,7 @@ mod tests { recent_mesh_rejections: vec![], plugin_frame_telemetry: PluginFrameTelemetryPayload::default(), logging: None, + plugin_status: Default::default(), }; assert_eq!( diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/collector.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/collector.rs index c164407ad9..c1d064d0aa 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/collector.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/collector.rs @@ -10,6 +10,7 @@ use super::inventory::{ InventoryScanCoordinator, InventoryScanDisposition, InventoryScanError, InventoryScanOutcome, InventoryScanResult, replace_local_instances_snapshot, replace_local_inventory_snapshot, }; +use super::plugin_status::{PluginStatusRejection, PluginStatusStore}; use super::plugins::{ PluginDataValue, PluginsSnapshotView, clear_plugin_data, clear_plugin_endpoints, plugins_snapshot, upsert_plugin_data, upsert_plugin_endpoint, @@ -49,6 +50,8 @@ use tokio::sync::watch; #[derive(Default)] struct RuntimeDataSharedState { snapshots: RwLock, + /// Apart from `snapshots`, so that cloning them does not copy plugin data. + plugin_status: Mutex, subscriptions: RuntimeDataSubscriptions, inventory_scan: Mutex, event_cutover_health: ShadowHealth, @@ -387,6 +390,82 @@ impl RuntimeDataCollector { }) } + /// Keep `request` as `plugin_name`'s contribution to `/api/status`. The + /// caller vouches that it comes from the plugin's current initialized + /// connection `generation`, whose manifest declares `schema_version`. + pub(crate) fn publish_plugin_status( + &self, + plugin_name: &str, + generation: u64, + schema_version: u32, + request: &crate::plugin::proto::PublishPluginStatusRequest, + ) -> Result { + let mut store = self.plugin_status_store(); + let accepted = store.publish( + plugin_name, + generation, + schema_version, + request, + tokio::time::Instant::now(), + crate::mesh::current_time_unix_ms(), + )?; + if let Some(fresh_for) = accepted.fresh_for + && let Some(expiry) = self.wake_status_after(fresh_for) + { + store.set_expiry(plugin_name, expiry); + } + drop(store); + self.shared.subscriptions.publish(RuntimeDataDirty::STATUS); + Ok(accepted.response) + } + + /// The plugin connection `generation` is gone: its snapshot stays, shown + /// as unavailable. + pub(crate) fn mark_plugin_status_unavailable(&self, plugin_name: &str, generation: u64) { + let changed = self + .plugin_status_store() + .mark_unavailable(plugin_name, generation); + if changed { + self.shared.subscriptions.publish(RuntimeDataDirty::STATUS); + } + } + + /// The plugin stopped for good: its snapshot goes. + pub(crate) fn remove_plugin_status(&self, plugin_name: &str) { + let changed = self.plugin_status_store().remove(plugin_name); + if changed { + self.shared.subscriptions.publish(RuntimeDataDirty::STATUS); + } + } + + pub(crate) fn plugin_status_payloads( + &self, + ) -> BTreeMap { + self.plugin_status_store() + .payloads(tokio::time::Instant::now()) + } + + fn plugin_status_store(&self) -> std::sync::MutexGuard<'_, PluginStatusStore> { + self.shared + .plugin_status + .lock() + .expect("runtime data plugin status lock poisoned") + } + + /// Mark status dirty once `after` has passed, so `/api/events` sends the + /// snapshot turning stale. Holds the collector weakly. + fn wake_status_after(&self, after: std::time::Duration) -> Option { + let runtime = tokio::runtime::Handle::try_current().ok()?; + let shared = Arc::downgrade(&self.shared); + let task = runtime.spawn(async move { + tokio::time::sleep(after).await; + if let Some(shared) = shared.upgrade() { + shared.subscriptions.publish(RuntimeDataDirty::STATUS); + } + }); + Some(task.abort_handle()) + } + pub(crate) fn build_hardware_view(&self, input: HardwareViewInput) -> HardwareViewSnapshot { HardwareViewSnapshot { my_hostname: input.my_hostname, diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/mod.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/mod.rs index e940187de8..6cde31bb0f 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/mod.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/mod.rs @@ -9,6 +9,7 @@ mod event_cutover; mod inventory; use mesh_llm_control_api::status::metrics; mod model_labels; +mod plugin_status; #[cfg(test)] mod plugin_tests; mod plugins; @@ -496,6 +497,7 @@ pub(crate) mod tests { recent_mesh_rejections: vec![], plugin_frame_telemetry: PluginFrameTelemetryPayload::default(), logging: None, + plugin_status: Default::default(), }; assert_eq!( diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime_data/plugin_status.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/plugin_status.rs new file mode 100644 index 0000000000..6d471fcef5 --- /dev/null +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime_data/plugin_status.rs @@ -0,0 +1,426 @@ +//! Plugin contributions to `GET /api/status`. +//! +//! The node's collector keeps each plugin's latest accepted snapshot, so a +//! status read never reaches a plugin. The host owns the envelope around the +//! plugin's data: receipt time, freshness and availability. Limits and the +//! wire contract are in `mesh_llm_plugin::plugin_status`. + +use crate::api::status::{PluginStatusPayload, PluginStatusState}; +use crate::plugin::proto; +use mesh_llm_plugin::plugin_status::{MAX_DATA_BYTES, MIN_PUBLISH_INTERVAL, effective_fresh_for}; +use std::collections::BTreeMap; +use std::time::Duration; +use tokio::task::AbortHandle; +use tokio::time::Instant; + +/// Why the host refused a snapshot. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum PluginStatusRejection { + TooLarge { bytes: usize }, + NotAnObject, + TooSoon { retry_after: Duration }, +} + +impl PluginStatusRejection { + pub(crate) fn message(&self, plugin_name: &str) -> String { + match self { + Self::TooLarge { bytes } => format!( + "status data from plugin `{plugin_name}` is {bytes} bytes; the limit is {MAX_DATA_BYTES}" + ), + Self::NotAnObject => { + format!("status data from plugin `{plugin_name}` must be a JSON object") + } + Self::TooSoon { retry_after } => format!( + "plugin `{plugin_name}` published its status less than {MIN_PUBLISH_INTERVAL:?} ago; retry in {retry_after:?}" + ), + } + } +} + +struct PluginStatusEntry { + /// The plugin connection that published it. + generation: u64, + schema_version: u32, + data: serde_json::Value, + received_at: Instant, + received_at_unix_ms: u64, + fresh_for: Duration, + /// False once that connection is gone. + connected: bool, + /// Wakes `/api/events` when the snapshot turns stale. + expiry: Option, +} + +impl PluginStatusEntry { + fn state(&self, now: Instant) -> PluginStatusState { + if !self.connected { + PluginStatusState::Unavailable + } else if now.saturating_duration_since(self.received_at) >= self.fresh_for { + PluginStatusState::Stale + } else { + PluginStatusState::Ready + } + } + + fn fresh_until_unix_ms(&self) -> u64 { + self.received_at_unix_ms + .saturating_add(u64::try_from(self.fresh_for.as_millis()).unwrap_or(u64::MAX)) + } + + fn cancel_expiry(&mut self) { + if let Some(expiry) = self.expiry.take() { + expiry.abort(); + } + } +} + +impl Drop for PluginStatusEntry { + fn drop(&mut self) { + self.cancel_expiry(); + } +} + +/// A snapshot the host accepted. +pub(crate) struct AcceptedPluginStatus { + pub(crate) response: proto::PublishPluginStatusResponse, + /// When it turns stale, for the expiry wake-up. `None` after a withdrawal. + pub(crate) fresh_for: Option, +} + +#[derive(Default)] +pub(crate) struct PluginStatusStore { + entries: BTreeMap, +} + +impl PluginStatusStore { + /// Accept `request` from connection `generation` of `plugin_name`, which + /// the caller has checked is the plugin's current, initialized connection + /// and declares `schema_version`. An empty `data_json` withdraws. + pub(crate) fn publish( + &mut self, + plugin_name: &str, + generation: u64, + schema_version: u32, + request: &proto::PublishPluginStatusRequest, + now: Instant, + now_unix_ms: u64, + ) -> Result { + if request.data_json.is_empty() { + self.entries.remove(plugin_name); + return Ok(AcceptedPluginStatus { + response: proto::PublishPluginStatusResponse::default(), + fresh_for: None, + }); + } + if request.data_json.len() > MAX_DATA_BYTES { + return Err(PluginStatusRejection::TooLarge { + bytes: request.data_json.len(), + }); + } + if let Some(previous) = self.entries.get(plugin_name) + && previous.generation == generation + { + let elapsed = now.saturating_duration_since(previous.received_at); + if elapsed < MIN_PUBLISH_INTERVAL { + return Err(PluginStatusRejection::TooSoon { + retry_after: MIN_PUBLISH_INTERVAL - elapsed, + }); + } + } + let data = match serde_json::from_str::(&request.data_json) { + Ok(data @ serde_json::Value::Object(_)) => data, + _ => return Err(PluginStatusRejection::NotAnObject), + }; + let entry = PluginStatusEntry { + generation, + schema_version, + data, + received_at: now, + received_at_unix_ms: now_unix_ms, + fresh_for: effective_fresh_for(request.fresh_for_ms), + connected: true, + expiry: None, + }; + let accepted = AcceptedPluginStatus { + response: proto::PublishPluginStatusResponse { + received_at_unix_ms: entry.received_at_unix_ms, + fresh_until_unix_ms: entry.fresh_until_unix_ms(), + }, + fresh_for: Some(entry.fresh_for), + }; + self.entries.insert(plugin_name.to_string(), entry); + Ok(accepted) + } + + /// Attach the wake-up that fires when `plugin_name`'s snapshot turns stale. + pub(crate) fn set_expiry(&mut self, plugin_name: &str, expiry: AbortHandle) { + match self.entries.get_mut(plugin_name) { + Some(entry) => { + entry.cancel_expiry(); + entry.expiry = Some(expiry); + } + None => expiry.abort(), + } + } + + /// The connection `generation` of `plugin_name` is gone: keep what it + /// published, shown as unavailable. A snapshot from a later connection is + /// left alone. Returns whether anything changed. + pub(crate) fn mark_unavailable(&mut self, plugin_name: &str, generation: u64) -> bool { + match self.entries.get_mut(plugin_name) { + Some(entry) if entry.generation == generation && entry.connected => { + entry.connected = false; + entry.cancel_expiry(); + true + } + _ => false, + } + } + + /// The plugin stopped for good. Returns whether it had a snapshot. + pub(crate) fn remove(&mut self, plugin_name: &str) -> bool { + self.entries.remove(plugin_name).is_some() + } + + pub(crate) fn payloads(&self, now: Instant) -> BTreeMap { + self.entries + .iter() + .map(|(name, entry)| { + ( + name.clone(), + PluginStatusPayload { + schema_version: entry.schema_version, + state: entry.state(now), + received_at_unix_ms: entry.received_at_unix_ms, + fresh_until_unix_ms: entry.fresh_until_unix_ms(), + data: entry.data.clone(), + }, + ) + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use mesh_llm_plugin::plugin_status::{DEFAULT_FRESH_FOR, MAX_FRESH_FOR}; + + fn request(data_json: &str, fresh_for_ms: u64) -> proto::PublishPluginStatusRequest { + proto::PublishPluginStatusRequest { + data_json: data_json.into(), + fresh_for_ms, + } + } + + #[test] + fn a_snapshot_is_ready_then_stale_inside_a_host_owned_envelope() { + let mut store = PluginStatusStore::default(); + let start = Instant::now(); + let accepted = store + .publish( + "powermetrics", + 1, + 3, + &request(r#"{"idle_watts":8.2}"#, 5_000), + start, + 1_000, + ) + .unwrap(); + assert_eq!(accepted.response.received_at_unix_ms, 1_000); + assert_eq!(accepted.response.fresh_until_unix_ms, 6_000); + assert_eq!(accepted.fresh_for, Some(Duration::from_secs(5))); + + let ready = &store.payloads(start + Duration::from_secs(4))["powermetrics"]; + assert_eq!(ready.state, PluginStatusState::Ready); + assert_eq!(ready.schema_version, 3); + assert_eq!(ready.data, serde_json::json!({"idle_watts": 8.2})); + assert_eq!( + store.payloads(start + Duration::from_secs(5))["powermetrics"].state, + PluginStatusState::Stale + ); + } + + #[test] + fn two_plugins_keep_their_own_snapshots() { + let mut store = PluginStatusStore::default(); + let now = Instant::now(); + store + .publish("a", 1, 1, &request(r#"{"from":"a"}"#, 0), now, 1) + .unwrap(); + store + .publish("b", 1, 1, &request(r#"{"from":"b"}"#, 0), now, 1) + .unwrap(); + store + .publish( + "a", + 1, + 1, + &request(r#"{"from":"a again"}"#, 0), + now + MIN_PUBLISH_INTERVAL, + 2, + ) + .unwrap(); + let payloads = store.payloads(now + MIN_PUBLISH_INTERVAL); + assert_eq!(payloads["a"].data, serde_json::json!({"from": "a again"})); + assert_eq!(payloads["b"].data, serde_json::json!({"from": "b"})); + assert_eq!( + payloads["b"].fresh_until_unix_ms, + 1 + DEFAULT_FRESH_FOR.as_millis() as u64 + ); + } + + #[test] + fn malformed_oversized_and_too_frequent_snapshots_are_refused() { + let mut store = PluginStatusStore::default(); + let now = Instant::now(); + for not_an_object in ["{", "[1]", "8.2", "\"text\"", "null"] { + assert_eq!( + store + .publish("p", 1, 1, &request(not_an_object, 0), now, 1) + .err(), + Some(PluginStatusRejection::NotAnObject), + "{not_an_object}" + ); + } + let oversized = format!(r#"{{"pad":"{}"}}"#, "x".repeat(MAX_DATA_BYTES)); + assert_eq!( + store + .publish("p", 1, 1, &request(&oversized, 0), now, 1) + .err(), + Some(PluginStatusRejection::TooLarge { + bytes: oversized.len() + }) + ); + assert!(store.payloads(now).is_empty(), "nothing was stored"); + + store + .publish("p", 1, 1, &request(r#"{"n":1}"#, 0), now, 1) + .unwrap(); + let half = MIN_PUBLISH_INTERVAL / 2; + assert_eq!( + store + .publish("p", 1, 1, &request(r#"{"n":2}"#, 0), now + half, 2) + .err(), + Some(PluginStatusRejection::TooSoon { + retry_after: MIN_PUBLISH_INTERVAL - half + }) + ); + assert_eq!(store.payloads(now)["p"].data, serde_json::json!({"n": 1})); + // A new connection's first snapshot is not held to the old one's pace. + store + .publish("p", 2, 1, &request(r#"{"n":3}"#, 0), now + half, 3) + .unwrap(); + assert_eq!(store.payloads(now)["p"].data, serde_json::json!({"n": 3})); + } + + #[test] + fn freshness_is_kept_within_the_host_bounds() { + let mut store = PluginStatusStore::default(); + let accepted = store + .publish("p", 1, 1, &request("{}", u64::MAX), Instant::now(), 0) + .unwrap(); + assert_eq!(accepted.fresh_for, Some(MAX_FRESH_FOR)); + assert_eq!( + accepted.response.fresh_until_unix_ms, + MAX_FRESH_FOR.as_millis() as u64 + ); + } + + #[test] + fn a_closed_connection_leaves_its_snapshot_unavailable_but_not_a_later_one() { + let mut store = PluginStatusStore::default(); + let now = Instant::now(); + store + .publish("p", 1, 1, &request(r#"{"n":1}"#, 0), now, 1) + .unwrap(); + assert!(store.mark_unavailable("p", 1)); + assert!(!store.mark_unavailable("p", 1), "already unavailable"); + let unavailable = &store.payloads(now)["p"]; + assert_eq!(unavailable.state, PluginStatusState::Unavailable); + assert_eq!(unavailable.data, serde_json::json!({"n": 1})); + + // The restarted plugin publishes again; a late notice about the old + // connection does not touch it. + store + .publish("p", 2, 1, &request(r#"{"n":2}"#, 0), now, 2) + .unwrap(); + assert!(!store.mark_unavailable("p", 1)); + assert_eq!(store.payloads(now)["p"].state, PluginStatusState::Ready); + assert!( + !store.mark_unavailable("q", 1), + "no snapshot, nothing to mark" + ); + } + + #[tokio::test(start_paused = true)] + async fn the_collector_wakes_status_readers_when_a_snapshot_turns_stale() { + use crate::runtime_data::{RuntimeDataCollector, RuntimeDataDirty}; + + let collector = RuntimeDataCollector::new(); + let mut subscription = collector.subscribe(); + collector + .publish_plugin_status("p", 1, 1, &request("{}", 2_000)) + .unwrap(); + assert!( + subscription.has_changed().unwrap(), + "a publication wakes readers" + ); + subscription.borrow_and_update(); + assert_eq!( + collector.plugin_status_payloads()["p"].state, + PluginStatusState::Ready + ); + + // A newer snapshot replaces the old one's wake-up with its own. + tokio::time::sleep(Duration::from_secs(1)).await; + collector + .publish_plugin_status("p", 1, 1, &request("{}", 5_000)) + .unwrap(); + subscription.borrow_and_update(); + tokio::time::sleep(Duration::from_millis(4_999)).await; + assert!( + !subscription.has_changed().unwrap(), + "the replaced snapshot's expiry does not fire" + ); + assert_eq!( + collector.plugin_status_payloads()["p"].state, + PluginStatusState::Ready + ); + + tokio::time::timeout(Duration::from_secs(1), subscription.changed()) + .await + .expect("readers are woken when the snapshot turns stale") + .unwrap(); + assert!( + subscription + .borrow() + .dirty + .contains(RuntimeDataDirty::STATUS) + ); + assert_eq!( + collector.plugin_status_payloads()["p"].state, + PluginStatusState::Stale + ); + } + + #[test] + fn a_withdrawal_or_a_stop_removes_the_snapshot() { + let mut store = PluginStatusStore::default(); + let now = Instant::now(); + store.publish("p", 1, 1, &request("{}", 0), now, 1).unwrap(); + // Withdrawing is not held to the publication pace. + let withdrawn = store.publish("p", 1, 1, &request("", 0), now, 1).unwrap(); + assert_eq!( + withdrawn.response, + proto::PublishPluginStatusResponse::default() + ); + assert_eq!(withdrawn.fresh_for, None); + assert!(store.payloads(now).is_empty()); + + store.publish("p", 2, 1, &request("{}", 0), now, 1).unwrap(); + assert!(store.remove("p")); + assert!(!store.remove("p")); + assert!(store.payloads(now).is_empty()); + } +} diff --git a/mesh/crates/mesh-llm-plugin-manager/src/defaults.rs b/mesh/crates/mesh-llm-plugin-manager/src/defaults.rs index 37098ca1f9..7540b9ff10 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/defaults.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/defaults.rs @@ -59,6 +59,8 @@ pub enum Surface { /// The OpenAI exchange lifecycle hook: it sees every OpenAI exchange the /// node handles, prompts and answers included. OpenAiExchangeHook, + /// The plugin's own snapshot, shown in `GET /api/status`. + StatusContributions, } impl Surface { @@ -74,6 +76,7 @@ impl Surface { Self::OtherEndpoints => "other endpoints", Self::VirtualModels => "virtual models", Self::OpenAiExchangeHook => "OpenAI exchange hook", + Self::StatusContributions => "status contributions", } } } @@ -88,6 +91,7 @@ pub const UNLISTED_DEFAULT_ALLOWS: &[Surface] = &[ Surface::HttpRoutes, Surface::McpOperations, Surface::OtherEndpoints, + Surface::StatusContributions, ]; /// This build's entry for a default plugin, by its installed name. diff --git a/mesh/crates/mesh-llm-plugin/proto/plugin.proto b/mesh/crates/mesh-llm-plugin/proto/plugin.proto index 86fda434fb..c6d3360d48 100644 --- a/mesh/crates/mesh-llm-plugin/proto/plugin.proto +++ b/mesh/crates/mesh-llm-plugin/proto/plugin.proto @@ -34,6 +34,8 @@ message Envelope { PeerBlockResponse peer_block_response = 33; PluginKeyRequest plugin_key_request = 34; PluginKeyResponse plugin_key_response = 35; + PublishPluginStatusRequest publish_plugin_status_request = 36; + PublishPluginStatusResponse publish_plugin_status_response = 37; } } @@ -199,6 +201,19 @@ message PluginManifest { repeated VirtualModelManifest virtual_models = 13; // Optional, additive generation-3 lifecycle contract. Declarations are not grants. optional OpenAiExchangeHookManifest openai_exchange_hook = 14; + // This plugin publishes a snapshot shown in `GET /api/status`; see + // `PublishPluginStatusRequest`. A host takes publications only from a plugin + // that declares this. + optional PluginStatusManifest plugin_status = 15; +} + +message PluginStatusManifest { + // The version of the plugin's own snapshot schema, shown beside its data. + // At least 1. + uint32 schema_version = 1; + // Refuse to initialize on a host that does not list the `plugin_status.v1` + // capability, instead of running without a status contribution. + bool required = 2; } message VirtualModelManifest { @@ -743,6 +758,29 @@ message PluginKeyResponse { bytes binding_signature = 2; } +// A plugin publishes the snapshot that `GET /api/status` shows under +// `plugins.`, where `` is the host's name for the plugin +// connection, never a name the plugin claims. A later publication replaces it, and an empty `data_json` +// withdraws it. The host keeps the latest one and owns its envelope: receipt +// time and freshness. `/api/status` reads that copy and never calls the +// plugin. Handled only by a host listing the `plugin_status.v1` capability, +// for a plugin whose manifest declares `plugin_status`, from its current +// connection. +message PublishPluginStatusRequest { + // A JSON object, at most 16 KiB, in the plugin's own schema. Empty to withdraw. + string data_json = 1; + // How long the host shows the snapshot as `ready` before it turns `stale`. + // 0 means 60 s; the host keeps it between 1 s and 1 h. + uint64 fresh_for_ms = 2; +} + +message PublishPluginStatusResponse { + // When the host accepted the snapshot, Unix milliseconds; 0 after a withdrawal. + uint64 received_at_unix_ms = 1; + // When it turns `stale`, Unix milliseconds; 0 after a withdrawal. + uint64 fresh_until_unix_ms = 2; +} + message ErrorResponse { int32 code = 1; string message = 2; diff --git a/mesh/crates/mesh-llm-plugin/src/context.rs b/mesh/crates/mesh-llm-plugin/src/context.rs index 168a17b7de..95123d2384 100644 --- a/mesh/crates/mesh-llm-plugin/src/context.rs +++ b/mesh/crates/mesh-llm-plugin/src/context.rs @@ -332,6 +332,75 @@ impl<'a> PluginContext<'a> { } } + /// Publish `data`, a JSON object of at most + /// [`crate::plugin_status::MAX_DATA_BYTES`], as this plugin's snapshot in + /// `GET /api/status`; it replaces the previous one. The host shows it as + /// `ready` for `fresh_for` (0 for the default), then `stale`. See + /// [`crate::plugin_status`]. + /// + /// Fails at once, without sending anything, if the host does not list + /// [`crate::host_capabilities::PLUGIN_STATUS`]. The host refuses a snapshot + /// from a plugin whose manifest does not declare `plugin_status`, one that + /// is too large or not an object, and one sent sooner than + /// [`crate::plugin_status::MIN_PUBLISH_INTERVAL`] after the last. + pub async fn publish_status( + &mut self, + data: &T, + fresh_for: std::time::Duration, + ) -> Result { + let request = proto::PublishPluginStatusRequest { + data_json: serde_json::to_string(data)?, + fresh_for_ms: u64::try_from(fresh_for.as_millis()).unwrap_or(u64::MAX), + }; + self.publish_status_within(request, PEER_BLOCK_REQUEST_TIMEOUT) + .await + } + + /// Remove this plugin's snapshot from `GET /api/status`. + pub async fn withdraw_status(&mut self) -> Result<()> { + self.publish_status_within( + proto::PublishPluginStatusRequest::default(), + PEER_BLOCK_REQUEST_TIMEOUT, + ) + .await + .map(|_| ()) + } + + async fn publish_status_within( + &mut self, + request: proto::PublishPluginStatusRequest, + timeout: std::time::Duration, + ) -> Result { + if !self.host_supports(crate::host_capabilities::PLUGIN_STATUS) { + bail!( + "status contributions are unsupported by this host: it does not list the `{}` capability", + crate::host_capabilities::PLUGIN_STATUS + ); + } + let request_id = next_host_request_id(); + let (tx, rx) = oneshot::channel(); + insert_pending_host_response(&self.pending_host_responses, request_id, tx); + let mut pending_guard = + PendingHostResponseGuard::new(request_id, self.pending_host_responses.clone()); + + self.send_payload( + proto::envelope::Payload::PublishPluginStatusRequest(request), + request_id, + ) + .await?; + + let Ok(response) = tokio::time::timeout(timeout, rx).await else { + bail!("status publication: the host did not answer within {timeout:?}"); + }; + let response = response??; + pending_guard.disarm(); + match response.payload { + Some(proto::envelope::Payload::PublishPluginStatusResponse(response)) => Ok(response), + Some(proto::envelope::Payload::ErrorResponse(error)) => bail!(error.message), + _ => bail!("Host returned an unexpected status publication response"), + } + } + pub async fn connect_mesh_stream( &mut self, request: proto::OpenMeshStreamRequest, @@ -404,6 +473,7 @@ pub(crate) fn drain_pending_host_responses( #[cfg(test)] mod tests { use super::*; + use std::time::Duration; fn context( host_capabilities: &[&str], @@ -538,4 +608,99 @@ mod tests { assert_eq!(response.binding_signature, vec![2; 64]); host.await.unwrap(); } + + #[tokio::test] + async fn a_status_publication_to_an_older_host_fails_at_once() { + let (mut context, mut outbound_rx, pending) = context(&[]); + let error = context + .publish_status(&serde_json::json!({"watts": 8.2}), Duration::ZERO) + .await + .unwrap_err(); + assert!( + error.to_string().contains("unsupported by this host"), + "{error}" + ); + assert!(outbound_rx.try_recv().is_err(), "nothing was sent"); + assert!(pending.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn a_status_publication_the_host_never_answers_times_out() { + let (mut context, mut outbound_rx, pending) = + context(&[crate::host_capabilities::PLUGIN_STATUS]); + let error = context + .publish_status_within( + proto::PublishPluginStatusRequest { + data_json: "{}".into(), + fresh_for_ms: 0, + }, + Duration::from_millis(20), + ) + .await + .unwrap_err(); + assert!(error.to_string().contains("did not answer"), "{error}"); + assert!(outbound_rx.try_recv().is_ok(), "the publication was sent"); + assert!(pending.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn a_status_publication_sends_the_data_and_returns_the_host_answer() { + let (mut context, mut outbound_rx, pending) = + context(&[crate::host_capabilities::PLUGIN_STATUS]); + let host = tokio::spawn(async move { + let request = outbound_rx.recv().await.unwrap(); + let Some(proto::envelope::Payload::PublishPluginStatusRequest(publication)) = + request.payload + else { + panic!("expected a status publication"); + }; + assert_eq!(publication.data_json, r#"{"watts":8.2}"#); + assert_eq!(publication.fresh_for_ms, 5_000); + let sender = remove_pending_host_response(&pending, request.request_id).unwrap(); + sender + .send(Ok(proto::Envelope { + request_id: request.request_id, + payload: Some(proto::envelope::Payload::PublishPluginStatusResponse( + proto::PublishPluginStatusResponse { + received_at_unix_ms: 1_000, + fresh_until_unix_ms: 6_000, + }, + )), + ..Default::default() + })) + .unwrap(); + }); + let response = context + .publish_status(&serde_json::json!({"watts": 8.2}), Duration::from_secs(5)) + .await + .unwrap(); + assert_eq!(response.fresh_until_unix_ms, 6_000); + host.await.unwrap(); + } + + #[tokio::test] + async fn a_withdrawal_sends_empty_data() { + let (mut context, mut outbound_rx, pending) = + context(&[crate::host_capabilities::PLUGIN_STATUS]); + let host = tokio::spawn(async move { + let request = outbound_rx.recv().await.unwrap(); + assert!(matches!( + request.payload, + Some(proto::envelope::Payload::PublishPluginStatusRequest(ref publication)) + if publication.data_json.is_empty() + )); + let sender = remove_pending_host_response(&pending, request.request_id).unwrap(); + sender + .send(Ok(proto::Envelope { + request_id: request.request_id, + payload: Some(proto::envelope::Payload::PublishPluginStatusResponse( + proto::PublishPluginStatusResponse::default(), + )), + ..Default::default() + })) + .unwrap(); + }); + context.withdraw_status().await.unwrap(); + host.await.unwrap(); + } } diff --git a/mesh/crates/mesh-llm-plugin/src/lib.rs b/mesh/crates/mesh-llm-plugin/src/lib.rs index 4a6e498f2a..e845c1c004 100644 --- a/mesh/crates/mesh-llm-plugin/src/lib.rs +++ b/mesh/crates/mesh-llm-plugin/src/lib.rs @@ -11,6 +11,7 @@ mod internal_rpc; mod io; mod manifest; pub mod openai_exchange; +pub mod plugin_status; mod runtime; mod simple_plugin; mod virtual_model; @@ -106,6 +107,35 @@ pub mod host_capabilities { pub const PEER_BLOCKS: &str = "peer_blocks.v1"; /// The host accepts `PluginKeyRequest` and announces the key it binds. pub const PLUGIN_KEYS: &str = "plugin_keys.v1"; + /// The host accepts `PublishPluginStatusRequest` and shows the snapshot in + /// `GET /api/status` (see [`crate::plugin_status`]). + pub const PLUGIN_STATUS: &str = "plugin_status.v1"; + + /// Why a plugin with `manifest` cannot run on this host: a capability its + /// manifest requires that the host does not list. + pub(crate) fn unsupported_requirement( + manifest: Option<&crate::proto::PluginManifest>, + host_supports: impl Fn(&str) -> bool, + ) -> Option<&'static str> { + let manifest = manifest?; + if manifest + .openai_exchange_hook + .as_ref() + .is_some_and(|hook| hook.required) + && !host_supports(OPENAI_EXCHANGE) + { + return Some("host does not support required openai_exchange.v1 contract"); + } + if manifest + .plugin_status + .as_ref() + .is_some_and(|status| status.required) + && !host_supports(PLUGIN_STATUS) + { + return Some("host does not support required plugin_status.v1 contributions"); + } + None + } } #[macro_export] diff --git a/mesh/crates/mesh-llm-plugin/src/manifest.rs b/mesh/crates/mesh-llm-plugin/src/manifest.rs index 68858f0421..bae079e1bc 100644 --- a/mesh/crates/mesh-llm-plugin/src/manifest.rs +++ b/mesh/crates/mesh-llm-plugin/src/manifest.rs @@ -39,6 +39,7 @@ pub enum ManifestEntry { MeshEventSubscription(proto::MeshEventSubscriptionManifest), WebUi(proto::PluginWebUiManifest), OpenAiExchangeHook(proto::OpenAiExchangeHookManifest), + PluginStatus(proto::PluginStatusManifest), } #[derive(Clone, Debug, Default)] @@ -88,6 +89,7 @@ impl PluginManifestBuilder { ManifestEntry::OpenAiExchangeHook(hook) => { self.manifest.openai_exchange_hook = Some(Box::new(hook)) } + ManifestEntry::PluginStatus(status) => self.manifest.plugin_status = Some(status), } } } diff --git a/mesh/crates/mesh-llm-plugin/src/plugin_status.rs b/mesh/crates/mesh-llm-plugin/src/plugin_status.rs new file mode 100644 index 0000000000..9f557a10d5 --- /dev/null +++ b/mesh/crates/mesh-llm-plugin/src/plugin_status.rs @@ -0,0 +1,197 @@ +//! Plugin contributions to the host's `GET /api/status`. +//! +//! A plugin declares [`plugin_status`] in its manifest and publishes snapshots +//! with [`crate::PluginContext::publish_status`]. The host keeps the latest one +//! and shows it in `GET /api/status` under `plugins.`, inside an +//! envelope the host owns: +//! +//! ```json +//! { +//! "schema_version": 1, +//! "state": "ready", +//! "received_at_unix_ms": 1793404800000, +//! "fresh_until_unix_ms": 1793404860000, +//! "data": { "source": "macmon", "idle_watts": 8.2 } +//! } +//! ``` +//! +//! `state` is `ready` until the snapshot's freshness runs out, then `stale`, +//! and `unavailable` once the plugin connection that published it is gone. The +//! freshness is the host's: it says when the host last heard from the plugin, +//! not how old the plugin's own readings are, which belong in `data`. + +use crate::manifest::ManifestEntry; +use crate::proto; +use std::time::Duration; + +/// The largest `data_json` a host accepts, in bytes. +pub const MAX_DATA_BYTES: usize = 16 * 1024; +/// The shortest interval between two snapshots a host accepts from one plugin +/// connection. A withdrawal is always accepted. +pub const MIN_PUBLISH_INTERVAL: Duration = Duration::from_secs(1); +/// How long a snapshot stays `ready` when it sets `fresh_for_ms` to 0. +pub const DEFAULT_FRESH_FOR: Duration = Duration::from_secs(60); +/// The shortest freshness a host keeps; a shorter one is raised to it. +pub const MIN_FRESH_FOR: Duration = Duration::from_secs(1); +/// The longest freshness a host keeps; a longer one is lowered to it. +pub const MAX_FRESH_FOR: Duration = Duration::from_secs(60 * 60); + +/// Declare that this plugin publishes snapshots in version `schema_version` +/// (at least 1) of its own schema. +pub fn plugin_status(schema_version: u32) -> PluginStatusBuilder { + PluginStatusBuilder { + inner: proto::PluginStatusManifest { + schema_version, + required: false, + }, + } +} + +#[derive(Clone, Debug)] +pub struct PluginStatusBuilder { + inner: proto::PluginStatusManifest, +} + +impl PluginStatusBuilder { + /// Refuse to initialize on a host that does not list + /// [`crate::host_capabilities::PLUGIN_STATUS`]. + pub fn required(mut self, required: bool) -> Self { + self.inner.required = required; + self + } + + pub fn build(self) -> proto::PluginStatusManifest { + self.inner + } +} + +impl From for ManifestEntry { + fn from(value: PluginStatusBuilder) -> Self { + ManifestEntry::PluginStatus(value.build()) + } +} + +/// How long the host keeps a snapshot published with `fresh_for_ms` as +/// `ready`. +pub fn effective_fresh_for(fresh_for_ms: u64) -> Duration { + if fresh_for_ms == 0 { + return DEFAULT_FRESH_FOR; + } + Duration::from_millis(fresh_for_ms).clamp(MIN_FRESH_FOR, MAX_FRESH_FOR) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + LocalStream, PROTOCOL_VERSION, PluginMetadata, PluginRuntime, SimplePlugin, + plugin_server_info, read_envelope, write_envelope, + }; + + #[test] + fn freshness_defaults_to_a_minute_and_stays_between_a_second_and_an_hour() { + assert_eq!(effective_fresh_for(0), DEFAULT_FRESH_FOR); + assert_eq!(effective_fresh_for(1), MIN_FRESH_FOR); + assert_eq!(effective_fresh_for(5_000), Duration::from_secs(5)); + assert_eq!(effective_fresh_for(u64::MAX), MAX_FRESH_FOR); + } + + #[test] + fn the_declaration_lands_in_the_manifest() { + let manifest = crate::plugin_manifest() + .item(plugin_status(2).required(true)) + .build(); + assert_eq!( + manifest.plugin_status, + Some(proto::PluginStatusManifest { + schema_version: 2, + required: true, + }) + ); + } + + async fn initialize_status_plugin( + required: bool, + host_capabilities: Vec, + ) -> Option { + let plugin = SimplePlugin::new(PluginMetadata::new( + "demo", + "1.0.0", + plugin_server_info("demo", "1.0.0", "Demo", "Demo plugin", None::), + )) + .with_manifest( + crate::plugin_manifest() + .item(crate::plugin_status::plugin_status(1).required(required)) + .build(), + ); + let (plugin_stream, host_stream) = tokio::io::duplex(64 * 1024); + let runtime = tokio::spawn(PluginRuntime::run_with_stream( + plugin, + LocalStream::Memory(plugin_stream), + )); + let mut host_stream = LocalStream::Memory(host_stream); + write_envelope( + &mut host_stream, + &proto::Envelope { + protocol_version: PROTOCOL_VERSION, + plugin_id: "demo".into(), + request_id: 1, + payload: Some(proto::envelope::Payload::InitializeRequest( + proto::InitializeRequest { + host_protocol_version: PROTOCOL_VERSION, + host_capabilities, + ..Default::default() + }, + )), + }, + ) + .await + .unwrap(); + let response = + tokio::time::timeout(Duration::from_secs(1), read_envelope(&mut host_stream)) + .await + .expect("initialize response") + .unwrap(); + runtime.abort(); + response.payload + } + + #[tokio::test] + async fn a_required_status_contribution_refuses_a_host_without_it() { + let payload = initialize_status_plugin(true, Vec::new()).await; + let Some(proto::envelope::Payload::ErrorResponse(error)) = payload else { + panic!("expected an initialize error, got {payload:?}"); + }; + assert!( + error.message.contains("plugin_status.v1"), + "{}", + error.message + ); + + let payload = + initialize_status_plugin(true, vec![crate::host_capabilities::PLUGIN_STATUS.into()]) + .await; + let Some(proto::envelope::Payload::InitializeResponse(init)) = payload else { + panic!("expected an initialize response, got {payload:?}"); + }; + assert_eq!( + init.manifest.and_then(|manifest| manifest.plugin_status), + Some(proto::PluginStatusManifest { + schema_version: 1, + required: true, + }) + ); + } + + #[tokio::test] + async fn an_optional_status_contribution_initializes_on_an_older_host() { + let payload = initialize_status_plugin(false, Vec::new()).await; + assert!( + matches!( + payload, + Some(proto::envelope::Payload::InitializeResponse(_)) + ), + "{payload:?}" + ); + } +} diff --git a/mesh/crates/mesh-llm-plugin/src/runtime.rs b/mesh/crates/mesh-llm-plugin/src/runtime.rs index f34e6ff6f2..fb3d1f7b30 100644 --- a/mesh/crates/mesh-llm-plugin/src/runtime.rs +++ b/mesh/crates/mesh-llm-plugin/src/runtime.rs @@ -1017,20 +1017,15 @@ impl PluginRuntime { Arc::from(request.host_capabilities.clone()); let mut plugin = state.plugin.clone().write_owned().await; let mut context = Self::context(&state); - if plugin - .manifest() - .and_then(|m| m.openai_exchange_hook) - .is_some_and(|h| h.required) - && !context.host_supports(crate::host_capabilities::OPENAI_EXCHANGE) - { + if let Some(message) = crate::host_capabilities::unsupported_requirement( + plugin.manifest().as_ref(), + |capability| context.host_supports(capability), + ) { Self::write_payload( &state, request_id, proto::envelope::Payload::ErrorResponse( - PluginError::invalid_request( - "host does not support required openai_exchange.v1 contract", - ) - .into_error_response(), + PluginError::invalid_request(message).into_error_response(), ), ) .await?; diff --git a/mesh/docs/plugins/README.md b/mesh/docs/plugins/README.md index 239fcaa681..e35a0ffb92 100644 --- a/mesh/docs/plugins/README.md +++ b/mesh/docs/plugins/README.md @@ -1389,6 +1389,62 @@ Every change is published once, as JSON, on the local channel `until_ms` and `reason` are omitted when absent. The host keeps no ranking, no history of changes, and no shared lists. +## Status Contributions + +A plugin can add a snapshot of its own to the node's `GET /api/status`, so +clients see it without querying a plugin endpoint. It declares +`mesh_llm_plugin::plugin_status::plugin_status(schema_version)` in its manifest +(`PluginManifest.plugin_status`), then publishes with +`PluginContext::publish_status(&data, fresh_for)`, from `on_initialized` or any +task holding an owned context. Each publication replaces the previous one; +`withdraw_status` removes it. The host shows the latest one under the name it +knows the plugin connection by, never a name the plugin claims, so one plugin +cannot overwrite another's contribution or a core field: + +```json +"plugins": { + "powermetrics": { + "schema_version": 1, + "state": "ready", + "received_at_unix_ms": 1793404800000, + "fresh_until_unix_ms": 1793404860000, + "data": { "source": "macmon", "idle_watts": 8.2 } + } +} +``` + +`data` is the plugin's, in version `schema_version` of its own schema. The rest +is the host's: + +- `state` is `ready` until `fresh_until_unix_ms`, then `stale`. A snapshot asks + for its freshness with `fresh_for`: 0 means 60 s, and the host keeps it + between 1 s and 1 h. When the plugin connection that published it closes or + fails, the snapshot stays, shown as `unavailable`, until a later connection + publishes. When the plugin is disabled, removed or shut down, it goes. +- The timestamps say when the host last heard from the plugin. They say nothing + about how old the plugin's own readings are: a plugin that publishes an old or + missing sensor reading says so in `data`. + +The host refuses a publication from a plugin whose manifest does not declare +`plugin_status`, from a connection that is no longer the plugin's current one, +`data_json` that is not a JSON object or is larger than 16 KiB, and a snapshot +sent less than 1 s after the previous one from the same connection. Refusals +come back as an error and change nothing; a withdrawal is always accepted. A +plugin may publish from `on_initialized`: a publication that arrives before the +host has read the plugin's manifest waits for it. + +Reads serve the host's copy: `/api/status` never starts, restarts or calls a +plugin, so a hung plugin cannot slow it. Every accepted publication, and every +change of state, wakes `/api/events`, which sends the new status. Without any +contribution, `plugins` is omitted and the response is unchanged. It is +local to this node, like the rest of `/api/status`: nothing is gossiped. + +The host advertises the `plugin_status.v1` host capability in its +`InitializeRequest`. Against a host without it, `publish_status` fails at once; +a plugin that cannot run without it declares `.required(true)` and then refuses +to initialize there. A default-managed plugin keeps its declaration only when +its entry in `DEFAULT_PLUGINS` allows `Surface::StatusContributions`. + ## What The Host Owns The host is responsible for: