feat(m0.6-r2): isolated plugin worker transport

- add a hidden __plugin-worker mode that loads one native library in a child
  process and serves length-prefixed JSON invoke frames
- add host WorkerPlugin with ready handshake, export cross-check, per-call
  timeout and crash/EOF propagation
- route kind: worker without in-process trust; native still requires explicit
  trust; wasm is rejected explicitly
- report worker_processes=true while keeping strict OS isolation unavailable
- test successful worker calls and worker crash isolation
- update plugin ABI spec and R2 status
This commit is contained in:
cflmy committed 2026-11-20 11:52:26 +08:00
1 parent 4ce37afb39
commit 44c2df2361
12 files changed
+661 -47

No files matched your search

+66 -28
View File
@@ -8,7 +8,9 @@ use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use marqdo_plugin_abi::{ErrorKind as PluginErrorKind, LoadedPlugin, PluginError, PluginManifest};
use marqdo_plugin_abi::{
ErrorKind as PluginErrorKind, LoadedPlugin, PluginError, PluginKind, PluginManifest,
};
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, RuntimeError, Value};
@@ -17,6 +19,7 @@ use crate::capability::{Capabilities, CapabilityAudit, CapabilityBroker};
use crate::context::ExecutionContext;
use crate::fs::ProjectFs;
use crate::handles::{contains_plugin_handle, PluginHandleTable};
use crate::plugin_worker::WorkerPlugin;
use crate::trace::{EffectTrace, SemanticEvent, TraceEntry};
use marqdo_sandbox::{PlatformCapabilities, SandboxMode};
@@ -150,7 +153,24 @@ struct PluginSlot {
manifest_digest: String,
/// Complete export name -> declared signature.
exports: BTreeMap<String, String>,
plugin: LoadedPlugin,
plugin: PluginTransport,
}
enum PluginTransport {
Native(LoadedPlugin),
Worker(WorkerPlugin),
}
impl PluginTransport {
fn invoke(
&mut self,
request: &marqdo_plugin_abi::WireRequest,
) -> Result<marqdo_plugin_abi::WireResponse, PluginError> {
match self {
PluginTransport::Native(plugin) => plugin.invoke(request),
PluginTransport::Worker(plugin) => plugin.invoke(request),
}
}
}
impl StdHost {
@@ -199,18 +219,6 @@ impl StdHost {
base_dir: &std::path::Path,
trusted: bool,
) -> Result<Vec<String>, RuntimeError> {
if !trusted {
let mut error = RuntimeError::new(
ErrorCategory::PermissionDenied,
None,
"loading an in-process native plugin requires explicit trust",
);
error.effect_trace.push(
"hint: no isolated plugin worker transport is implemented in this build; in-process native code shares the host address space"
.to_string(),
);
return Err(error);
}
self.capabilities
.check_plugin(&manifest.plugin.name, None)?;
manifest.validate().map_err(map_plugin_error)?;
@@ -239,26 +247,56 @@ impl StdHost {
.resolve_artifact(&marqdo_plugin_abi::HostTarget::current())
.map_err(map_plugin_error)?;
let manifest_digest = artifact.sha256.clone();
let mut broker =
CapabilityBroker::with_audit(self.capabilities.clone(), Arc::clone(&self.broker_audit));
for capability in &self.vendor_capabilities {
broker.allow_vendor(capability.clone());
}
let package = manifest.plugin.name.clone();
let options = marqdo_plugin_abi::LoadOptions {
host_target: marqdo_plugin_abi::HostTarget::current(),
capability_handler: Some(Box::new(move |capability, request| {
broker.authorize(&package, capability, request)
})),
let transport = match manifest.plugin.kind {
PluginKind::Native => {
if !trusted {
let mut error = RuntimeError::new(
ErrorCategory::PermissionDenied,
None,
"loading an in-process native plugin requires explicit trust",
);
error.effect_trace.push(
"hint: use `kind: worker` for crash isolation, or pass --trust-native-plugin for in-process native code"
.to_string(),
);
return Err(error);
}
let mut broker = CapabilityBroker::with_audit(
self.capabilities.clone(),
Arc::clone(&self.broker_audit),
);
for capability in &self.vendor_capabilities {
broker.allow_vendor(capability.clone());
}
let package = manifest.plugin.name.clone();
let options = marqdo_plugin_abi::LoadOptions {
host_target: marqdo_plugin_abi::HostTarget::current(),
capability_handler: Some(Box::new(move |capability, request| {
broker.authorize(&package, capability, request)
})),
};
PluginTransport::Native(
LoadedPlugin::open_with(manifest, base_dir, options)
.map_err(map_plugin_error)?,
)
}
PluginKind::Worker => PluginTransport::Worker(
WorkerPlugin::spawn(manifest, base_dir).map_err(map_plugin_error)?,
),
PluginKind::Wasm => {
return Err(RuntimeError::new(
ErrorCategory::KernelUnavailable,
None,
"plugin kind `wasm` is not supported in this build",
))
}
};
let loaded =
LoadedPlugin::open_with(manifest, base_dir, options).map_err(map_plugin_error)?;
let index = self.plugins.len();
self.plugins.push(PluginSlot {
package: manifest.plugin.name.clone(),
manifest_digest,
exports: exports.clone(),
plugin: loaded,
plugin: transport,
});
let names: Vec<String> = exports.keys().cloned().collect();
for name in &names {
+1
View File
@@ -11,6 +11,7 @@ pub mod fs;
pub mod handles;
pub mod host;
pub mod kernels;
mod plugin_worker;
pub mod trace;
pub use budget::{Budget, DEFAULT_FUEL, DEFAULT_OUTPUT_BYTES, DEFAULT_STACK_LIMIT};
+192
View File
@@ -0,0 +1,192 @@
//! Host side of the isolated plugin worker transport (ADR-0010).
//!
//! The worker is a child process running the same core binary with the hidden
//! `__plugin-worker` command. It isolates crashes and keeps native code out of
//! the interpreter process. A plain process is **not** an OS sandbox; strict
//! mode still refuses without a real isolation adapter.
use std::collections::BTreeMap;
use std::path::Path;
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::{self, Receiver};
use std::thread;
use std::time::Duration;
use marqdo_plugin_abi::worker::{read_frame, write_frame, WORKER_COMMAND};
use marqdo_plugin_abi::{PluginError, PluginManifest, WireRequest, WireResponse};
use serde_json::json;
/// A native plugin running in an isolated worker process.
pub struct WorkerPlugin {
child: Child,
stdin: ChildStdin,
frames: Receiver<Result<serde_json::Value, PluginError>>,
exports: BTreeMap<String, String>,
}
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);
const CALL_TIMEOUT: Duration = Duration::from_secs(10);
impl std::fmt::Debug for WorkerPlugin {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WorkerPlugin")
.field("pid", &self.child.id())
.field("exports", &self.exports.keys().collect::<Vec<_>>())
.finish()
}
}
impl WorkerPlugin {
/// Spawn a worker for `manifest` and wait for its ready frame.
pub fn spawn(manifest: &PluginManifest, base_dir: &Path) -> Result<Self, PluginError> {
let manifest_path = if base_dir.join("plugin.yaml").is_file() {
base_dir.join("plugin.yaml")
} else {
return Err(PluginError::load(
"worker_manifest_missing",
format!("no plugin.yaml in `{}`", base_dir.display()),
));
};
let executable = std::env::current_exe().map_err(|error| {
PluginError::load(
"worker_spawn_failed",
format!("cannot find the current executable: {error}"),
)
})?;
let mut child = Command::new(executable)
.arg(WORKER_COMMAND)
.arg(&manifest_path)
.arg(base_dir)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.map_err(|error| {
PluginError::load(
"worker_spawn_failed",
format!("cannot start plugin worker: {error}"),
)
})?;
let Some(stdin) = child.stdin.take() else {
let _ = child.kill();
return Err(PluginError::load(
"worker_spawn_failed",
"worker stdin unavailable",
));
};
let Some(mut stdout) = child.stdout.take() else {
let _ = child.kill();
return Err(PluginError::load(
"worker_spawn_failed",
"worker stdout unavailable",
));
};
let (sender, frames) = mpsc::channel();
thread::Builder::new()
.name("marqdo-plugin-worker-reader".to_string())
.spawn(move || loop {
let frame = read_frame(&mut stdout);
let failed = frame.is_err();
if sender.send(frame).is_err() || failed {
break;
}
})
.map_err(|error| {
let _ = child.kill();
PluginError::load(
"worker_spawn_failed",
format!("cannot start worker reader: {error}"),
)
})?;
let ready = frames.recv_timeout(HANDSHAKE_TIMEOUT).map_err(|_| {
let _ = child.kill();
PluginError::invoke("plugin.timeout", "plugin worker handshake timed out")
})??;
if ready.get("kind").and_then(serde_json::Value::as_str) != Some("ready") {
let _ = child.kill();
return Err(PluginError::load(
"worker_handshake_failed",
"worker did not report ready",
));
}
let mut exports = BTreeMap::new();
if let Some(entries) = ready.get("exports").and_then(serde_json::Value::as_array) {
for entry in entries {
let Some(name) = entry.get("name").and_then(serde_json::Value::as_str) else {
continue;
};
let signature = entry
.get("signature")
.and_then(serde_json::Value::as_str)
.unwrap_or_default()
.to_string();
exports.insert(name.to_string(), signature);
}
}
let declared: std::collections::BTreeSet<&str> = manifest
.plugin
.exports
.iter()
.map(|export| export.name.as_str())
.collect();
let actual: std::collections::BTreeSet<&str> = exports.keys().map(String::as_str).collect();
if declared != actual {
let _ = child.kill();
return Err(PluginError::manifest(
"worker_export_mismatch",
"worker exports do not match the manifest",
));
}
Ok(Self {
child,
stdin,
frames,
exports,
})
}
/// Invoke one export in the worker.
pub fn invoke(&mut self, request: &WireRequest) -> Result<WireResponse, PluginError> {
let request_value: serde_json::Value = serde_json::from_slice(&request.to_json_bytes()?)
.map_err(|error| PluginError::wire("worker_encode_failed", error.to_string()))?;
write_frame(
&mut self.stdin,
&json!({"kind": "invoke", "request": request_value}),
)?;
let frame = match self.frames.recv_timeout(CALL_TIMEOUT) {
Ok(frame) => frame?,
Err(_) => {
let _ = self.child.kill();
return Err(PluginError::invoke(
"plugin.timeout",
"plugin worker exceeded its invocation timeout",
));
}
};
match frame.get("kind").and_then(serde_json::Value::as_str) {
Some("response") => marqdo_plugin_abi::worker::response_from_frame(&frame),
Some("error") => Err(PluginError::invoke(
frame
.get("code")
.and_then(serde_json::Value::as_str)
.unwrap_or("plugin_call_failed"),
frame
.get("message")
.and_then(serde_json::Value::as_str)
.unwrap_or("worker reported an error"),
)),
_ => Err(PluginError::invoke(
"plugin.crashed",
"plugin worker closed or violated the frame protocol",
)),
}
}
}
impl Drop for WorkerPlugin {
fn drop(&mut self) {
let _ = write_frame(&mut self.stdin, &json!({"kind": "shutdown"}));
let _ = self.child.kill();
let _ = self.child.wait();
}
}