Files
leleka/control-plane/src/embedded_engine.rs
T
Pavlo Ratushnyi 35bf3a03d3 STRA-338 S16: gateway ports (EngineClient, ResponseStore, Clock, ToolHub, VisionEncoder) with adapters and fakes
AppState now holds ports instead of concrete types: `engine: Option<SharedEngine>` replaces the
mpsc::Sender<GenerationCommand>, `responses: SharedResponseStore` replaces Arc<RwLock<ResponseHistory>>,
`clock: SharedClock` serves queue deadlines, uptime and response timestamps, `mcp` is a ToolHub and `vision` a
VisionEncoder. The channel (adapters::ChannelEngine), the history with its disk snapshot
(responses::HistoryResponseStore), the system clock, mcp::Hub and vision::Vision are the adapters; main.rs serve()
composes them. No behaviour change: the HTTP handlers make the same calls in the same order, the queue claim race is
unchanged, only the deadline now reads the injected clock.

Ports are called per request, never per token or stream event (docs/architecture/gateway-ports.md).
ports/fakes has an in-memory adapter per port; control-plane/tests/ports_fakes.rs (12 tests), queue.rs and
adapters/channel_engine.rs add tests that drive the real handlers through them.

Architecture gate: dyn-trait:strata-control fell 35 -> 21 (a BoxError alias replaces 20 `Box<dyn Error>` spellings,
which pays for the 6 new port aliases); main.rs 1156 -> 1155 lines. Also adds scripts/dev/test-outcomes.py (per-test
outcome comparison of two cargo test logs) and scripts/dev/wsl-cargo.sh.
2026-11-05 20:06:28 +01:00

145 lines
5.3 KiB
Rust

//! Opt-in packaged worker. The host still supplies the ELF's shared libraries.
use std::{ffi::OsStr, fs::File, path::PathBuf};
mod payload {
include!(concat!(env!("OUT_DIR"), "/embedded-engine.rs"));
}
pub fn info() -> serde_json::Value {
serde_json::json!({
"embedded": !payload::BYTES.is_empty(),
"bytes": payload::BYTES.len(),
"sha256": (!payload::BYTES.is_empty()).then_some(payload::SHA256),
"declared_source_revision": (!payload::BYTES.is_empty()).then_some(payload::SOURCE_REVISION),
"target_os": std::env::consts::OS,
"target_arch": std::env::consts::ARCH,
"shared_libraries_bundled": false,
"model_bundled": false,
"selection": "engine.executable=@embedded",
})
}
/// Holds the anonymous executable alive for initial spawn and all worker restarts.
pub struct EmbeddedEngine {
_file: File,
pub executable: PathBuf,
}
pub fn resolve(executable: &OsStr) -> Result<Option<EmbeddedEngine>, crate::BoxError> {
if executable != OsStr::new("@embedded") {
return Ok(None);
}
if payload::BYTES.is_empty() {
return Err(
"this binary has no embedded engine; use an external executable or a payload build"
.into(),
);
}
materialize(payload::BYTES).map(Some)
}
/// Explicit loader/help probe; this is not an inference or readiness check.
pub fn help() -> Result<(), crate::BoxError> {
let engine = resolve(OsStr::new("@embedded"))?.ok_or("no embedded engine")?;
let status = std::process::Command::new(&engine.executable)
.arg("--help")
.env("CUDA_VISIBLE_DEVICES", "")
.status()?;
if !status.success() {
return Err(format!("embedded engine help exited with {status}").into());
}
Ok(())
}
#[cfg(not(target_os = "linux"))]
fn materialize(_: &[u8]) -> Result<EmbeddedEngine, crate::BoxError> {
Err("embedded worker execution requires Linux".into())
}
#[cfg(target_os = "linux")]
fn materialize(bytes: &[u8]) -> Result<EmbeddedEngine, crate::BoxError> {
use std::{
io::Write,
os::fd::{AsRawFd, FromRawFd},
};
// SAFETY: constant NUL-terminated name, supported flags, no borrowed pointers retained.
let mut fd = unsafe {
libc::memfd_create(
c"strata-engine".as_ptr(),
libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING | libc::MFD_EXEC,
)
};
if fd < 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::EINVAL) {
// Older kernels do not know MFD_EXEC. Do not retry EPERM/EACCES policy failures.
// SAFETY: same constant name; legacy flags have been available since Linux 3.17.
fd = unsafe {
libc::memfd_create(
c"strata-engine".as_ptr(),
libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING,
)
};
}
if fd < 0 {
return Err(std::io::Error::last_os_error().into());
}
// SAFETY: successful memfd_create transfers a new owned fd exactly once.
let mut file = unsafe { File::from_raw_fd(fd) };
file.write_all(bytes)?;
let seals = libc::F_SEAL_WRITE | libc::F_SEAL_GROW | libc::F_SEAL_SHRINK | libc::F_SEAL_SEAL;
// SAFETY: valid owned fd, integer fcntl argument for F_ADD_SEALS.
if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_ADD_SEALS, seals) } < 0 {
return Err(std::io::Error::last_os_error().into());
}
// Use the parent's fd path: CLOEXEC does not need to leak a descriptor to children.
let executable = PathBuf::from(format!(
"/proc/{}/fd/{}",
std::process::id(),
file.as_raw_fd()
));
Ok(EmbeddedEngine {
_file: file,
executable,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn external_selection_never_materializes_an_engine() {
assert!(resolve(OsStr::new("/external/strata")).unwrap().is_none());
assert_eq!(info()["shared_libraries_bundled"], false);
if payload::BYTES.is_empty() {
assert!(resolve(OsStr::new("@embedded")).is_err());
}
}
#[cfg(target_os = "linux")]
#[test]
fn sealed_payload_is_exact_immutable_and_removed_on_drop() {
use std::{io::Write, os::unix::fs::MetadataExt};
let engine = materialize(b"immutable fixture bytes").unwrap();
let path = engine.executable.clone();
assert_eq!(std::fs::read(&path).unwrap(), b"immutable fixture bytes");
let mut other = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
assert!(other.write_all(b"x").is_err());
assert!(other.set_len(0).is_err());
assert!(other.set_len(100).is_err());
// Keep a witness open so this inode cannot be recycled during the check.
// Parallel tests can reuse the original descriptor number after Drop.
let original = other.metadata().unwrap();
assert_eq!(std::fs::metadata(&path).unwrap().ino(), original.ino());
drop(engine);
match std::fs::metadata(&path) {
Ok(current) => assert_ne!(
(current.dev(), current.ino()),
(original.dev(), original.ino()),
"original descriptor still refers to the payload after Drop"
),
Err(error) => assert_eq!(error.kind(), std::io::ErrorKind::NotFound),
}
drop(other);
}
}