25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(plugins): coordinate sidecar cleanup across hosts
ezreal041eb78f4bfa
diff --git a/crates/dbx-mcp/src/backend.rs b/crates/dbx-mcp/src/backend.rsindex 9189ae1d18..87528b7827 100644--- a/crates/dbx-mcp/src/backend.rs+++ b/crates/dbx-mcp/src/backend.rs@@ -906,7 +906,7 @@ impl LocalBackend {let tools: Value = match self.state.plugin_host- .invoke(&plugin.manifest.id, "mcp/tools", json!({}), None, Some(std::time::Duration::from_secs(30)))+ .probe(&plugin.manifest.id, "mcp/tools", json!({}), Some(std::time::Duration::from_secs(30))).await{Ok(tools) => tools,@@ -980,14 +980,14 @@ impl LocalBackend {}).map(|plugin| (plugin.manifest.id.clone(), plugin.manifest.name.clone())).collect();- // Probe every candidate's sidecar concurrently; the probes share the- // plugin sidecar sessions, so repeated listings are cheap.+ // Discovery uses short-lived sessions: merely listing tools must not keep every+ // installed plugin loaded in every independent MCP host.let probes = candidates.into_iter().map(|(plugin_id, plugin_name)| {let state = Arc::clone(&self.state);async move {let listing = state.plugin_host- .invoke::<Value>(&plugin_id, "mcp/tools", json!({}), None, Some(PLUGIN_TOOLS_PROBE_TIMEOUT))+ .probe::<Value>(&plugin_id, "mcp/tools", json!({}), Some(PLUGIN_TOOLS_PROBE_TIMEOUT)).await;(plugin_id, plugin_name, listing)}diff --git a/crates/dbx-plugin-runtime/src/plugins.rs b/crates/dbx-plugin-runtime/src/plugins.rsindex 6eca31b329..47a27c29b6 100644--- a/crates/dbx-plugin-runtime/src/plugins.rs+++ b/crates/dbx-plugin-runtime/src/plugins.rs@@ -12,6 +12,8 @@ mod host;mod installer;mod jdbc_sessions;mod lifecycle;+#[cfg(all(test, any(windows, unix)))]+mod lifecycle_tests;mod manifest;mod marketplace;mod runtime;@@ -167,12 +169,8 @@ impl PluginRegistry {}pub fn new_with_app_version(root_dir: PathBuf, app_version: impl Into<String>) -> Self {- Self {- root_dir,- app_version: app_version.into(),- lifecycle: PluginLifecycle::default(),- jdbc_runtimes: Default::default(),- }+ let lifecycle = PluginLifecycle::for_store(&root_dir);+ Self { root_dir, app_version: app_version.into(), lifecycle, jdbc_runtimes: Default::default() }}pub fn lifecycle(&self) -> PluginLifecycle {@@ -329,9 +327,16 @@ impl PluginRegistry {whereT: DeserializeOwned,{+ let _operation = self.lifecycle.begin_operation(&plugin.manifest.id)?;+ // A rollback in another host may have completed between discovery and admission.+ let plugin = self.find_plugin(&plugin.manifest.id)?.ok_or("Plugin is no longer installed")?;ensure_plugin_compatible(&plugin)?;let env = PluginRuntimeEnv::default().with_plugin_data_dir(&self.plugin_data_dir(&plugin.manifest.id));- let session = PluginSidecarSession::start(plugin, self.app_version.clone(), env).await?;+ let runtime_lease = self.lifecycle.runtime_lease(&plugin.manifest.id)?;+ let session =+ PluginSidecarSession::start_with_runtime_lease(plugin, self.app_version.clone(), env, runtime_lease)+ .await?;+ let _cleanup = runtime::ShutdownOnDrop::new(session.clone());let result =session.invoke_with_timeout(method, params, Some(capability_id), Some(PLUGIN_REQUEST_TIMEOUT)).await;match (result, session.shutdown().await) {@@ -386,8 +391,18 @@ impl PluginRegistry {// and makes the whole start -> invoke -> shutdown sequence mutually exclusive with an// install, rollback, or uninstall of the same plugin.let _operation = self.lifecycle.begin_operation(&plugin.manifest.id)?;+ let current = self.find_driver(driver_id)?.ok_or("Plugin driver is no longer installed")?;+ if current.manifest.id != plugin.manifest.id {+ return Err(format!("Plugin driver '{driver_id}' changed. Please reconnect."));+ }+ let plugin = current;+ ensure_plugin_compatible(&plugin)?;let env = env.with_plugin_data_dir(&self.plugin_data_dir(&plugin.manifest.id));- let session = PluginSidecarSession::start(plugin, self.app_version.clone(), env).await?;+ let runtime_lease = self.lifecycle.runtime_lease(&plugin.manifest.id)?;+ let session =+ PluginSidecarSession::start_with_runtime_lease(plugin, self.app_version.clone(), env, runtime_lease)+ .await?;+ let _cleanup = runtime::ShutdownOnDrop::new(session.clone());let result = session.invoke_with_timeout(method, params, Some(driver_id), timeout_duration).await;match (result, session.shutdown().await) {(Ok(value), Ok(())) => Ok(value),@@ -484,7 +499,8 @@ impl PluginDriverSession {env: PluginRuntimeEnv,activity: lifecycle::PluginUsageGuard,) -> Result<Self, String> {- let sidecar = PluginSidecarSession::start(plugin, app_version, env).await?;+ let runtime_lease = activity.runtime_lease()?;+ let sidecar = PluginSidecarSession::start_with_runtime_lease(plugin, app_version, env, runtime_lease).await?;Ok(Self { sidecar, driver_id, _activity: Some(activity), logical: None })}@@ -609,6 +625,8 @@ impl Drop for PluginDriverSession {fn drop(&mut self) {if let Some(logical) = &self.logical {logical.close_in_background();+ } else {+ drop(runtime::ShutdownOnDrop::new(self.sidecar.clone()));}}}diff --git a/crates/dbx-plugin-runtime/src/plugins/host.rs b/crates/dbx-plugin-runtime/src/plugins/host.rsindex 7917236a81..22d4878451 100644--- a/crates/dbx-plugin-runtime/src/plugins/host.rs+++ b/crates/dbx-plugin-runtime/src/plugins/host.rs@@ -126,15 +126,16 @@ impl PluginHost {env: PluginRuntimeEnv,) -> Result<Arc<PluginSidecarSession>, String> {let _activity = self.inner.registry.lifecycle.begin_operation(plugin_id)?;- if let Some(session) = self.running_session(plugin_id).await {- return Ok(session);- }-let _activation = self.inner.activation_lock.lock().await;if let Some(session) = self.running_session(plugin_id).await {return Ok(session);}- self.inner.sessions.write().await.remove(plugin_id);+ // Failed/stopping sessions still own process handles. Do not silently replace one.+ let previous = self.inner.sessions.read().await.get(plugin_id).cloned();+ if let Some(previous) = previous {+ previous.shutdown().await?;+ self.inner.sessions.write().await.remove(plugin_id);+ }let plugin = self.inner@@ -145,12 +146,106 @@ impl PluginHost {return Err(format!("Plugin '{plugin_id}' is incompatible: {}", plugin.compatibility.errors.join("; ")));}let env = env.with_plugin_data_dir(&self.inner.registry.plugin_data_dir(&plugin.manifest.id));- let session = PluginSidecarSession::start(plugin, self.inner.registry.app_version().to_string(), env).await?;+ let runtime_lease = self.inner.registry.lifecycle.runtime_lease(plugin_id)?;+ let probe = self.inner.registry.lifecycle.update_probe(plugin_id)?;+ let session = PluginSidecarSession::start_with_runtime_lease(+ plugin,+ self.inner.registry.app_version().to_string(),+ env,+ runtime_lease,+ )+ .await?;+ // Registration can wait for the session map; cancellation there must still stop the child.+ let startup = super::runtime::ShutdownOnDrop::new(session.clone());self.forward_session_events(&session);self.inner.sessions.write().await.insert(plugin_id.to_string(), session.clone());+ self.watch_session(&session, probe);+ startup.disarm();Ok(session)}+ /// Discovery must not leave one idle process per installed plugin in every MCP client.+ /// Reuse a live session, but keep a session started only for probing short-lived.+ pub async fn probe<T>(+ &self,+ plugin_id: &str,+ method: &str,+ params: serde_json::Value,+ timeout: Option<Duration>,+ ) -> Result<T, String>+ where+ T: DeserializeOwned,+ {+ let _activity = self.inner.registry.lifecycle.begin_operation(plugin_id)?;+ if let Some(session) = self.running_session(plugin_id).await {+ return session.invoke_with_timeout(method, params, None, timeout).await;+ }+ let plugin = self+ .inner+ .registry+ .find_plugin(plugin_id)?+ .ok_or_else(|| format!("Plugin '{plugin_id}' is not installed"))?;+ if !plugin.compatibility.compatible {+ return Err(format!("Plugin '{plugin_id}' is incompatible: {}", plugin.compatibility.errors.join("; ")));+ }+ let env = PluginRuntimeEnv::default().with_plugin_data_dir(&self.inner.registry.plugin_data_dir(plugin_id));+ let session = PluginSidecarSession::start_with_runtime_lease(+ plugin,+ self.inner.registry.app_version().to_string(),+ env,+ self.inner.registry.lifecycle.runtime_lease(plugin_id)?,+ )+ .await?;+ let _cleanup = super::runtime::ShutdownOnDrop::new(session.clone());+ let result = session.invoke_with_timeout(method, params, None, timeout).await;+ let shutdown = session.shutdown().await;+ match (result, shutdown) {+ (Ok(value), Ok(())) => Ok(value),+ (Err(error), Ok(())) | (Ok(_), Err(error)) => Err(error),+ (Err(error), Err(shutdown)) => Err(format!("{error}; additionally failed to stop plugin: {shutdown}")),+ }+ }++ fn watch_session(&self, session: &Arc<PluginSidecarSession>, probe: super::lifecycle::PluginUpdateProbe) {+ let owner = Arc::downgrade(&self.inner);+ let runtime = Arc::downgrade(session);+ tokio::spawn(async move {+ loop {+ tokio::time::sleep(Duration::from_millis(250)).await;+ let Some(session) = runtime.upgrade() else { break };+ let Some(inner) = owner.upgrade() else {+ // The stdout task owns an Arc to the session; dropping the host alone cannot+ // break that cycle while the sidecar is waiting for its next request.+ match session.shutdown().await {+ Ok(()) => break,+ Err(error) => log::warn!("{error}"),+ }+ continue;+ };+ let plugin_id = &session.plugin().manifest.id;+ let stop = match probe.requested() {+ Ok(requested) => {+ requested+ || matches!(+ session.status().state,+ PluginSessionState::Stopping | PluginSessionState::Stopped | PluginSessionState::Exited+ )+ }+ Err(error) => {+ log::warn!("{error}");+ false+ }+ };+ if stop {+ match stop_host_session(&inner, plugin_id, Some(&session)).await {+ Ok(()) => break,+ Err(error) => log::warn!("{error}"),+ }+ }+ }+ });+ }+pub async fn invoke<T>(&self,plugin_id: &str,@@ -340,17 +435,14 @@ impl PluginHost {}pub async fn stop(&self, plugin_id: &str) -> Result<(), String> {- if let Some(session) = self.inner.sessions.write().await.remove(plugin_id) {- session.shutdown().await?;- }- Ok(())+ stop_host_session(&self.inner, plugin_id, None).await}pub async fn stop_all(&self) -> Result<(), String> {- let sessions = std::mem::take(&mut *self.inner.sessions.write().await);+ let plugins = self.inner.sessions.read().await.keys().cloned().collect::<Vec<_>>();let mut errors = Vec::new();- for (plugin_id, session) in sessions {- if let Err(error) = session.shutdown().await {+ for plugin_id in plugins {+ if let Err(error) = self.stop(&plugin_id).await {errors.push(format!("{plugin_id}: {error}"));}}@@ -370,14 +462,19 @@ impl PluginHost {/// Callers drain the plugin's connection pools and external driver pools first: the lease is/// refused while the plugin still has an active connection or operation.pub async fn uninstall_plugin(&self, plugin_id: &str) -> Result<(), String> {- let _update = self.inner.registry.lifecycle.begin_update(plugin_id)?;+ let update = self.inner.registry.lifecycle.begin_update(plugin_id)?;self.stop(plugin_id).await?;let root_dir = self.inner.registry.root_dir().to_path_buf();let app_version = self.inner.registry.app_version().to_string();// Uninstall never validates a package signature, so it must not load the user trust store.let installer = PluginPackageInstaller::with_trust_store(root_dir, app_version, PluginTrustStore::default());let plugin_id = plugin_id.to_string();- tokio::task::spawn_blocking(move || installer.uninstall(&plugin_id)).await.map_err(|error| error.to_string())?+ tokio::task::spawn_blocking(move || {+ update.drain_runtimes()?;+ installer.uninstall(&plugin_id)+ })+ .await+ .map_err(|error| error.to_string())?}async fn running_session(&self, plugin_id: &str) -> Option<Arc<PluginSidecarSession>> {@@ -451,6 +548,24 @@ impl PluginHost {}}+async fn stop_host_session(+ inner: &PluginHostInner,+ plugin_id: &str,+ expected: Option<&Arc<PluginSidecarSession>>,+) -> Result<(), String> {+ let _activation = inner.activation_lock.lock().await;+ let session = inner.sessions.read().await.get(plugin_id).cloned();+ if let Some(session) = session {+ if expected.is_some_and(|expected| !Arc::ptr_eq(expected, &session)) {+ return Ok(());+ }+ session.shutdown().await?;+ // Keep a session tracked on failure, so a retry can still terminate its process tree.+ inner.sessions.write().await.remove(plugin_id);+ }+ Ok(())+}+fn required_plugin_binding<'a>(value: &'a Option<String>, field: &str) -> Result<&'a str, String> {value.as_deref()diff --git a/crates/dbx-plugin-runtime/src/plugins/installer.rs b/crates/dbx-plugin-runtime/src/plugins/installer.rsindex 8a90cbc918..a560d7ffee 100644--- a/crates/dbx-plugin-runtime/src/plugins/installer.rs+++ b/crates/dbx-plugin-runtime/src/plugins/installer.rs@@ -568,6 +568,9 @@ impl PluginPackageInstaller {make_backend_executable(&compatibility.backend_executable)?;let update_guard = self.lifecycle.as_ref().map(|lifecycle| lifecycle.begin_update(&manifest.id)).transpose()?;+ if let Some(guard) = &update_guard {+ guard.drain_runtimes()?;+ }let container_dir = self.root_dir.join(&manifest.id);migrate_legacy_container(&container_dir)?;let versions_dir = container_dir.join(VERSIONS_DIR);@@ -705,6 +708,9 @@ impl PluginPackageInstaller {fn rollback_locked(&self, plugin_id: &str) -> Result<PluginRollbackResult, String> {let update_guard = self.lifecycle.as_ref().map(|lifecycle| lifecycle.begin_update(plugin_id)).transpose()?;+ if let Some(guard) = &update_guard {+ guard.drain_runtimes()?;+ }let container_dir = self.root_dir.join(plugin_id);let current = read_latest_activation(&container_dir)?.ok_or_else(|| format!("Plugin '{plugin_id}' does not have an active version"))?;diff --git a/crates/dbx-plugin-runtime/src/plugins/lifecycle.rs b/crates/dbx-plugin-runtime/src/plugins/lifecycle.rsindex 00b592cafb..a966a99816 100644--- a/crates/dbx-plugin-runtime/src/plugins/lifecycle.rs+++ b/crates/dbx-plugin-runtime/src/plugins/lifecycle.rs@@ -1,5 +1,11 @@use std::collections::{BTreeMap, HashMap};+use std::fs::{File, OpenOptions};+use std::path::{Path, PathBuf};use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use fs2::FileExt;+use sha2::{Digest, Sha256};const UPDATE_IN_PROGRESS: &str = "Plugin update is in progress. Please try again after it finishes.";const OPERATIONS_ACTIVE: &str = "Plugin update blocked by active operations. Please wait for them to finish.";@@ -7,6 +13,22 @@ const OPERATIONS_ACTIVE: &str = "Plugin update blocked by active operations. Ple#[derive(Debug, Clone, Default)]pub struct PluginLifecycle {usage: Arc<Mutex<HashMap<String, PluginUsage>>>,+ store: Option<Arc<PathBuf>>,+}++pub(super) struct PluginUpdateProbe(Option<File>);++impl PluginUpdateProbe {+ pub(super) fn requested(&self) -> Result<bool, String> {+ let Some(file) = &self.0 else { return Ok(false) };+ match FileExt::try_lock_shared(file) {+ Ok(()) => FileExt::unlock(file)+ .map(|()| false)+ .map_err(|error| format!("Failed to release plugin lifecycle probe: {error}")),+ Err(error) if lock_contended(&error) => Ok(true),+ Err(error) => Err(format!("Failed to inspect plugin lifecycle lock: {error}")),+ }+ }}#[derive(Debug, Default)]@@ -44,6 +66,9 @@ struct PluginUsageLease {lifecycle: PluginLifecycle,plugin_id: String,kind: PluginUsageKind,+ // Release the runtime barrier before admitting new operations.+ runtime_lock: Mutex<Option<File>>,+ _activity_lock: Option<File>,}#[derive(Debug)]@@ -54,6 +79,39 @@ enum PluginUsageKind {}impl PluginLifecycle {+ pub(super) fn for_store(root: &Path) -> Self {+ Self { store: Some(Arc::new(root.join(".runtime"))), ..Self::default() }+ }++ fn lock_file(&self, plugin_id: &str, name: &str) -> Result<Option<File>, String> {+ let Some(root) = &self.store else { return Ok(None) };+ // IDs arriving from external tool calls must never become filesystem paths.+ let key = format!("{:x}", Sha256::digest(plugin_id.as_bytes()));+ let dir = root.join(key);+ std::fs::create_dir_all(&dir).map_err(|error| format!("Failed to prepare plugin lifecycle: {error}"))?;+ OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .open(dir.join(name))+ .map(Some)+ .map_err(|error| format!("Failed to open plugin lifecycle lock: {error}"))+ }++ pub(super) fn runtime_lease(&self, plugin_id: &str) -> Result<Option<File>, String> {+ let file = self.lock_file(plugin_id, "runtime.lock")?;+ if let Some(file) = &file {+ FileExt::try_lock_shared(file).map_err(|_| UPDATE_IN_PROGRESS.to_string())?;+ }+ Ok(file)+ }++ /// An exclusive activity lock requests idle runtimes in *every* DBX host to stop.+ pub(super) fn update_probe(&self, plugin_id: &str) -> Result<PluginUpdateProbe, String> {+ Ok(PluginUpdateProbe(self.lock_file(plugin_id, "activity.lock")?))+ }+pub(crate) fn check_update(&self, plugin_id: &str) -> Result<(), String> {let usage = self.usage.lock().unwrap_or_else(|error| error.into_inner());usage.get(plugin_id).map_or(Ok(()), PluginUsage::ensure_updatable)@@ -78,6 +136,26 @@ impl PluginLifecycle {if usage.updating {return Err(UPDATE_IN_PROGRESS.to_string());}+ if matches!(kind, PluginUsageKind::Update) {+ usage.ensure_updatable()?;+ }+ let file = self.lock_file(plugin_id, "activity.lock")?;+ if let Some(file) = &file {+ let result = if matches!(kind, PluginUsageKind::Update) {+ FileExt::try_lock_exclusive(file)+ } else {+ FileExt::try_lock_shared(file)+ };+ result.map_err(|error| {+ if lock_contended(&error) {+ if matches!(kind, PluginUsageKind::Update) {+ "Plugin update blocked by active connections or operations in another DBX host. Close them and try again.".to_string()+ } else {+ UPDATE_IN_PROGRESS.to_string()+ }+ } else { format!("Failed to lock plugin lifecycle: {error}") }+ })?;+ }match &kind {PluginUsageKind::Connection(label) => *usage.connections.entry(label.clone()).or_default() += 1,PluginUsageKind::Operation => usage.operations += 1,@@ -87,11 +165,53 @@ impl PluginLifecycle {}}Ok(PluginUsageGuard {- _lease: Arc::new(PluginUsageLease { lifecycle: self.clone(), plugin_id: plugin_id.to_string(), kind }),+ _lease: Arc::new(PluginUsageLease {+ lifecycle: self.clone(),+ plugin_id: plugin_id.to_string(),+ kind,+ runtime_lock: Mutex::new(None),+ _activity_lock: file,+ }),})}}+fn lock_contended(error: &std::io::Error) -> bool {+ error.raw_os_error() == fs2::lock_contended_error().raw_os_error()+}++impl PluginUsageGuard {+ pub(super) fn runtime_lease(&self) -> Result<Option<File>, String> {+ self._lease.lifecycle.runtime_lease(&self._lease.plugin_id)+ }++ /// Called on a blocking installer thread, after the activity lock prevents new work.+ /// Runtime monitors release their shared locks only after all executable handles drop.+ pub(super) fn drain_runtimes(&self) -> Result<(), String> {+ let Some(file) = self._lease.lifecycle.lock_file(&self._lease.plugin_id, "runtime.lock")? else {+ return Ok(());+ };+ let deadline = Instant::now() + Duration::from_secs(15);+ loop {+ match FileExt::try_lock_exclusive(&file) {+ Ok(()) => {+ *self._lease.runtime_lock.lock().unwrap_or_else(|error| error.into_inner()) = Some(file);+ return Ok(());+ }+ Err(error) if lock_contended(&error) && Instant::now() < deadline => {+ std::thread::sleep(Duration::from_millis(20));+ }+ Err(error) => {+ return Err(format!(+ "Failed to stop plugin '{}' runtimes in other DBX hosts: {error}",+ self._lease.plugin_id+ ))+ }+ }+ }+ }+}+impl Drop for PluginUsageLease {fn drop(&mut self) {let mut plugins = self.lifecycle.usage.lock().unwrap_or_else(|error| error.into_inner());diff --git a/crates/dbx-plugin-runtime/src/plugins/lifecycle_tests.rs b/crates/dbx-plugin-runtime/src/plugins/lifecycle_tests.rsnew file mode 100644index 0000000000..1ec224c032--- /dev/null+++ b/crates/dbx-plugin-runtime/src/plugins/lifecycle_tests.rs@@ -0,0 +1,309 @@+use std::collections::BTreeMap;+use std::io::{Cursor, Write};+use std::path::Path;+use std::sync::Arc;+use std::time::Duration;++use serde_json::{json, Value};+use sha2::{Digest, Sha256};+use zip::write::SimpleFileOptions;++use super::{PluginHost, PluginInstallPolicy, PluginPackageInstaller, PluginRegistry, PluginTrustStore};++const ID: &str = "sample.lifecycle";++fn package(version: &str) -> Vec<u8> {+ #[cfg(windows)]+ let (executable, script, extra) = (+ "sidecar.cmd",+ "@echo off\r\n\"%SystemRoot%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoLogo -NoProfile -ExecutionPolicy Bypass -File \"%~dp0sidecar.ps1\"\r\n",+ Some(("sidecar.ps1", r#"+while ($null -ne ($line = [Console]::ReadLine())) {+ $r = $line | ConvertFrom-Json+ if ($r.method -eq 'plugin/initialize') {+ if ($env:DBX_LIFECYCLE_STALL -eq '1') {+ [IO.Directory]::CreateDirectory($env:DBX_PLUGIN_DATA_DIR) | Out-Null+ [IO.File]::WriteAllText((Join-Path $env:DBX_PLUGIN_DATA_DIR 'waiting'), 'ready')+ continue+ }+ $result = @{protocolVersion=1; capabilities=@(); plugin=@{id=$env:DBX_PLUGIN_ID; version=$env:DBX_PLUGIN_VERSION}}+ } elseif ($r.method -eq 'wait') {+ [IO.Directory]::CreateDirectory($env:DBX_PLUGIN_DATA_DIR) | Out-Null+ [IO.File]::WriteAllText((Join-Path $env:DBX_PLUGIN_DATA_DIR 'waiting'), 'ready')+ continue+ } else { $result = $env:DBX_PLUGIN_VERSION }+ [Console]::WriteLine((@{jsonrpc='2.0'; id=$r.id; result=$result} | ConvertTo-Json -Depth 8 -Compress))+}+"#)),+ );+ #[cfg(unix)]+ let (executable, script, extra): (&str, &str, Option<(&str, &str)>) = (+ "sidecar.sh",+ r#"#!/bin/sh+while IFS= read -r request; do+ id=$(printf '%s' "$request" | sed -E 's/.*"id":([0-9]+).*/\1/')+ case "$request" in+ *plugin/initialize*)+ if [ "$DBX_LIFECYCLE_STALL" = 1 ]; then mkdir -p "$DBX_PLUGIN_DATA_DIR"; touch "$DBX_PLUGIN_DATA_DIR/waiting"; continue; fi+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"capabilities":[],"plugin":{"id":"%s","version":"%s"}}}\n' "$id" "$DBX_PLUGIN_ID" "$DBX_PLUGIN_VERSION" ;;+ *'"method":"wait"'*) mkdir -p "$DBX_PLUGIN_DATA_DIR"; touch "$DBX_PLUGIN_DATA_DIR/waiting" ;;+ *) printf '{"jsonrpc":"2.0","id":%s,"result":"%s"}\n' "$id" "$DBX_PLUGIN_VERSION" ;;+ esac+done+"#,+ None,+ );+ let manifest = json!({+ "manifest_version":1, "id":ID, "name":"Lifecycle fixture", "version":version,+ "publisher":"dbx", "engines":{"dbx":">=0.1.0", "host_api":"^1.0"},+ "entrypoints":{"backend":{"protocol_versions":[1],"transport":"stdio-jsonl","executable":executable}}+ })+ .to_string();+ let mut files = BTreeMap::from([("manifest.json", manifest.as_str()), (executable, script)]);+ if let Some((name, content)) = extra {+ files.insert(name, content);+ }+ let checksums: BTreeMap<_, _> =+ files.iter().map(|(name, bytes)| (*name, format!("{:x}", Sha256::digest(bytes.as_bytes())))).collect();+ let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));+ let options = SimpleFileOptions::default().unix_permissions(0o755);+ for (name, content) in files {+ zip.start_file(name, options).unwrap();+ zip.write_all(content.as_bytes()).unwrap();+ }+ zip.start_file("checksums.json", options).unwrap();+ zip.write_all(json!({"algorithm":"sha256","files":checksums}).to_string().as_bytes()).unwrap();+ zip.finish().unwrap().into_inner()+}++fn registry(root: &Path) -> PluginRegistry {+ PluginRegistry::new_with_app_version(root.to_path_buf(), "0.6.14")+}++fn installer(root: &Path) -> PluginPackageInstaller {+ PluginPackageInstaller::with_trust_store(root.to_path_buf(), "0.6.14", PluginTrustStore::default())+ .with_lifecycle(registry(root).lifecycle())+}++fn install(root: &Path, version: &str) {+ installer(root).install_bytes(&package(version), PluginInstallPolicy::LocalDevelopment).unwrap();+}++async fn version(host: &PluginHost) -> String {+ host.invoke(ID, "version", json!({}), None, Some(Duration::from_secs(5))).await.unwrap()+}++async fn wait_until(mut ready: impl FnMut() -> bool) {+ tokio::time::timeout(Duration::from_secs(8), async {+ while !ready() {+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ })+ .await+ .expect("plugin processes and image handles should be released");+}++#[tokio::test]+async fn rollback_drains_every_host_then_uninstall_releases_both_versions() {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path().join("plugins");+ install(&root, "0.3.3");+ install(&root, "0.3.4");+ let first = PluginHost::new(registry(&root));+ let second = PluginHost::new(registry(&root));+ assert_eq!(version(&first).await, "0.3.4");+ assert_eq!(version(&second).await, "0.3.4");+ let runtime = Arc::downgrade(&first.activate(ID).await.unwrap());+ let rollback = installer(&root);+ let result = tokio::task::spawn_blocking(move || rollback.rollback(ID)).await.unwrap().unwrap();+ assert_eq!(result.plugin.manifest.version, "0.3.3");+ assert!(runtime.upgrade().is_none(), "old executable handles must drop before rollback commits");+ assert!(first.list_active().await.is_empty());+ assert!(second.list_active().await.is_empty());+ drop(result);+ assert_eq!(version(&first).await, "0.3.3");+ assert_eq!(version(&second).await, "0.3.3");+ // A third, independent host performs the uninstall while both MCP hosts are still alive.+ PluginHost::new(registry(&root)).uninstall_plugin(ID).await.unwrap();+ assert!(!root.join(ID).exists());+ assert!(first.list_active().await.is_empty());+ assert!(second.list_active().await.is_empty());+}++#[tokio::test]+async fn discovery_is_transient_and_preserves_a_live_session() {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path().join("plugins");+ install(&root, "0.3.4");+ let host = PluginHost::new(registry(&root));+ let result: String = host.probe(ID, "mcp/tools", json!({}), None).await.unwrap();+ assert_eq!(result, "0.3.4");+ assert!(host.list_active().await.is_empty());+ let session = host.activate(ID).await.unwrap();+ let _: String = host.probe(ID, "mcp/tools", json!({}), None).await.unwrap();+ assert!(Arc::ptr_eq(&session, &host.activate(ID).await.unwrap()));+ host.stop_all().await.unwrap();+}++#[tokio::test]+async fn cancelled_discovery_does_not_leave_a_process_or_block_uninstall() {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path().join("plugins");+ install(&root, "0.3.4");+ let host = PluginHost::new(registry(&root));+ let marker = registry(&root).plugin_data_dir(ID).join("waiting");+ let probing = host.clone();+ let task = tokio::spawn(async move { probing.probe::<Value>(ID, "wait", json!({}), None).await });+ wait_until(|| marker.exists()).await;+ task.abort();+ let _ = task.await;+ host.uninstall_plugin(ID).await.unwrap();+ assert!(!root.join(ID).exists());+}++#[tokio::test]+async fn cancelled_initialization_releases_the_untracked_runtime() {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path().join("plugins");+ install(&root, "0.3.4");+ let host = PluginHost::new(registry(&root));+ let marker = registry(&root).plugin_data_dir(ID).join("waiting");+ let starting = host.clone();+ let task = tokio::spawn(async move {+ starting.activate_with_env(ID, super::PluginRuntimeEnv::default().with_var("DBX_LIFECYCLE_STALL", "1")).await+ });+ wait_until(|| marker.exists()).await;+ task.abort();+ let _ = task.await;+ assert!(host.list_active().await.is_empty());+ host.uninstall_plugin(ID).await.unwrap();+ assert!(!root.join(ID).exists());+}++#[tokio::test]+async fn rollback_refuses_another_hosts_active_request_without_killing_it() {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path().join("plugins");+ install(&root, "0.3.3");+ install(&root, "0.3.4");+ let host = PluginHost::new(registry(&root));+ let marker = registry(&root).plugin_data_dir(ID).join("waiting");+ let requesting = host.clone();+ let task = tokio::spawn(async move { requesting.invoke::<Value>(ID, "wait", json!({}), None, None).await });+ wait_until(|| marker.exists()).await;+ let session = host.activate(ID).await.unwrap();+ let rollback = installer(&root);+ let error = tokio::task::spawn_blocking(move || rollback.rollback(ID)).await.unwrap().unwrap_err();+ assert!(error.contains("another DBX host"), "{error}");+ assert_eq!(session.status().state, super::PluginSessionState::Running);+ assert_eq!(registry(&root).find_plugin(ID).unwrap().unwrap().manifest.version, "0.3.4");+ task.abort();+ let _ = task.await;+ drop(session);+ host.uninstall_plugin(ID).await.unwrap();+}++#[tokio::test]+async fn dropping_the_host_stops_its_cached_process() {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path().join("plugins");+ install(&root, "0.3.4");+ let host = PluginHost::new(registry(&root));+ let runtime = Arc::downgrade(&host.activate(ID).await.unwrap());+ drop(host);+ wait_until(|| runtime.upgrade().is_none()).await;+ // On Windows this also exercises release of the launcher's working-directory handle.+ std::fs::rename(root.join(ID), root.join("retired")).unwrap();+}++#[tokio::test]+async fn dropping_a_driver_session_releases_its_process_before_uninstall() {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path().join("plugins");+ install(&root, "0.3.4");+ let registry = registry(&root);+ let driver = super::PluginDriverSession::start(+ registry.find_plugin(ID).unwrap().unwrap(),+ "fixture".to_string(),+ "0.6.14".to_string(),+ super::PluginRuntimeEnv::default(),+ registry.lifecycle().begin_connection(ID, "Fixture").unwrap(),+ )+ .await+ .unwrap();+ let runtime = Arc::downgrade(&driver.sidecar);+ std::thread::spawn(move || drop(driver)).join().unwrap();+ wait_until(|| runtime.upgrade().is_none()).await;+ PluginHost::new(registry).uninstall_plugin(ID).await.unwrap();+ assert!(!root.join(ID).exists());+}++#[test]+fn independent_hosts_refuse_updates_while_real_work_is_active() {+ let temp = tempfile::tempdir().unwrap();+ let first = registry(temp.path()).lifecycle();+ let second = registry(temp.path()).lifecycle();+ let connection = first.begin_connection(ID, "Production").unwrap();+ assert!(second.begin_update(ID).unwrap_err().contains("another DBX host"));+ assert!(second.begin_update("other").is_ok());+ drop(connection);+ let operation = first.begin_operation(ID).unwrap();+ assert!(second.begin_update(ID).is_err());+ drop(operation);+ let update = second.begin_update(ID).unwrap();+ assert!(first.begin_operation(ID).is_err());+ drop(update);+ assert!(first.begin_operation(ID).is_ok());+}++#[tokio::test]+#[ignore = "subprocess fixture for external_host_observes_rollback_and_uninstall"]+async fn external_host_fixture() {+ let root = std::env::var_os("DBX_LIFECYCLE_TEST_ROOT").expect("fixture root");+ let root = Path::new(&root);+ let control = root.parent().unwrap();+ let host = PluginHost::new(registry(root));+ std::fs::write(control.join("ready"), version(&host).await).unwrap();+ tokio::time::timeout(Duration::from_secs(30), async {+ loop {+ if control.join("quit").exists() {+ break;+ }+ if control.join("probe").exists() && !control.join("observed").exists() {+ std::fs::write(control.join("observed"), version(&host).await).unwrap();+ }+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ })+ .await+ .unwrap();+ host.stop_all().await.unwrap();+}++#[tokio::test]+async fn external_host_observes_rollback_and_uninstall() {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path().join("plugins");+ install(&root, "0.3.3");+ install(&root, "0.3.4");+ let mut command = crate::process::new_tokio_command(std::env::current_exe().unwrap());+ command+ .args(["--exact", "plugins::lifecycle_tests::external_host_fixture", "--ignored", "--nocapture"])+ .env("DBX_LIFECYCLE_TEST_ROOT", &root)+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::inherit())+ .kill_on_drop(true);+ let mut child = command.spawn().unwrap();+ wait_until(|| std::fs::read_to_string(temp.path().join("ready")).ok().as_deref() == Some("0.3.4")).await;+ assert_eq!(std::fs::read_to_string(temp.path().join("ready")).unwrap(), "0.3.4");+ let rollback = installer(&root);+ drop(tokio::task::spawn_blocking(move || rollback.rollback(ID)).await.unwrap().unwrap());+ std::fs::write(temp.path().join("probe"), "").unwrap();+ wait_until(|| std::fs::read_to_string(temp.path().join("observed")).ok().as_deref() == Some("0.3.3")).await;+ assert_eq!(std::fs::read_to_string(temp.path().join("observed")).unwrap(), "0.3.3");+ PluginHost::new(registry(&root)).uninstall_plugin(ID).await.unwrap();+ assert!(!root.join(ID).exists());+ std::fs::write(temp.path().join("quit"), "").unwrap();+ assert!(tokio::time::timeout(Duration::from_secs(8), child.wait()).await.unwrap().unwrap().success());+}diff --git a/crates/dbx-plugin-runtime/src/plugins/runtime.rs b/crates/dbx-plugin-runtime/src/plugins/runtime.rsindex 40dc6b9cf8..6fd4200cef 100644--- a/crates/dbx-plugin-runtime/src/plugins/runtime.rs+++ b/crates/dbx-plugin-runtime/src/plugins/runtime.rs@@ -171,6 +171,37 @@ pub struct PluginSidecarSession {/// request deadlines of this session so a user typing an MFA code cannot/// fail a plugin `connection/test` or `connection/connect` call.prompts: PromptActivity,+ owner_runtime: tokio::runtime::Handle,+ // Kept until the session (including its child/image handle) is completely dropped.+ _runtime_lease: Option<std::fs::File>,+}++/// Cancelled discovery/initialization must not leave the stdout task and child owning each other.+pub(super) struct ShutdownOnDrop(Option<Arc<PluginSidecarSession>>);++impl ShutdownOnDrop {+ pub(super) fn new(session: Arc<PluginSidecarSession>) -> Self {+ Self(Some(session))+ }+ pub(super) fn disarm(mut self) {+ self.0.take();+ }+}++impl Drop for ShutdownOnDrop {+ fn drop(&mut self) {+ let Some(session) = self.0.take() else { return };+ if session.status().state == PluginSessionState::Stopped {+ return;+ }+ // Pool/session owners can also be dropped from a blocking thread.+ let runtime = session.owner_runtime.clone();+ runtime.spawn(async move {+ if let Err(error) = session.shutdown().await {+ log::warn!("{error}");+ }+ });+ }}/// Tracks whether this plugin session has a user prompt open, and wakes the@@ -213,6 +244,15 @@ impl PluginSidecarSession {plugin: InstalledPlugin,app_version: impl Into<String>,env: PluginRuntimeEnv,+ ) -> Result<Arc<Self>, String> {+ Self::start_with_runtime_lease(plugin, app_version, env, None).await+ }++ pub(super) async fn start_with_runtime_lease(+ plugin: InstalledPlugin,+ app_version: impl Into<String>,+ env: PluginRuntimeEnv,+ runtime_lease: Option<std::fs::File>,) -> Result<Arc<Self>, String> {ensure_plugin_backend(&plugin)?;let transport = plugin.manifest.backend_entrypoint().map(|backend| backend.transport).unwrap_or_default();@@ -240,8 +280,11 @@ impl PluginSidecarSession {status,handshake: RwLock::new(None),prompts: PromptActivity::default(),+ owner_runtime: tokio::runtime::Handle::current(),+ _runtime_lease: runtime_lease,});+ let startup = ShutdownOnDrop::new(session.clone());session.spawn_stdout_reader(stdout);if let Some(stderr) = stderr {session.spawn_stderr_reader(stderr);@@ -278,6 +321,7 @@ impl PluginSidecarSession {session.plugin.manifest.id));}+ startup.disarm();Ok(session)}