Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(python-server): add Python server runtime for executing user code

Steven Enamakel2598125634cf
diff --git a/crates/openhuman-core/src/runtime/python_server/mod.rs b/crates/openhuman-core/src/runtime/python_server/mod.rs
index 8253f3a445..e00e7813a5 100644
--- a/crates/openhuman-core/src/runtime/python_server/mod.rs
+++ b/crates/openhuman-core/src/runtime/python_server/mod.rs
@@ -5,11 +5,9 @@
//! Rust callers over a private JSONL stdio protocol.
pub mod kompress;
-pub mod protocol;
pub mod registry;
pub mod server;
pub mod spacy;
-pub mod types;
pub use kompress::{ensure_kompress, kompress_provisioned, request_kompress, KompressResponse};
pub use registry::{enabled_backends, RuntimePythonBackend};
@@ -17,4 +15,4 @@ pub use server::{ensure_started, status, RuntimePythonServer};
pub use spacy::{
ensure_spacy, extract as extract_spacy, spacy_provisioned, SpacyResponse, SPACY_MODEL,
};
-pub use types::{BackendStatus, RuntimePythonServerStatus};
+pub use tinyruntime_pyserver::{BackendStatus, ServerStatus as RuntimePythonServerStatus};
diff --git a/crates/openhuman-core/src/runtime/python_server/protocol.rs b/crates/openhuman-core/src/runtime/python_server/protocol.rs
deleted file mode 100644
index 704e452086..0000000000
--- a/crates/openhuman-core/src/runtime/python_server/protocol.rs
+++ /dev/null
@@ -1,45 +0,0 @@
-use serde::{Deserialize, Serialize};
-use serde_json::Value;
-
-pub const PROTOCOL_VERSION: u32 = 1;
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct ReadyLine {
- #[serde(default)]
- pub ready: bool,
- #[serde(default)]
- pub protocol: Option<u32>,
- #[serde(default)]
- pub backends: Vec<String>,
- #[serde(default)]
- pub error: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct PythonServerRequest {
- pub id: String,
- pub method: String,
- #[serde(default)]
- pub params: Value,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct PythonServerError {
- pub code: String,
- pub message: String,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct PythonServerResponse {
- pub id: Option<String>,
- #[serde(default)]
- pub ok: bool,
- #[serde(default)]
- pub result: Option<Value>,
- #[serde(default)]
- pub error: Option<PythonServerError>,
-}
-
-#[cfg(test)]
-#[path = "protocol_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/runtime/python_server/protocol_tests.rs b/crates/openhuman-core/src/runtime/python_server/protocol_tests.rs
deleted file mode 100644
index 103a1243d0..0000000000
--- a/crates/openhuman-core/src/runtime/python_server/protocol_tests.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-use super::*;
-
-#[test]
-fn ready_line_parses() {
- let ready: ReadyLine =
- serde_json::from_str(r#"{"ready":true,"protocol":1,"backends":["spacy"]}"#).unwrap();
- assert!(ready.ready);
- assert_eq!(ready.protocol, Some(PROTOCOL_VERSION));
- assert_eq!(ready.backends, vec!["spacy"]);
-}
-
-#[test]
-fn response_parses_error_envelope() {
- let response: PythonServerResponse = serde_json::from_str(
- r#"{"id":"7","ok":false,"error":{"code":"bad_request","message":"missing text"}}"#,
- )
- .unwrap();
- assert!(!response.ok);
- assert_eq!(response.id.as_deref(), Some("7"));
- assert_eq!(response.error.unwrap().code, "bad_request");
-}
diff --git a/crates/openhuman-core/src/runtime/python_server/server.py b/crates/openhuman-core/src/runtime/python_server/server.py
deleted file mode 100644
index 7015d7f0a5..0000000000
--- a/crates/openhuman-core/src/runtime/python_server/server.py
+++ /dev/null
@@ -1,229 +0,0 @@
-#!/usr/bin/env python3
-"""OpenHuman runtime Python server.
-
-Private JSONL stdio protocol. Rust owns the process and sends one compact JSON
-request per line. This server keeps expensive Python backends warm for the
-life of the Rust core process.
-
-Enabled backends are passed via the OPENHUMAN_RPS_BACKENDS env var (comma
-separated, e.g. "spacy,kompress"). Each backend lazy- or eager-loads its model
-as appropriate; spaCy loads at startup (fast), Kompress (torch/ModernBERT)
-loads on first request so a missing/slow model never blocks the handshake.
-"""
-
-import json
-import os
-import re
-import sys
-
-PROTOCOL = 1
-SPACY_MODEL = "en_core_web_sm"
-
-_BACKENDS = [
- b.strip()
- for b in os.environ.get("OPENHUMAN_RPS_BACKENDS", "spacy").split(",")
- if b.strip()
-]
-
-_spacy_nlp = None
-
-# Kompress (ModernBERT) lazy-loaded state.
-_kompress_tok = None
-_kompress_model = None
-_KOMPRESS_MODEL = os.environ.get("OPENHUMAN_RPS_KOMPRESS_MODEL", "answerdotai/ModernBERT-base")
-_KOMPRESS_DEVICE = os.environ.get("OPENHUMAN_RPS_KOMPRESS_DEVICE", "cpu")
-_KOMPRESS_TARGET_RATIO = float(os.environ.get("OPENHUMAN_RPS_KOMPRESS_TARGET_RATIO", "0.5"))
-_KOMPRESS_MAX_INPUT = int(os.environ.get("OPENHUMAN_RPS_KOMPRESS_MAX_INPUT_CHARS", "200000"))
-
-
-def _emit(obj):
- sys.stdout.write(json.dumps(obj, ensure_ascii=False, separators=(",", ":")))
- sys.stdout.write("\n")
- sys.stdout.flush()
-
-
-def _error(req_id, code, message):
- return {"id": req_id, "ok": False, "error": {"code": code, "message": str(message)}}
-
-
-def _configure_stdio():
- if hasattr(sys.stdin, "reconfigure"):
- sys.stdin.reconfigure(encoding="utf-8")
- if hasattr(sys.stdout, "reconfigure"):
- sys.stdout.reconfigure(encoding="utf-8")
-
-
-# ── spaCy backend ────────────────────────────────────────────────────────
-
-
-def _load_spacy():
- global _spacy_nlp
- if _spacy_nlp is not None:
- return _spacy_nlp
-
- import spacy
-
- try:
- _spacy_nlp = spacy.load(SPACY_MODEL, disable=["parser"])
- except Exception:
- _spacy_nlp = spacy.load(SPACY_MODEL)
- return _spacy_nlp
-
-
-def _spacy_extract(params):
- text = (params or {}).get("text") or ""
- nlp = _load_spacy()
- doc = nlp(text)
- entities = [
- {
- "text": ent.text,
- "label": ent.label_,
- "start": int(ent.start_char),
- "end": int(ent.end_char),
- }
- for ent in doc.ents
- ]
- seen = set()
- nouns = []
- for tok in doc:
- if tok.pos_ in ("NOUN", "PROPN") and not tok.is_stop and tok.is_alpha:
- key = (tok.lemma_ or tok.text).lower().strip()
- if len(key) >= 2 and key not in seen:
- seen.add(key)
- nouns.append(key)
- return {"entities": entities, "nouns": nouns}
-
-
-# ── Kompress backend (ModernBERT salience compressor) ────────────────────
-
-_SENT_RE = re.compile(r"(?<=[.!?])\s+|\n+")
-
-
-def _pick_device():
- if _KOMPRESS_DEVICE != "auto":
- return _KOMPRESS_DEVICE
- try:
- import torch
-
- if torch.cuda.is_available():
- return "cuda"
- if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
- return "mps"
- except Exception:
- pass
- return "cpu"
-
-
-def _load_kompress():
- global _kompress_tok, _kompress_model
- if _kompress_model is not None:
- return
- import torch # noqa: F401
- from transformers import AutoModel, AutoTokenizer
-
- device = _pick_device()
- _kompress_tok = AutoTokenizer.from_pretrained(_KOMPRESS_MODEL)
- _kompress_model = AutoModel.from_pretrained(_KOMPRESS_MODEL).to(device)
- _kompress_model.eval()
- _kompress_model._oh_device = device
-
-
-def _split_sentences(text):
- parts = [p.strip() for p in _SENT_RE.split(text)]
- return [p for p in parts if p]
-
-
-def _kompress_compress(params):
- params = params or {}
- text = params.get("text") or ""
- target_ratio = float(params.get("target_ratio", _KOMPRESS_TARGET_RATIO))
- max_input = int(params.get("max_input_chars", _KOMPRESS_MAX_INPUT))
- if len(text) > max_input:
- text = text[:max_input]
-
- sentences = _split_sentences(text)
- if len(sentences) <= 3:
- return {"compressed_text": text, "input_chars": len(text), "output_chars": len(text)}
-
- _load_kompress()
- import torch
-
- device = getattr(_kompress_model, "_oh_device", "cpu")
- with torch.no_grad():
- enc = _kompress_tok(
- sentences,
- return_tensors="pt",
- padding=True,
- truncation=True,
- max_length=128,
- ).to(device)
- out = _kompress_model(**enc)
- mask = enc["attention_mask"].unsqueeze(-1).float()
- summed = (out.last_hidden_state * mask).sum(dim=1)
- counts = mask.sum(dim=1).clamp(min=1.0)
- emb = summed / counts
- doc_mean = emb.mean(dim=0, keepdim=True)
- salience = (emb - doc_mean).norm(dim=1)
-
- n_keep = max(3, int(round(len(sentences) * target_ratio)))
- if n_keep >= len(sentences):
- out_text = text
- else:
- order = salience.argsort(descending=True).tolist()
- keep_idx = sorted(order[:n_keep])
- out_text = " ".join(sentences[i] for i in keep_idx)
-
- return {
- "compressed_text": out_text,
- "input_chars": len(text),
- "output_chars": len(out_text),
- }
-
-
-# ── Dispatch ─────────────────────────────────────────────────────────────
-
-
-def _handle(req):
- req_id = req.get("id")
- method = req.get("method")
- params = req.get("params") or {}
- if method == "spacy.extract":
- return {"id": req_id, "ok": True, "result": _spacy_extract(params)}
- if method == "kompress.compress":
- return {"id": req_id, "ok": True, "result": _kompress_compress(params)}
- return _error(req_id, "unknown_method", f"unknown runtime_python_server method: {method}")
-
-
-def main():
- _configure_stdio()
- # Eager-load only the cheap, fast backends at startup. Kompress (torch) is
- # lazy-loaded on first request so a heavy import never blocks the handshake.
- try:
- if "spacy" in _BACKENDS:
- _load_spacy()
- except Exception as exc:
- _emit({"ready": False, "error": f"{type(exc).__name__}: {exc}"})
- return 1
-
- _emit({"ready": True, "protocol": PROTOCOL, "backends": _BACKENDS})
- for line in sys.stdin:
- line = line.strip()
- if not line:
- continue
- try:
- req = json.loads(line)
- except Exception as exc:
- _emit(_error(None, "bad_json", exc))
- continue
- if not isinstance(req, dict):
- _emit(_error(None, "bad_request", "request must be a JSON object"))
- continue
- try:
- _emit(_handle(req))
- except Exception as exc:
- _emit(_error(req.get("id"), type(exc).__name__, exc))
- return 0
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/crates/openhuman-core/src/runtime/python_server/server.rs b/crates/openhuman-core/src/runtime/python_server/server.rs
index 4ce99ff037..334086791c 100644
--- a/crates/openhuman-core/src/runtime/python_server/server.rs
+++ b/crates/openhuman-core/src/runtime/python_server/server.rs
@@ -1,381 +1,47 @@
+//! Host side of the runtime Python server.
+//!
+//! The worker process itself (spawn, handshake, request/response, restart,
+//! idle expiry, startup back-off) lives in `tinyruntime-pyserver`. This file
+//! only maps `Config` and the managed interpreter onto a
+//! [`ServerLaunch`], and holds the process-wide slot.
+
use std::path::PathBuf;
-use std::sync::{Arc, OnceLock};
-use std::time::{Duration, Instant};
+use std::sync::Arc;
+use std::time::Duration;
-use anyhow::{bail, Context, Result};
-use serde::de::DeserializeOwned;
-use serde_json::{json, Value};
-use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines};
-use tokio::process::{Child, ChildStderr, ChildStdin, ChildStdout};
-use tokio::sync::Mutex;
+use anyhow::{bail, Result};
+use serde_json::json;
+use tinyruntime_pyserver::{IdleRule, PythonServer, ServerLaunch, ServerSlot, ServerStatus};
-use super::protocol::{PythonServerRequest, PythonServerResponse, ReadyLine, PROTOCOL_VERSION};
use super::registry::{enabled_backends, RuntimePythonBackend};
-use super::types::{BackendStatus, RuntimePythonServerStatus};
use crate::config::Config;
-use crate::runtime::python::process::PythonLaunchSpec;
-
-const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);
-/// Ceiling for a single backend request. spaCy extraction is sub-100ms; the
-/// Kompress (torch) backend can take seconds on CPU, so this is sized for the
-/// heavier backend (it's a max, not added latency for fast methods).
-const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
-const START_FAILURE_BACKOFF: Duration = Duration::from_secs(300);
-
-static SERVER: OnceLock<Mutex<ServerCache>> = OnceLock::new();
-
-fn server_slot() -> &'static Mutex<ServerCache> {
- SERVER.get_or_init(|| Mutex::new(ServerCache::Empty))
-}
-
-#[derive(Clone)]
-enum ServerCache {
- Empty,
- Ready(Arc<RuntimePythonServer>),
- Failed {
- message: String,
- retry_after: Instant,
- },
-}
-
-#[derive(Debug, Clone)]
-struct ServerLaunch {
- python_bin: PathBuf,
- script_path: PathBuf,
- backends: Vec<RuntimePythonBackend>,
- /// Extra environment for the worker (backend list + Kompress model/device/HF).
- env: Vec<(String, String)>,
-}
-
-struct ServerInner {
- _child: Child,
- stdin: ChildStdin,
- stdout: Lines<BufReader<ChildStdout>>,
- next_id: u64,
- ready_backends: Vec<String>,
-}
-
-fn drain_server_stderr(stderr: ChildStderr) {
- tokio::spawn(async move {
- let mut reader = BufReader::new(stderr);
- let mut buf = Vec::with_capacity(1024);
- let mut line_count = 0u64;
- let mut byte_count = 0u64;
-
- loop {
- buf.clear();
- match reader.read_until(b'\n', &mut buf).await {
- Ok(0) => {
- log::debug!(
- "[runtime_python_server] stderr drain closed lines={} bytes={}",
- line_count,
- byte_count
- );
- break;
- }
- Ok(n) => {
- line_count += 1;
- byte_count += n as u64;
- log::trace!(
- "[runtime_python_server] drained stderr line bytes={} total_lines={} total_bytes={}",
- n,
- line_count,
- byte_count
- );
- }
- Err(error) => {
- log::debug!(
- "[runtime_python_server] stderr drain failed after lines={} bytes={}: {error}",
- line_count,
- byte_count
- );
- break;
- }
- }
- }
- });
-}
-
-pub struct RuntimePythonServer {
- launch: ServerLaunch,
- inner: Mutex<Option<ServerInner>>,
- last_used: Mutex<Instant>,
-}
-
-impl RuntimePythonServer {
- async fn new(config: &Config) -> Result<Self> {
- let launch = prepare_launch(config).await?;
- Ok(Self {
- launch,
- inner: Mutex::new(None),
- last_used: Mutex::new(Instant::now()),
- })
- }
-
- pub async fn start(&self) -> Result<()> {
- let mut guard = self.inner.lock().await;
- if guard.is_some() {
- return Ok(());
- }
- let inner = spawn_inner(&self.launch).await?;
- *guard = Some(inner);
- Ok(())
- }
-
- pub async fn request<T>(&self, method: &str, params: Value) -> Result<T>
- where
- T: DeserializeOwned,
- {
- match self.request_once(method, params.clone()).await {
- Ok(value) => {
- self.mark_used().await;
- Ok(value)
- }
- Err(err) => {
- log::warn!(
- "[runtime_python_server] request failed; restarting server before retry: {err:#}"
- );
- self.reset().await;
- let value = self.request_once(method, params).await?;
- self.mark_used().await;
- Ok(value)
- }
- }
- }
-
- async fn request_once<T>(&self, method: &str, params: Value) -> Result<T>
- where
- T: DeserializeOwned,
- {
- let mut guard = self.inner.lock().await;
- if guard.is_none() {
- *guard = Some(spawn_inner(&self.launch).await?);
- }
- let inner = guard.as_mut().context("runtime python server missing")?;
- let id = inner.next_id.to_string();
- inner.next_id += 1;
-
- let request = PythonServerRequest {
- id: id.clone(),
- method: method.to_string(),
- params,
- };
- let mut line = serde_json::to_string(&request)?;
- line.push('\n');
- log::debug!(
- "[runtime_python_server] sending request id={} method={}",
- id,
- method
- );
- inner
- .stdin
- .write_all(line.as_bytes())
- .await
- .context("writing runtime python server request")?;
- inner
- .stdin
- .flush()
- .await
- .context("flushing runtime python server request")?;
-
- loop {
- let next = tokio::time::timeout(REQUEST_TIMEOUT, inner.stdout.next_line()).await;
- let line = match next {
- Ok(Ok(Some(line))) => line,
- Ok(Ok(None)) => bail!("runtime python server closed stdout"),
- Ok(Err(error)) => {
- return Err(error).context("reading runtime python server response")
- }
- Err(_) => bail!("runtime python server request timed out"),
- };
- let response: PythonServerResponse = match serde_json::from_str(&line) {
- Ok(response) => response,
- Err(error) => {
- log::warn!(
- "[runtime_python_server] unparseable response skipped: {error}; line_len={}",
- line.len()
- );
- continue;
- }
- };
- if response.id.as_deref() != Some(id.as_str()) {
- log::debug!(
- "[runtime_python_server] skipped response for different id={:?}",
- response.id
- );
- continue;
- }
- if !response.ok {
- let message = response
- .error
- .map(|error| format!("{}: {}", error.code, error.message))
- .unwrap_or_else(|| "unknown python server error".to_string());
- bail!("runtime python server `{method}` failed: {message}");
- }
- let result = response.result.unwrap_or(Value::Null);
- return serde_json::from_value(result)
- .with_context(|| format!("decoding runtime python server `{method}` result"));
- }
- }
-
- async fn reset(&self) {
- let mut guard = self.inner.lock().await;
- if let Some(mut inner) = guard.take() {
- if let Err(error) = inner._child.start_kill() {
- log::debug!("[runtime_python_server] failed to signal child shutdown: {error}");
- }
- }
- }
-
- async fn mark_used(&self) {
- *self.last_used.lock().await = Instant::now();
- }
- async fn kompress_idle_expired(&self, timeout: Duration) -> bool {
- self.launch
- .backends
- .contains(&RuntimePythonBackend::Kompress)
- && idle_timeout_expired(*self.last_used.lock().await, timeout)
- }
-
- fn status_from_inner(&self, inner: Option<&ServerInner>) -> RuntimePythonServerStatus {
- let running = inner.is_some();
- let ready_backends = inner
- .map(|inner| inner.ready_backends.as_slice())
- .unwrap_or(&[]);
- RuntimePythonServerStatus {
- enabled: true,
- running,
- backends: self
- .launch
- .backends
- .iter()
- .map(|backend| BackendStatus {
- id: backend.id().to_string(),
- enabled: true,
- ready: ready_backends.iter().any(|id| id == backend.id()),
- message: None,
- })
- .collect(),
- message: None,
- }
- }
-
- pub async fn status(&self) -> RuntimePythonServerStatus {
- let guard = self.inner.lock().await;
- self.status_from_inner(guard.as_ref())
- }
+/// A running worker process, as the rest of the core names it.
+pub type RuntimePythonServer = PythonServer;
- /// The backend set this server was launched for.
- pub fn backends(&self) -> &[RuntimePythonBackend] {
- &self.launch.backends
- }
-}
+static SLOT: ServerSlot = ServerSlot::new();
pub async fn ensure_started(config: &Config) -> Result<Arc<RuntimePythonServer>> {
- let mut guard = server_slot().lock().await;
- // If the enabled backend set changed since the server started (e.g. ML was
- // toggled on after a spaCy-only launch), the cached process can't serve the
- // new backend — it was never provisioned/launched for it. Rebuild instead of
- // reusing a stale launch.
- let requested_backends = enabled_backends(config);
- let cached = match &*guard {
- ServerCache::Ready(existing) => Some(existing.clone()),
- ServerCache::Empty | ServerCache::Failed { .. } => None,
+ let requested: Vec<String> = enabled_backends(config)
+ .iter()
+ .map(|backend| backend.id().to_string())
+ .collect();
+ let idle = IdleRule {
+ backend: RuntimePythonBackend::Kompress.id(),
+ timeout: Duration::from_secs(config.tokenjuice.ml_sidecar_idle_timeout_secs),
};
- if let Some(existing) = cached {
- if existing.backends() != requested_backends.as_slice() {
- log::info!(
- "[runtime_python_server] backend set changed ({:?} -> {:?}); rebuilding server",
- existing.backends(),
- requested_backends
- );
- existing.reset().await;
- *guard = ServerCache::Empty;
- } else {
- let idle_timeout = Duration::from_secs(config.tokenjuice.ml_sidecar_idle_timeout_secs);
- if existing.kompress_idle_expired(idle_timeout).await {
- log::info!(
- "[runtime_python_server] kompress backend idle for >= {:?}; rebuilding server",
- idle_timeout
- );
- existing.reset().await;
- *guard = ServerCache::Empty;
- }
- }
- }
- match &*guard {
- ServerCache::Ready(existing) => {
- let existing = existing.clone();
- if let Err(error) = existing.start().await {
- let message = format!("{error:#}");
- log::warn!(
- "[runtime_python_server] cached server failed to start; backing off: {message}"
- );
- *guard = ServerCache::Failed {
- message: message.clone(),
- retry_after: Instant::now() + START_FAILURE_BACKOFF,
- };
- bail!("runtime python server unavailable: {message}");
- }
- return Ok(existing);
- }
- ServerCache::Failed {
- message,
- retry_after,
- } if Instant::now() < *retry_after => {
- bail!("runtime python server unavailable after previous startup failure: {message}");
- }
- ServerCache::Failed { .. } | ServerCache::Empty => {}
- }
-
- match start_new_server(config).await {
- Ok(server) => {
- *guard = ServerCache::Ready(server.clone());
- Ok(server)
- }
- Err(error) => {
- let message = format!("{error:#}");
- log::warn!(
- "[runtime_python_server] startup failed; caching fallback state for {:?}: {message}",
- START_FAILURE_BACKOFF
- );
- *guard = ServerCache::Failed {
- message: message.clone(),
- retry_after: Instant::now() + START_FAILURE_BACKOFF,
- };
- bail!("runtime python server unavailable: {message}");
- }
- }
-}
-
-fn idle_timeout_expired(last_used: Instant, timeout: Duration) -> bool {
- last_used.elapsed() >= timeout
-}
-
-async fn start_new_server(config: &Config) -> Result<Arc<RuntimePythonServer>> {
- let server = Arc::new(RuntimePythonServer::new(config).await?);
- server.start().await?;
+ let server = SLOT
+ .ensure(&requested, Some(idle), async {
+ prepare_launch(config)
+ .await
+ .map_err(|error| tinyruntime_pyserver::Error::Prepare(format!("{error:#}")))
+ })
+ .await?;
Ok(server)
}
-pub async fn status() -> RuntimePythonServerStatus {
- let cached = {
- let guard = server_slot().lock().await;
- guard.clone()
- };
- match cached {
- ServerCache::Ready(server) => server.status().await,
- ServerCache::Failed { message, .. } => RuntimePythonServerStatus {
- enabled: true,
- running: false,
- backends: Vec::new(),
- message: Some(format!("runtime python server unavailable: {message}")),
- },
- ServerCache::Empty => {
- RuntimePythonServerStatus::disabled("runtime python server has not started")
- }
- }
+pub async fn status() -> ServerStatus {
+ SLOT.status().await
}
async fn prepare_launch(config: &Config) -> Result<ServerLaunch> {
@@ -420,12 +86,12 @@ async fn prepare_launch(config: &Config) -> Result<ServerLaunch> {
let script_path = write_server_script(config).await?;
- Ok(ServerLaunch {
+ Ok(ServerLaunch::new(
python_bin,
script_path,
- backends,
+ backends.iter().map(|b| b.id().to_string()).collect(),
env,
- })
+ ))
}
/// Environment the worker needs to load + run the Kompress model offline.
@@ -456,92 +122,7 @@ fn push_kompress_env(env: &mut Vec<(String, String)>, config: &Config, hf_home:
async fn write_server_script(config: &Config) -> Result<PathBuf> {
let root = super::spacy::python_server_cache_root(config);
- tokio::fs::create_dir_all(&root)
- .await
- .with_context(|| format!("creating runtime python server cache {}", root.display()))?;
- let script_path = root.join("runtime_python_server.py");
- tokio::fs::write(&script_path, include_str!("server.py"))
- .await
- .with_context(|| {
- format!(
- "writing runtime python server script {}",
- script_path.display()
- )
- })?;
- Ok(script_path)
-}
-
-async fn spawn_inner(launch: &ServerLaunch) -> Result<ServerInner> {
- log::info!(
- "[runtime_python_server] starting server python={} script={} backends={:?}",
- launch.python_bin.display(),
- launch.script_path.display(),
- launch.backends
- );
- let resolved = crate::runtime::python::ResolvedPython {
- bin_dir: launch
- .python_bin
- .parent()
- .map(PathBuf::from)
- .unwrap_or_else(|| PathBuf::from(".")),
- python_bin: launch.python_bin.clone(),
- version: "runtime-backend".to_string(),
- source: crate::runtime::python::PythonSource::Managed,
- };
- let mut spec = PythonLaunchSpec::new(launch.script_path.clone());
- for (key, value) in &launch.env {
- spec.env.insert(key.clone(), value.clone());
- }
- let mut child = crate::runtime::python::process::spawn_stdio_process(&resolved, &spec)
- .context("spawning runtime python server")?;
- let stdin = child
- .stdin
- .take()
- .context("runtime python server stdin missing")?;
- let stdout = child
- .stdout
- .take()
- .context("runtime python server stdout missing")?;
- if let Some(stderr) = child.stderr.take() {
- drain_server_stderr(stderr);
- } else {
- log::debug!("[runtime_python_server] stderr pipe missing; continuing without drain");
- }
- let mut lines = BufReader::new(stdout).lines();
-
- let ready_line = match tokio::time::timeout(HANDSHAKE_TIMEOUT, lines.next_line()).await {
- Ok(Ok(Some(line))) => line,
- Ok(Ok(None)) => bail!("runtime python server exited before readiness handshake"),
- Ok(Err(error)) => return Err(error).context("reading runtime python server handshake"),
- Err(_) => bail!("runtime python server readiness handshake timed out"),
- };
- let ready: ReadyLine = serde_json::from_str(&ready_line)
- .with_context(|| format!("parsing runtime python server ready line: {ready_line}"))?;
- if !ready.ready {
- bail!(
- "runtime python server failed to start: {}",
- ready.error.unwrap_or_else(|| "unknown".to_string())
- );
- }
- if ready.protocol != Some(PROTOCOL_VERSION) {
- bail!(
- "runtime python server protocol mismatch: expected {}, got {:?}",
- PROTOCOL_VERSION,
- ready.protocol
- );
- }
- log::info!(
- "[runtime_python_server] server ready backends={:?}",
- ready.backends
- );
-
- Ok(ServerInner {
- _child: child,
- stdin,
- stdout: lines,
- next_id: 0,
- ready_backends: ready.backends,
- })
+ Ok(tinyruntime_pyserver::write_script(&root).await?)
}
pub async fn request_spacy_extract(
@@ -549,9 +130,9 @@ pub async fn request_spacy_extract(
text: &str,
) -> Result<super::spacy::SpacyResponse> {
let server = ensure_started(config).await?;
- server
+ Ok(server
.request("spacy.extract", json!({ "text": text }))
- .await
+ .await?)
}
pub async fn request_kompress_compress(
@@ -559,7 +140,7 @@ pub async fn request_kompress_compress(
text: &str,
) -> Result<super::kompress::KompressResponse> {
let server = ensure_started(config).await?;
- server
+ Ok(server
.request(
"kompress.compress",
json!({
@@ -568,7 +149,7 @@ pub async fn request_kompress_compress(
"max_input_chars": config.tokenjuice.ml_max_input_chars,
}),
)
- .await
+ .await?)
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/runtime/python_server/server_tests.rs b/crates/openhuman-core/src/runtime/python_server/server_tests.rs
index b5aea1aaa8..350d7fcbc2 100644
--- a/crates/openhuman-core/src/runtime/python_server/server_tests.rs
+++ b/crates/openhuman-core/src/runtime/python_server/server_tests.rs
@@ -7,15 +7,3 @@ async fn prepare_launch_rejects_disabled_backends() {
let err = prepare_launch(&config).await.unwrap_err().to_string();
assert!(err.contains("no runtime python server backends enabled"));
}
-
-#[test]
-fn idle_timeout_expiry_uses_last_used_instant() {
- assert!(idle_timeout_expired(
- Instant::now() - Duration::from_secs(10),
- Duration::from_secs(5),
- ));
- assert!(!idle_timeout_expired(
- Instant::now(),
- Duration::from_secs(5),
- ));
-}
diff --git a/crates/openhuman-core/src/runtime/python_server/types.rs b/crates/openhuman-core/src/runtime/python_server/types.rs
deleted file mode 100644
index ad7459e798..0000000000
--- a/crates/openhuman-core/src/runtime/python_server/types.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct BackendStatus {
- pub id: String,
- pub enabled: bool,
- pub ready: bool,
- pub message: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct RuntimePythonServerStatus {
- pub enabled: bool,
- pub running: bool,
- pub backends: Vec<BackendStatus>,
- pub message: Option<String>,
-}
-
-impl RuntimePythonServerStatus {
- pub fn disabled(message: impl Into<String>) -> Self {
- Self {
- enabled: false,
- running: false,
- backends: Vec::new(),
- message: Some(message.into()),
- }
- }
-}