feat(node): manage owned worker lifecycle over gRPC (STRA-58)

This commit is contained in:
Pavlo Ratushnyi
2026-10-04 15:58:48 +02:00
parent 2dbc2bd7d0
commit ffda5f3b6d
8 changed files with 1123 additions and 3 deletions
+77
View File
@@ -125,3 +125,80 @@ reconciliation, verifying backend readiness after node restart (node connectivit
alone is insufficient), real-model harness test, platform qualification and
managed SSH tunnel recreation. An existing tunnel can recover and the gRPC
client reconnects, but this slice does not create/restart SSH processes.
## Managed worker profile (STRA-58)
Implemented CLI/gRPC slice: one trusted, operator-installed profile per node. It binds
an absolute executable and bounded argv to a model identifier and loopback HTTP
endpoint. gRPC exposes typed Start/Stop/Status with an operation UUID; no RPC can
supply executable, shell text or arbitrary arguments. Spawn a direct child with
restricted inherited environment, null logs, and no node credential inheritance.
Admission starts CLOSED. Start refuses an occupied endpoint, launches only its
configured process, polls bounded `/health` and requires status=ok, loaded=true,
model=expected while the child remains alive before opening admission. Child exit
closes admission. Stop closes admission first, waits for admitted work to drain,
and kills/reaps only its owned child. Drain timeout leaves admission closed and
reports failure; no implicit force termination of active inference.
An actor owns operations independently of RPC lifetime. Up to 256 operation IDs
are retained for this process epoch, matching duplicate returns prior status,
conflicting payload is rejected, and at capacity new IDs are refused (no unsafe
eviction). This is process-local idempotency; durable restart reconciliation is
not claimed. Agent restart starts closed and never adopts/kills an existing PID.
An orphan still holding the endpoint causes Start to fail explicitly. Profile
installation and orphan recovery remain separate provisioning/lifecycle gates.
Tests launch synthetic local fixture processes only, without real model requests.
The profile is a JSON file on the node, installed by its operator:
```json
{
"schema_version": 1,
"id": "my-model",
"model": "backend-model-identifier",
"executable": "/absolute/path/to/worker",
"args": ["--serve", "--port", "18090"],
"endpoint": "127.0.0.1:18090",
"startup_timeout_ms": 120000,
"capabilities": ["responses"]
}
```
The executable must remain in the foreground and expose HTTP Responses and
the health contract described above. Configure its real supported arguments;
the example is not a generic adapter for arbitrary engines. The profile ID is
the public gateway model ID; the model field is sent to the backend and checked
against health. Capabilities default to responses only; declare tools, reasoning,
structured_output, image/audio/file only after adapter verification. One slot is
reserved for the exclusive managed worker; the initial resource budget is a slot
sentinel, not an estimate of memory or automatic hardware admission.
```sh
strata-desktop node --listen 127.0.0.1:18766 --token-env STRATA_NODE_TOKEN --worker-profile PROFILE.json
strata-desktop worker --node 127.0.0.1:18766 --token-env STRATA_NODE_TOKEN status
strata-desktop worker --node 127.0.0.1:18766 --token-env STRATA_NODE_TOKEN start OPERATION_UUID
strata-desktop worker --node 127.0.0.1:18766 --token-env STRATA_NODE_TOKEN operation OPERATION_UUID
strata-desktop worker --node 127.0.0.1:18766 --token-env STRATA_NODE_TOKEN stop ANOTHER_UUID
```
Supply a private credential through the environment; start/stop return accepted,
not completed. Poll operation with the same UUID; never infer success from
acceptance. CLI stop uses a 30-second drain grace. A lost connection can query
the same ID in the same node epoch; unknown ID after node restart requires
explicit reconciliation, not automatic resubmission. Node capability is
worker.lifecycle.v1. Existing inventory-only UI children cannot own models;
managed nodes stay independent of UI lifetime. UI buttons and profile installation
remain pending.
The child receives STRATA_WORKER_ENDPOINT and STRATA_WORKER_MODEL alongside a
restricted platform environment. Backend stdout/stderr are discarded. An owned
process exit is observed within the 200 ms polling interval; runtime liveness
beyond process exit is not yet supervised after startup. Starting a replacement
clears previous_response_id ownership, preventing affinity to a lost conversation.
No inference request is retried by lifecycle.
Validation on macOS: real Rust fixture children, real gRPC and CLI subprocesses;
start/stop/auth/dedup/conflict, exact response bytes (zero tolerance), restart
affinity rejection, wrong model/occupied endpoint fail-closed, child crash and
explicit restart, drain timeout preserves active request. The ignored fixture
entry is invoked as a subprocess by the tests, not an omitted quality check.
These are synthetic protocol/process tests, not model quality or speed results.
+23
View File
@@ -2,6 +2,9 @@ syntax = "proto3";
package strata.node.v1;
option csharp_namespace = "Strata.Node.V1";
service Node {
rpc WorkerStatus(Empty) returns (WorkerState);
rpc ControlWorker(WorkerCommand) returns (WorkerOperation);
rpc OperationStatus(OperationQuery) returns (WorkerOperation);
rpc Handshake(Hello) returns (Snapshot);
rpc Hardware(Empty) returns (JsonDocument);
rpc Plan(JsonDocument) returns (JsonDocument);
@@ -30,3 +33,23 @@ message ResponseFrame {
Empty end = 3;
}
}
message WorkerState {
string profile_id = 1;
string model = 2;
string phase = 3;
uint32 pid = 4;
string reason = 5;
}
message WorkerCommand {
string operation_id = 1;
enum Action { UNSPECIFIED = 0; START = 1; STOP = 2; }
Action action = 2;
uint32 drain_timeout_ms = 3;
}
message OperationQuery { string operation_id = 1; }
message WorkerOperation {
string operation_id = 1;
string status = 2;
string reason = 3;
}
+12
View File
@@ -172,6 +172,18 @@ impl Gateway {
pub(crate) fn matches_credential(&self, token: &str) -> bool {
bool::from(token.as_bytes().ct_eq(self.0.token.as_bytes()))
}
pub(crate) fn clear_response_owners(&self) {
self.0.owners.lock().unwrap().clear();
}
pub(crate) fn set_managed_ready(&self, ready: bool) {
for i in 0..self.0.config.deployments.len() {
let _ = self.0.pool.set_ready(i, ready);
}
}
pub(crate) fn idle(&self) -> bool {
let s = self.0.pool.snapshot();
s.active == 0 && s.queued == 0
}
pub fn router(&self) -> Router {
Router::new()
.route("/v1/models", get(models))
+1
View File
@@ -1,6 +1,7 @@
//! Portable desktop contracts. Inventory is not an inference capability claim.
pub mod gateway;
pub mod hardware;
pub mod managed_worker;
pub mod node;
pub mod node_connection;
pub mod node_proxy;
+75 -3
View File
@@ -36,6 +36,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.await?;
return Ok(());
}
if args.first().is_some_and(|s| s == "worker") {
return worker(&args[1..]).await;
}
if args.first().is_some_and(|s| s == "node") {
return serve_node(&args[1..]).await;
}
@@ -57,7 +60,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
[cmd] if cmd == "--help" || cmd == "help" => {
println!(
"strata-desktop hardware\nstrata-desktop plan REQUIREMENTS.json [--hardware SNAPSHOT.json]\nstrata-desktop remote-inspect SSH_PROFILE.json\nstrata-desktop gateway POOL.json\nstrata-desktop node --listen 127.0.0.1:0 --token-env ENV [--pool POOL.json | --stdio-lifetime]\nstrata-desktop node-proxy --listen 127.0.0.1:18765 --node 127.0.0.1:18766 --token-env ENV\nInventory and planning are read-only. Gateway serves configured loopback workers; it does not start or replace models."
"strata-desktop hardware\nstrata-desktop plan REQUIREMENTS.json [--hardware SNAPSHOT.json]\nstrata-desktop remote-inspect SSH_PROFILE.json\nstrata-desktop gateway POOL.json\nstrata-desktop node --listen 127.0.0.1:0 --token-env ENV [--pool POOL.json | --worker-profile FILE | --stdio-lifetime]\nstrata-desktop node-proxy --listen 127.0.0.1:18765 --node 127.0.0.1:18766 --token-env ENV\nstrata-desktop worker --node 127.0.0.1:18766 --token-env ENV status|start UUID|stop UUID|operation UUID\nInventory and planning are read-only. Gateway serves configured loopback workers; it does not start or replace models."
);
return Ok(());
}
@@ -78,7 +81,7 @@ async fn serve_node(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
(address, token_env, rest)
}
_ => return Err(
"usage: node --listen LOOPBACK:PORT --token-env ENV [--pool FILE | --stdio-lifetime]"
"usage: node --listen LOOPBACK:PORT --token-env ENV [--pool FILE | --worker-profile FILE | --stdio-lifetime]"
.into(),
),
};
@@ -94,7 +97,12 @@ async fn serve_node(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
return Err("invalid credential variable name".into());
}
let token = std::env::var(token_env).map_err(|_| "missing node credential")?;
let mut profile = None;
let (gateway, stdio_lifetime) = match mode {
[p, file] if p == "--worker-profile" => {
profile = Some(read_json(file)?);
(None, false)
}
[] => (None, false),
[s] if s == "--stdio-lifetime" => (None, true),
[p, file] if p == "--pool" => (
@@ -106,7 +114,11 @@ async fn serve_node(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
),
_ => return Err("invalid node mode; stdio lifetime cannot own inference".into()),
};
let agent = node::Agent::new(token, gateway)?;
let agent = if let Some(profile) = profile {
node::Agent::managed(token, profile)?
} else {
node::Agent::new(token, gateway)?
};
let listener = tokio::net::TcpListener::bind(address).await?;
println!(
"{}",
@@ -131,3 +143,63 @@ async fn serve_node(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
})
.await
}
async fn worker(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
use node::proto::*;
let [n, address, t, env, action, rest @ ..] = args else {
return Err("worker --node LOOPBACK:PORT --token-env ENV status|start UUID|stop UUID|operation UUID".into());
};
if n != "--node" || t != "--token-env" {
return Err("invalid worker options".into());
}
let token = std::env::var(env).map_err(|_| "missing node credential")?;
let mut client = node::connect(address.parse()?).await?;
let value = match (action.as_str(), rest) {
("status", []) => {
let s = client
.worker_status(worker_request(Empty {}, &token)?)
.await?
.into_inner();
serde_json::json!({"profile_id":s.profile_id,"model":s.model,"phase":s.phase,"pid":s.pid,"reason":s.reason})
}
("start" | "stop", [id]) => {
let s = client
.control_worker(worker_request(
WorkerCommand {
operation_id: id.clone(),
action: if action == "start" { 1 } else { 2 },
drain_timeout_ms: if action == "stop" { 30000 } else { 0 },
},
&token,
)?)
.await?
.into_inner();
serde_json::json!({"operation_id":s.operation_id,"status":s.status,"reason":s.reason})
}
("operation", [id]) => {
let s = client
.operation_status(worker_request(
OperationQuery {
operation_id: id.clone(),
},
&token,
)?)
.await?
.into_inner();
serde_json::json!({"operation_id":s.operation_id,"status":s.status,"reason":s.reason})
}
_ => {
return Err(
"invalid worker action; supply a stable operation UUID for commands".into(),
);
}
};
println!("{}", serde_json::to_string(&value)?);
Ok(())
}
fn worker_request<T>(message: T, token: &str) -> Result<tonic::Request<T>, tonic::Status> {
let mut request = node::authorized(message, token)?;
request.set_timeout(std::time::Duration::from_secs(5));
Ok(request)
}
+400
View File
@@ -0,0 +1,400 @@
//! One trusted local profile. RPC supplies actions, never commands or paths.
use crate::{
gateway::{self, Gateway},
node::proto::{WorkerCommand, WorkerOperation, WorkerState},
};
use serde::Deserialize;
use std::{
collections::{BTreeMap, HashMap},
net::{IpAddr, SocketAddr},
path::PathBuf,
process::Stdio,
sync::{Arc, Mutex},
time::Duration,
};
use tokio::{
process::{Child, Command},
sync::{mpsc, watch},
task::JoinHandle,
};
use tonic::Status;
#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Profile {
pub schema_version: u32,
pub id: String,
pub model: String,
pub executable: PathBuf,
pub args: Vec<String>,
pub endpoint: SocketAddr,
pub startup_timeout_ms: u64,
/// Verified adapter capabilities, never inferred from the model name.
#[serde(default = "default_capabilities")]
pub capabilities: Vec<String>,
}
fn default_capabilities() -> Vec<String> {
vec!["responses".into()]
}
impl Profile {
pub fn validate(&self) -> Result<(), String> {
if self.schema_version != 1
|| self.id.is_empty()
|| self.id.len() > 128
|| !self
.id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|| self.capabilities.is_empty()
|| self.capabilities.len() > 16
|| !self.capabilities.iter().any(|c| c == "responses")
|| self.capabilities.iter().any(|c| {
![
"responses",
"tools",
"reasoning",
"structured_output",
"image",
"audio",
"file",
]
.contains(&c.as_str())
})
|| self.model.is_empty()
|| self.model.len() > 256
|| self.model.chars().any(char::is_control)
|| !self.executable.is_absolute()
|| !self.executable.is_file()
|| self.args.len() > 256
|| self.args.iter().any(|a| a.len() > 4096 || a.contains('\0'))
|| self.args.iter().map(String::len).sum::<usize>() > 32768
|| !self.endpoint.ip().is_loopback()
|| self.endpoint.port() < 1024
|| !(100..=3600000).contains(&self.startup_timeout_ms)
{
return Err("invalid managed worker profile".into());
}
Ok(())
}
pub fn gateway(&self, token: String) -> Result<Gateway, String> {
self.validate()?;
let gateway = Gateway::with_token(
gateway::Config {
schema_version: 1,
listen: SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 0),
token_env: "UNUSED".into(),
queue_limit: 16,
queue_timeout_ms: 1000,
request_timeout_ms: 3600000,
groups: vec![gateway::Group {
id: self.id.clone(),
slots: 1,
available_bytes: 1,
}],
deployments: vec![gateway::Deployment {
id: self.id.clone(),
model: self.model.clone(),
endpoint: format!("http://{}", self.endpoint),
token_env: None,
group: self.id.clone(),
slots: 1,
request_bytes: 1,
capabilities: self.capabilities.clone(),
}],
aliases: BTreeMap::new(),
},
token,
)?;
gateway.set_managed_ready(false);
Ok(gateway)
}
}
#[derive(Clone)]
pub struct Manager(Arc<Owner>);
struct Owner {
tx: mpsc::Sender<WorkerCommand>,
records: Records,
state: watch::Receiver<WorkerState>,
task: JoinHandle<()>,
}
impl Drop for Owner {
fn drop(&mut self) {
self.task.abort();
}
}
impl Manager {
pub fn new(profile: Profile, gateway: Gateway) -> Result<Self, String> {
profile.validate()?;
gateway.set_managed_ready(false);
let (state_tx, state) = watch::channel(WorkerState {
profile_id: profile.id.clone(),
model: profile.model.clone(),
phase: "stopped".into(),
pid: 0,
reason: String::new(),
});
let records = Arc::new(Mutex::new(HashMap::new()));
let (tx, rx) = mpsc::channel(8);
let task = tokio::spawn(run(profile, gateway, state_tx, records.clone(), rx));
Ok(Self(Arc::new(Owner {
tx,
records,
state,
task,
})))
}
pub fn state(&self) -> WorkerState {
self.0.state.borrow().clone()
}
pub fn operation(&self, id: &str) -> Result<WorkerOperation, Status> {
self.0
.records
.lock()
.unwrap()
.get(
&uuid::Uuid::parse_str(id)
.map_err(|_| Status::invalid_argument("operation UUID required"))?
.to_string(),
)
.map(|(_, r)| r.clone())
.ok_or_else(|| Status::not_found("unknown operation for this epoch"))
}
pub fn submit(&self, mut c: WorkerCommand) -> Result<WorkerOperation, Status> {
c.operation_id = uuid::Uuid::parse_str(&c.operation_id)
.map_err(|_| Status::invalid_argument("operation UUID required"))?
.to_string();
if !(1..=2).contains(&c.action)
|| c.drain_timeout_ms > 30000
|| (c.action == 1 && c.drain_timeout_ms != 0)
{
return Err(Status::invalid_argument(
"invalid worker action or drain timeout",
));
}
let mut records = self.0.records.lock().unwrap();
if let Some((old, result)) = records.get(&c.operation_id) {
return if old == &c {
Ok(result.clone())
} else {
Err(Status::already_exists(
"operation ID has different parameters",
))
};
}
if records.len() >= 256 {
return Err(Status::resource_exhausted(
"operation history full; reconcile before new epoch",
));
}
let permit = self
.0
.tx
.try_reserve()
.map_err(|_| Status::resource_exhausted("worker command queue full"))?;
let result = WorkerOperation {
operation_id: c.operation_id.clone(),
status: "accepted".into(),
reason: String::new(),
};
records.insert(c.operation_id.clone(), (c.clone(), result.clone()));
permit.send(c);
Ok(result)
}
}
fn state(tx: &watch::Sender<WorkerState>, phase: &str, pid: u32, reason: &str) {
tx.send_modify(|s| {
s.phase = phase.into();
s.pid = pid;
s.reason = reason.into();
});
}
async fn healthy(client: &reqwest::Client, profile: &Profile) -> bool {
let Ok(response) = client
.get(format!("http://{}/health", profile.endpoint))
.send()
.await
else {
return false;
};
if !response.status().is_success() {
return false;
}
let mut response = response;
let mut data = vec![];
loop {
match response.chunk().await {
Ok(Some(b)) if data.len() + b.len() <= 65536 => data.extend(b),
Ok(None) => break,
_ => return false,
}
}
let Ok(value) = serde_json::from_slice::<serde_json::Value>(&data) else {
return false;
};
value["status"] == "ok" && value["loaded"] == true && value["model"] == profile.model
}
async fn terminate(child: &mut Option<Child>) -> Result<(), &'static str> {
if let Some(c) = child {
c.start_kill().map_err(|_| "stop_failed")?;
tokio::time::timeout(Duration::from_secs(5), c.wait())
.await
.map_err(|_| "stop_timeout")?
.map_err(|_| "wait_failed")?;
}
*child = None;
Ok(())
}
async fn start(
profile: &Profile,
gateway: &Gateway,
tx: &watch::Sender<WorkerState>,
child: &mut Option<Child>,
client: &reqwest::Client,
) -> Result<(), &'static str> {
if let Some(c) = child.as_mut()
&& c.try_wait().map_err(|_| "wait_failed")?.is_some()
{
*child = None;
}
if child.is_some() {
return if tx.borrow().phase == "ready" {
Ok(())
} else {
Err("stop_existing_owned_worker_first")
};
}
gateway.set_managed_ready(false);
// Binding a temporary listener proves the endpoint was free before spawn.
let listener = tokio::net::TcpListener::bind(profile.endpoint)
.await
.map_err(|_| "endpoint_occupied")?;
drop(listener);
gateway.clear_response_owners();
state(tx, "starting", 0, "");
let mut command = Command::new(&profile.executable);
command.args(&profile.args).env_clear();
for key in [
"PATH",
"HOME",
"USER",
"TMPDIR",
"TEMP",
"TMP",
"SystemRoot",
"WINDIR",
"LD_LIBRARY_PATH",
"DYLD_LIBRARY_PATH",
"CUDA_VISIBLE_DEVICES",
] {
if let Some(value) = std::env::var_os(key) {
// Even a nonstandard token variable must not leak through the allowlist.
if !gateway.matches_credential(&value.to_string_lossy()) {
command.env(key, value);
}
}
}
command
.env("STRATA_WORKER_ENDPOINT", profile.endpoint.to_string())
.env("STRATA_WORKER_MODEL", &profile.model);
let process = command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(|_| "spawn_failed")?;
let pid = process.id().unwrap_or(0);
*child = Some(process);
state(tx, "starting", pid, "");
let deadline = tokio::time::Instant::now() + Duration::from_millis(profile.startup_timeout_ms);
while tokio::time::Instant::now() < deadline {
if child
.as_mut()
.unwrap()
.try_wait()
.map_err(|_| "wait_failed")?
.is_some()
{
*child = None;
return Err("worker_exited");
}
if healthy(client, profile).await
&& child
.as_mut()
.unwrap()
.try_wait()
.map_err(|_| "wait_failed")?
.is_none()
{
gateway.set_managed_ready(true);
state(tx, "ready", pid, "");
return Ok(());
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
terminate(child).await?;
Err("startup_timeout")
}
async fn stop(
gateway: &Gateway,
tx: &watch::Sender<WorkerState>,
child: &mut Option<Child>,
grace: u32,
) -> Result<(), &'static str> {
gateway.set_managed_ready(false);
state(
tx,
"draining",
child.as_ref().and_then(Child::id).unwrap_or(0),
"",
);
let deadline = tokio::time::Instant::now() + Duration::from_millis(grace as u64);
while !gateway.idle() {
if tokio::time::Instant::now() >= deadline {
return Err("drain_timeout");
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
terminate(child).await?;
state(tx, "stopped", 0, "");
Ok(())
}
type Records = Arc<Mutex<HashMap<String, (WorkerCommand, WorkerOperation)>>>;
async fn run(
profile: Profile,
gateway: Gateway,
tx: watch::Sender<WorkerState>,
records: Records,
mut rx: mpsc::Receiver<WorkerCommand>,
) {
let client = reqwest::Client::builder()
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_millis(500))
.build()
.expect("HTTP client");
let mut child: Option<Child> = None;
let mut tick = tokio::time::interval(Duration::from_millis(200));
loop {
tokio::select! {
command=rx.recv()=>{
let Some(command)=command else{break};
records.lock().unwrap().get_mut(&command.operation_id).unwrap().1.status="running".into();
let result=if command.action==1 {start(&profile,&gateway,&tx,&mut child,&client).await}else{stop(&gateway,&tx,&mut child,command.drain_timeout_ms).await};
if let Err(reason)=result {gateway.set_managed_ready(false);state(&tx,"failed",child.as_ref().and_then(Child::id).unwrap_or(0),reason);}
let mut records=records.lock().unwrap();let r=&mut records.get_mut(&command.operation_id).unwrap().1;
r.status=if result.is_ok(){"succeeded"}else{"failed"}.into();r.reason=result.err().unwrap_or("").into();
},
_=tick.tick()=>{
if let Some(c)=child.as_mut() {
match c.try_wait() {
Ok(Some(_))=>{child=None;gateway.set_managed_ready(false);state(&tx,"failed",0,"worker_exited");},
Err(_)=>{gateway.set_managed_ready(false);state(&tx,"failed",c.id().unwrap_or(0),"wait_failed");},
Ok(None)=>{}
}
}
}
}
}
gateway.set_managed_ready(false);
let _ = terminate(&mut child).await;
}
+60
View File
@@ -27,13 +27,26 @@ pub struct Agent(Arc<Inner>);
struct Inner {
token: String,
router: Option<Router>,
manager: Option<crate::managed_worker::Manager>,
state: watch::Sender<Snapshot>,
observers: Arc<Semaphore>,
responses: Arc<Semaphore>,
hardware: Mutex<Option<(std::time::Instant, hardware::Hardware)>>,
}
impl Agent {
pub fn managed(token: String, profile: crate::managed_worker::Profile) -> Result<Self, String> {
let gateway = profile.gateway(token.clone())?;
let manager = crate::managed_worker::Manager::new(profile, gateway.clone())?;
Self::build(token, Some(gateway), Some(manager))
}
pub fn new(token: String, gateway: Option<Gateway>) -> Result<Self, String> {
Self::build(token, gateway, None)
}
fn build(
token: String,
gateway: Option<Gateway>,
manager: Option<crate::managed_worker::Manager>,
) -> Result<Self, String> {
if token.len() < 32 || token.len() > 4096 || !token.bytes().all(|b| b.is_ascii_graphic()) {
return Err("node credential must be 32..4096 printable ASCII bytes".into());
}
@@ -47,6 +60,9 @@ impl Agent {
if gateway.is_some() {
capabilities.push("responses.gateway.v1".into());
}
if manager.is_some() {
capabilities.push("worker.lifecycle.v1".into());
}
let (state, _) = watch::channel(Snapshot {
protocol_version: 1,
agent_epoch: uuid::Uuid::new_v4().to_string(),
@@ -57,6 +73,7 @@ impl Agent {
});
Ok(Self(Arc::new(Inner {
token,
manager,
router: gateway.map(|g| g.router()),
state,
observers: Arc::new(Semaphore::new(16)),
@@ -155,6 +172,41 @@ impl Drop for Active {
}
#[tonic::async_trait]
impl Node for Agent {
async fn worker_status(&self, r: Request<Empty>) -> Result<Response<WorkerState>, Status> {
self.auth(&r)?;
Ok(Response::new(
self.0
.manager
.as_ref()
.ok_or_else(|| Status::failed_precondition("no managed profile"))?
.state(),
))
}
async fn control_worker(
&self,
r: Request<WorkerCommand>,
) -> Result<Response<WorkerOperation>, Status> {
self.auth(&r)?;
self.0
.manager
.as_ref()
.ok_or_else(|| Status::failed_precondition("no managed profile"))?
.submit(r.into_inner())
.map(Response::new)
}
async fn operation_status(
&self,
r: Request<OperationQuery>,
) -> Result<Response<WorkerOperation>, Status> {
self.auth(&r)?;
self.0
.manager
.as_ref()
.ok_or_else(|| Status::failed_precondition("no managed profile"))?
.operation(&r.get_ref().operation_id)
.map(Response::new)
}
async fn handshake(&self, r: Request<Hello>) -> Result<Response<Snapshot>, Status> {
self.auth(&r)?;
if r.get_ref().protocol_version != 1 {
@@ -221,6 +273,14 @@ impl Node for Agent {
r: Request<ResponseRequest>,
) -> Result<Response<Self::RespondStream>, Status> {
self.auth(&r)?;
if self
.0
.manager
.as_ref()
.is_some_and(|m| m.state().phase != "ready")
{
return Err(Status::unavailable("managed worker is not ready"));
}
if r.get_ref().json.len() > 2 * 1024 * 1024 {
return Err(Status::resource_exhausted("request exceeds 2 MiB"));
}
+475
View File
@@ -0,0 +1,475 @@
use std::{net::SocketAddr, time::Duration};
use strata_desktop_core::{
managed_worker::{Manager, Profile},
node::{self, proto::*},
};
use tokio::net::TcpListener;
const TOKEN: &str = "synthetic-lifecycle-test-token-32bytes";
const OUTPUT: &str =
r#"{"id":"resp_fixture","object":"response","status":"completed","output":[]}"#;
// Same Rust test executable becomes a real isolated backend child. No Python,
// GPU, model download, request capture or running user endpoint is involved.
#[test]
#[ignore]
fn fixture() {
let Ok(endpoint) = std::env::var("STRATA_WORKER_ENDPOINT") else {
return;
};
assert!(std::env::var("STRATA_NODE_TOKEN").is_err());
let model = std::env::var("STRATA_WORKER_MODEL").unwrap();
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async move {
let health_model = if model == "wrong" {
"unexpected".to_string()
} else {
model.clone()
};
let router = axum::Router::new()
.route(
"/health",
axum::routing::get(move || {
let model = health_model.clone();
async move {
axum::Json(
serde_json::json!({"status":"ok","loaded":true,"model":model}),
)
}
}),
)
.route(
"/v1/responses",
axum::routing::post(move || {
let slow = model == "slow";
async move {
if slow {
tokio::time::sleep(Duration::from_millis(600)).await;
}
(
[(axum::http::header::CONTENT_TYPE, "application/json")],
OUTPUT,
)
}
}),
)
.route(
"/exit",
axum::routing::get(|| async {
std::process::exit(7);
#[allow(unreachable_code)]
"exited"
}),
);
axum::serve(TcpListener::bind(endpoint).await.unwrap(), router)
.await
.unwrap();
});
}
async fn profile(model: &str) -> Profile {
let l = TcpListener::bind("127.0.0.1:0").await.unwrap();
let endpoint = l.local_addr().unwrap();
drop(l);
Profile {
schema_version: 1,
id: "fixture".into(),
model: model.into(),
executable: std::env::current_exe().unwrap(),
args: vec![
"--exact".into(),
"fixture".into(),
"--ignored".into(),
"--nocapture".into(),
],
endpoint,
startup_timeout_ms: 1500,
capabilities: vec!["responses".into()],
}
}
fn command(action: i32, grace: u32) -> WorkerCommand {
WorkerCommand {
operation_id: uuid::Uuid::new_v4().to_string(),
action,
drain_timeout_ms: grace,
}
}
async fn finish(m: &Manager, c: WorkerCommand) -> WorkerOperation {
let id = c.operation_id.clone();
m.submit(c).unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let s = m.operation(&id).unwrap();
if s.status == "succeeded" || s.status == "failed" {
break s;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap()
}
struct Server {
address: SocketAddr,
task: tokio::task::JoinHandle<()>,
}
impl Drop for Server {
fn drop(&mut self) {
self.task.abort();
}
}
async fn serve(p: Profile) -> Server {
let l = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = l.local_addr().unwrap();
let agent = node::Agent::managed(TOKEN.into(), p).unwrap();
Server {
address,
task: tokio::spawn(async move {
agent.serve(l, std::future::pending()).await.unwrap();
}),
}
}
fn req<T>(v: T) -> tonic::Request<T> {
node::authorized(v, TOKEN).unwrap()
}
async fn remote_finish(
c: &mut node_client::NodeClient<tonic::transport::Channel>,
op: WorkerCommand,
) -> WorkerOperation {
let id = op.operation_id.clone();
c.control_worker(req(op)).await.unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let op = c
.operation_status(req(OperationQuery {
operation_id: id.clone(),
}))
.await
.unwrap()
.into_inner();
if op.status == "succeeded" || op.status == "failed" {
break op;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap()
}
#[tokio::test]
async fn grpc_owned_start_stop_and_exact_response() {
let server = serve(profile("test").await).await;
let mut c = node::connect(server.address).await.unwrap();
assert_eq!(
c.worker_status(Empty {}).await.unwrap_err().code(),
tonic::Code::Unauthenticated
);
assert_eq!(
c.worker_status(req(Empty {}))
.await
.unwrap()
.into_inner()
.phase,
"stopped"
);
let input = ResponseRequest {
json: br#"{"model":"fixture","input":"synthetic","stream":false}"#.to_vec(),
};
assert_eq!(
c.respond(req(input.clone())).await.unwrap_err().code(),
tonic::Code::Unavailable
);
let op = command(1, 0);
assert_eq!(remote_finish(&mut c, op.clone()).await.status, "succeeded");
let state = c.worker_status(req(Empty {})).await.unwrap().into_inner();
assert_eq!(state.phase, "ready");
assert_ne!(state.pid, 0);
// Same operation ID survives transport disconnect without spawning twice.
drop(c);
let mut c = node::connect(server.address).await.unwrap();
assert_eq!(
c.control_worker(req(op.clone()))
.await
.unwrap()
.into_inner()
.status,
"succeeded"
);
assert_eq!(
c.worker_status(req(Empty {}))
.await
.unwrap()
.into_inner()
.pid,
state.pid
);
let mut conflict = op;
conflict.action = 2;
assert_eq!(
c.control_worker(req(conflict)).await.unwrap_err().code(),
tonic::Code::AlreadyExists
);
let mut frames = c.respond(req(input.clone())).await.unwrap().into_inner();
let mut data = vec![];
let mut end = false;
while let Some(frame) = frames.message().await.unwrap() {
match frame.payload.unwrap() {
response_frame::Payload::Data(b) => data.extend(b),
response_frame::Payload::End(_) => end = true,
response_frame::Payload::Headers(h) => assert_eq!(h.status, 200),
}
}
assert_eq!(data, OUTPUT.as_bytes());
assert!(end);
assert_eq!(
remote_finish(&mut c, command(2, 1000)).await.status,
"succeeded"
);
assert_eq!(
c.worker_status(req(Empty {}))
.await
.unwrap()
.into_inner()
.phase,
"stopped"
);
assert_eq!(
c.respond(req(input)).await.unwrap_err().code(),
tonic::Code::Unavailable
);
assert_eq!(
remote_finish(&mut c, command(1, 0)).await.status,
"succeeded"
);
let mut old = c
.respond(req(ResponseRequest {
json:
br#"{"model":"fixture","input":"synthetic","previous_response_id":"resp_fixture"}"#
.to_vec(),
}))
.await
.unwrap()
.into_inner();
assert!(matches!(
old.message().await.unwrap().unwrap().payload,
Some(response_frame::Payload::Headers(ResponseHeaders {
status: 409,
..
}))
));
drop(old);
assert_eq!(
remote_finish(&mut c, command(2, 1000)).await.status,
"succeeded"
);
}
#[tokio::test]
async fn wrong_health_and_occupied_endpoint_fail_closed() {
let mut p = profile("wrong").await;
p.startup_timeout_ms = 300;
let g = p.gateway(TOKEN.into()).unwrap();
let m = Manager::new(p, g).unwrap();
assert_eq!(finish(&m, command(1, 0)).await.reason, "startup_timeout");
assert_eq!(m.state().pid, 0);
let p = profile("test").await;
let held = TcpListener::bind(p.endpoint).await.unwrap();
let m = Manager::new(p.clone(), p.gateway(TOKEN.into()).unwrap()).unwrap();
assert_eq!(finish(&m, command(1, 0)).await.reason, "endpoint_occupied");
assert_eq!(m.state().pid, 0);
assert!(
tokio::net::TcpStream::connect(held.local_addr().unwrap())
.await
.is_ok()
);
}
#[tokio::test]
async fn unexpected_child_exit_closes_admission_and_can_restart() {
let p = profile("test").await;
let m = Manager::new(p.clone(), p.gateway(TOKEN.into()).unwrap()).unwrap();
assert_eq!(finish(&m, command(1, 0)).await.status, "succeeded");
let _ = reqwest::get(format!("http://{}/exit", p.endpoint)).await;
tokio::time::timeout(Duration::from_secs(2), async {
while m.state().phase != "failed" {
tokio::time::sleep(Duration::from_millis(20)).await;
}
})
.await
.unwrap();
assert_eq!(m.state().reason, "worker_exited");
assert_eq!(finish(&m, command(1, 0)).await.status, "succeeded");
assert_eq!(finish(&m, command(2, 0)).await.status, "succeeded");
}
#[tokio::test]
async fn stop_timeout_does_not_kill_active_request() {
let server = serve(profile("slow").await).await;
let mut c = node::connect(server.address).await.unwrap();
assert_eq!(
remote_finish(&mut c, command(1, 0)).await.status,
"succeeded"
);
let mut response_client = c.clone();
let request = tokio::spawn(async move {
let mut stream = response_client
.respond(req(ResponseRequest {
json: br#"{"model":"fixture","input":"synthetic","stream":false}"#.to_vec(),
}))
.await
.unwrap()
.into_inner();
let mut data = vec![];
while let Some(f) = stream.message().await.unwrap() {
if let Some(response_frame::Payload::Data(b)) = f.payload {
data.extend(b)
}
}
data
});
tokio::time::timeout(Duration::from_secs(2), async {
loop {
if c.handshake(req(Hello {
protocol_version: 1,
}))
.await
.unwrap()
.into_inner()
.active_responses
== 1
{
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
// Give the request time to acquire its lease before draining.
tokio::time::sleep(Duration::from_millis(50)).await;
assert_eq!(
remote_finish(&mut c, command(2, 0)).await.reason,
"drain_timeout"
);
assert_ne!(
c.worker_status(req(Empty {}))
.await
.unwrap()
.into_inner()
.pid,
0
);
assert_eq!(request.await.unwrap(), OUTPUT.as_bytes());
assert_eq!(
remote_finish(&mut c, command(2, 1000)).await.status,
"succeeded"
);
}
#[tokio::test]
async fn cli_profile_start_status_stop_and_node_drop_cleanup() {
use tokio::io::{AsyncBufReadExt, BufReader};
let p = profile("test").await;
let path = std::env::temp_dir().join(format!("strata-profile-{}.json", uuid::Uuid::new_v4()));
struct FileGuard(std::path::PathBuf);
impl Drop for FileGuard {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
let _file = FileGuard(path.clone());
std::fs::write(
&path,
serde_json::to_vec(&serde_json::json!({
"schema_version":1,"id":p.id,"model":p.model,"executable":p.executable,"args":p.args,
"endpoint":p.endpoint,"startup_timeout_ms":p.startup_timeout_ms
}))
.unwrap(),
)
.unwrap();
let mut node = tokio::process::Command::new(env!("CARGO_BIN_EXE_strata-desktop"))
.args([
"node",
"--listen",
"127.0.0.1:0",
"--token-env",
"STRATA_NODE_TOKEN",
"--worker-profile",
])
.arg(&path)
.env("STRATA_NODE_TOKEN", TOKEN)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.kill_on_drop(true)
.spawn()
.unwrap();
let mut lines = BufReader::new(node.stdout.take().unwrap()).lines();
let line = tokio::time::timeout(Duration::from_secs(5), lines.next_line())
.await
.unwrap()
.unwrap()
.unwrap();
let address = serde_json::from_str::<serde_json::Value>(&line).unwrap()["endpoint"]
.as_str()
.unwrap()
.trim_start_matches("http://")
.to_string();
async fn cli(address: &str, action: &[&str]) -> serde_json::Value {
let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_strata-desktop"));
command
.args([
"worker",
"--node",
address,
"--token-env",
"STRATA_NODE_TOKEN",
])
.args(action)
.env("STRATA_NODE_TOKEN", TOKEN)
.kill_on_drop(true);
let output = tokio::time::timeout(Duration::from_secs(5), command.output())
.await
.unwrap()
.unwrap();
assert!(output.status.success(), "CLI action failed");
serde_json::from_slice(&output.stdout).unwrap()
}
assert_eq!(cli(&address, &["status"]).await["phase"], "stopped");
let id = uuid::Uuid::new_v4().to_string();
assert_eq!(cli(&address, &["start", &id]).await["operation_id"], id);
let mut c = node::connect(address.parse().unwrap()).await.unwrap();
assert_eq!(
remote_finish(
&mut c,
WorkerCommand {
operation_id: id.clone(),
action: 1,
drain_timeout_ms: 0
}
)
.await
.status,
"succeeded"
);
assert_eq!(
cli(&address, &["operation", &id]).await["status"],
"succeeded"
);
assert_eq!(cli(&address, &["status"]).await["phase"], "ready");
let id = uuid::Uuid::new_v4().to_string();
cli(&address, &["stop", &id]).await;
assert_eq!(
remote_finish(
&mut c,
WorkerCommand {
operation_id: id,
action: 2,
drain_timeout_ms: 30000
}
)
.await
.status,
"succeeded"
);
node.kill().await.unwrap();
node.wait().await.unwrap();
assert!(TcpListener::bind(p.endpoint).await.is_ok());
}