Files
leleka/desktop-core/examples/fake_runtime.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 0ca493be04 test: run the scripted-engine HTTP smokes through the runtime stack (fake_runtime over real gRPC)
fake_runtime is a leleka.runtime.v1 server (the real RuntimeServer) whose engine is the same
engine.sh the smokes already use; fixture.runtime_stack() swaps strata-next's engine child for
it when STRATA_TEST_FAKE_RUNTIME is set, otherwise nothing changes. scripts/test-api-over-runtime.py
runs the ten smokes whose assertions do not depend on strata-next owning the engine process.

The HTTP layer clamps reasoning_tokens to the engine-reported output total, which a text-level
engine's re-tokenized pieces can otherwise exceed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-16 03:00:55 +02:00

359 lines
13 KiB
Rust

//! A fake `leleka-inference` for end-to-end tests of the API stack without a GPU.
//!
//! It serves the real `leleka.runtime.v1` gRPC contract (`RuntimeServer`) but the engine behind it
//! is an existing *stdio token engine*: the scripted `engine.sh` programs the repository's smoke and
//! replay scripts already use (`scripts/smoke-*.py`, `scripts/test-live-responses-replay.py`). The
//! backend encodes the prompt it receives, sends the `GEN` line, and turns the engine's `T <id>`
//! lines back into UTF-8 text deltas, which is what the Rust engine's contract carries.
//!
//! ```text
//! fake_runtime --listen 127.0.0.1:PORT --token-env VAR --engine PATH --tokenizer DIR [--engine-arg A]...
//! ```
//!
//! It loads the model itself (as `leleka-cli load` would), then prints `LISTENING <addr>` on stdout
//! and serves until stdin closes or it is signalled. The model it claims is a fixture, not a model.
//! Test tooling only: it is not built into any shipped binary.
use std::{
io::{BufRead, BufReader, Write},
process::{Child, ChildStdin, Command, Stdio},
sync::{Arc, Mutex},
time::Duration,
};
use leleka_backend_api as api;
use leleka_runtime_client::{
client::RuntimeClient,
convert::{config_to_proto, descriptor_to_proto},
proto,
};
use strata_control::{
reasoning_budget::Utf8Stream,
tokenizer::Tokenizer,
wire::{self, Event, Finish, Generate},
};
use strata_desktop_core::runtime_rpc::RuntimeServer;
pub fn descriptor() -> api::ModelDescriptor {
api::ModelDescriptor {
family: "fixture_family".into(),
architecture: "fixture_arch".into(),
artifact_digest: format!("sha256:{}", "c".repeat(64)),
weight_format: "fixture:stdio".into(),
}
}
struct Active {
id: String,
}
struct StdioTokenBackend {
exe: String,
args: Vec<String>,
tokenizer: Arc<Tokenizer>,
child: Option<Arc<Mutex<Child>>>,
stdin: Option<Arc<Mutex<ChildStdin>>>,
lines: Option<Arc<Mutex<BufReader<std::process::ChildStdout>>>>,
ready: bool,
active: Arc<Mutex<Option<Active>>>,
}
fn failure(code: api::ErrorCode, message: &str) -> api::BackendError {
api::BackendError {
code,
message: message.to_owned(),
retryable: false,
}
}
impl api::Backend for StdioTokenBackend {
fn identity(&self) -> api::BackendIdentity {
api::BackendIdentity {
name: "fake-stdio-token-engine".into(),
implementation_version: "test".into(),
api_version: api::BACKEND_API_VERSION,
}
}
fn capabilities(&self) -> api::BackendCapabilities {
let d = descriptor();
api::BackendCapabilities {
supported_models: if self.ready {
vec![api::SupportedModelTuple {
family: d.family,
architecture: d.architecture,
weight_format: d.weight_format,
}]
} else {
Vec::new()
},
max_concurrent_generations: 1,
supports_cancellation: true,
supports_tool_call_streaming: false,
}
}
fn load(
&mut self,
model: api::ModelDescriptor,
config: api::RuntimeConfig,
) -> Result<api::LoadedModel, api::BackendError> {
if model != descriptor() {
return Err(failure(
api::ErrorCode::UnsupportedModel,
"unsupported model",
));
}
let mut child = Command::new(&self.exe)
.arg("--serve")
.args(&self.args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.map_err(|e| failure(api::ErrorCode::BackendUnavailable, &e.to_string()))?;
let stdin = child.stdin.take().expect("piped stdin");
let mut stdout = BufReader::new(child.stdout.take().expect("piped stdout"));
loop {
let mut line = String::new();
if stdout.read_line(&mut line).unwrap_or(0) == 0 {
return Err(failure(
api::ErrorCode::BackendUnavailable,
"engine exited before READY",
));
}
if line.starts_with("READY") {
break;
}
}
// The stand-in for leleka-inference *is* its engine: when the engine process dies, so does the
// fake runtime, as the real one would take its engine down with it.
let child = Arc::new(Mutex::new(child));
let watched = Arc::clone(&child);
std::thread::spawn(move || {
loop {
std::thread::sleep(Duration::from_millis(50));
if let Ok(Some(status)) = watched.lock().unwrap().try_wait() {
eprintln!("fake_runtime: the engine exited ({status}); exiting");
std::process::exit(2);
}
}
});
self.child = Some(child);
self.stdin = Some(Arc::new(Mutex::new(stdin)));
self.lines = Some(Arc::new(Mutex::new(stdout)));
self.ready = true;
Ok(api::LoadedModel {
handle: "fake-stdio-handle".into(),
descriptor: model,
load_config_version: config.load_config_version,
effective_mode: config.inference_mode,
mode_identity_digest: format!("sha256:{}", "d".repeat(64)),
})
}
fn start_generation(
&mut self,
_: &api::LoadedModel,
request: api::GenerationRequest,
) -> Result<api::GenerationStream, api::BackendError> {
let (Some(stdin), Some(lines)) = (self.stdin.clone(), self.lines.clone()) else {
return Err(failure(api::ErrorCode::BackendUnavailable, "not loaded"));
};
{
let mut active = self.active.lock().unwrap();
if active.is_some() {
return Err(failure(api::ErrorCode::ResourceExhausted, "busy"));
}
*active = Some(Active {
id: request.request_id.clone(),
});
}
let ids = self
.tokenizer
.encode(&request.prompt, true)
.map_err(|e| failure(api::ErrorCode::InvalidRequest, &e.to_string()))?;
let generate = Generate {
token_ids: ids,
max_new: request.max_output_tokens,
..Default::default()
};
let line = generate
.line()
.map_err(|e| failure(api::ErrorCode::InvalidRequest, e))?;
{
let mut pipe = stdin.lock().unwrap();
pipe.write_all(line.as_bytes())
.and_then(|()| pipe.flush())
.map_err(|e| failure(api::ErrorCode::BackendUnavailable, &e.to_string()))?;
}
let (sink, stream) = api::GenerationSink::channel();
let tokenizer = Arc::clone(&self.tokenizer);
let active = Arc::clone(&self.active);
std::thread::spawn(move || {
let stops = ["<|im_end|>", "<|endoftext|>"].map(|s| tokenizer.special_id(s));
let mut utf8 = Utf8Stream::default();
let mut reader = lines.lock().unwrap();
loop {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
*active.lock().unwrap() = None;
return; // the engine died: no terminal event
}
match wire::parse_line(&line) {
Ok(Some(Event::Token(id))) => {
if stops.contains(&Some(id)) {
continue; // the Rust engine never reports its stop token
}
let bytes = tokenizer.decode_bytes(&[id]).unwrap_or_default();
let text = utf8.push(&bytes);
if !text.is_empty()
&& sink.emit(api::GenerationEvent::TextDelta { text }).is_err()
{
*active.lock().unwrap() = None;
return;
}
}
Ok(Some(Event::Done(done))) => {
let tail = utf8.push(&[]);
if !tail.is_empty() {
let _ = sink.emit(api::GenerationEvent::TextDelta { text: tail });
}
*active.lock().unwrap() = None;
let usage = api::Usage {
input_tokens: done.prompt_tokens,
output_tokens: done.generated,
reused_input_tokens: done.reused.unwrap_or(0),
};
let _ = match done.finish {
Finish::Stop => sink.complete(api::FinishReason::Stop, usage),
Finish::Length => sink.complete(api::FinishReason::Length, usage),
Finish::Cancel => sink.cancel(),
};
return;
}
Ok(Some(Event::Error(message))) => {
*active.lock().unwrap() = None;
let _ = sink.fail(api::ErrorCode::Internal, message, false);
return;
}
Ok(Some(Event::PromptProgress { .. }) | None) => {}
Err(_) => {
*active.lock().unwrap() = None;
return;
}
}
}
});
Ok(stream)
}
fn cancel(&mut self, request_id: &str) -> Result<(), api::BackendError> {
if self.active.lock().unwrap().as_ref().map(|a| a.id.as_str()) != Some(request_id) {
return Err(failure(api::ErrorCode::InvalidRequest, "not active"));
}
let stdin = self.stdin.clone().expect("loaded");
let mut pipe = stdin.lock().unwrap();
pipe.write_all(b"STOP\n")
.and_then(|()| pipe.flush())
.map_err(|e| failure(api::ErrorCode::BackendUnavailable, &e.to_string()))
}
fn unload(&mut self, _: api::LoadedModel) -> Result<(), api::BackendError> {
self.ready = false;
if let Some(stdin) = &self.stdin {
let _ = stdin.lock().unwrap().write_all(b"QUIT\n");
}
Ok(())
}
}
impl Drop for StdioTokenBackend {
fn drop(&mut self) {
if let Some(child) = &self.child {
let mut child = child.lock().unwrap();
let _ = child.kill();
let _ = child.wait();
}
}
}
fn argument(args: &[String], name: &str) -> Option<String> {
args.iter()
.position(|a| a == name)
.and_then(|i| args.get(i + 1).cloned())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().skip(1).collect();
let listen = argument(&args, "--listen").unwrap_or_else(|| "127.0.0.1:0".into());
let token_env = argument(&args, "--token-env").ok_or("--token-env is required")?;
let token = std::env::var(&token_env)?;
let exe = argument(&args, "--engine").ok_or("--engine is required")?;
let tokenizer_dir = argument(&args, "--tokenizer").ok_or("--tokenizer is required")?;
let engine_args: Vec<String> = args
.iter()
.enumerate()
.filter(|(i, a)| a.as_str() == "--engine-arg" && *i + 1 < args.len())
.map(|(i, _)| args[i + 1].clone())
.collect();
let tokenizer = Arc::new(Tokenizer::from_assets(std::path::Path::new(
&tokenizer_dir,
))?);
let backend = StdioTokenBackend {
exe,
args: engine_args,
tokenizer,
child: None,
stdin: None,
lines: None,
ready: false,
active: Arc::new(Mutex::new(None)),
};
let server =
RuntimeServer::new(Box::new(backend), token.clone()).map_err(|e| e.message().to_owned())?;
let listener = tokio::net::TcpListener::bind(&listen).await?;
let address = listener.local_addr()?;
let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
let serving = tokio::spawn(async move {
let _ = server
.serve(listener, async {
let _ = stopped.await;
})
.await;
});
// What `leleka-cli load` does: one Load RPC for the current epoch.
let mut client = RuntimeClient::connect(address, token).await?;
let epoch = client.snapshot().await?.epoch;
client
.load(proto::LoadRequest {
operation_id: uuid::Uuid::new_v4().to_string(),
expected_epoch: epoch,
model: Some(descriptor_to_proto(&descriptor())),
config: Some(config_to_proto(&api::RuntimeConfig {
load_config_version: api::LOAD_CONFIG_VERSION,
inference_mode: api::InferenceMode::Native,
gpu_memory_limit_bytes: None,
allow_experimental: false,
})),
})
.await?;
while !client.snapshot().await?.model_ready {
tokio::time::sleep(Duration::from_millis(10)).await;
}
println!("LISTENING {address}");
std::io::stdout().flush()?;
// Serve until the parent closes our stdin or kills us.
tokio::task::spawn_blocking(|| {
let mut sink = String::new();
while std::io::stdin().read_line(&mut sink).unwrap_or(0) > 0 {
sink.clear();
}
})
.await?;
let _ = stop.send(());
let _ = tokio::time::timeout(Duration::from_secs(5), serving).await;
Ok(())
}