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>
This commit is contained in:
Pavlo Ratushnyi
2026-10-16 03:00:55 +02:00
co-authored by Claude Sonnet 5.5
parent 26574ae3e7
commit 0ca493be04
14 changed files with 471 additions and 2 deletions
+4 -2
View File
@@ -1285,7 +1285,9 @@ pub async fn create(
let usage = Usage {
input_tokens: done.prompt_tokens,
output_tokens: done.generated,
reasoning_tokens,
// Counted from the ids that were decoded; a text-level engine reports its own total, which
// this count must never exceed (equal on the stdio wire, where each id is one T line).
reasoning_tokens: reasoning_tokens.min(done.generated),
cached_tokens: done.reused.unwrap_or(0),
};
match ResponseTrace::build_with_terminal(
@@ -2240,7 +2242,7 @@ fn stream_live_buffered(
Usage {
input_tokens: done.prompt_tokens,
output_tokens: done.generated,
reasoning_tokens,
reasoning_tokens: reasoning_tokens.min(done.generated),
cached_tokens: done.reused.unwrap_or(0),
},
&id,
+358
View File
@@ -0,0 +1,358 @@
//! 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(())
}
+1
View File
@@ -106,6 +106,7 @@ done
assert all('usage' not in e for e in events)
return chunks
env = fixture.runtime_stack(env, root) # no-op unless STRATA_TEST_FAKE_RUNTIME is set
with tempfile.TemporaryFile() as logs:
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True)
try:
+1
View File
@@ -64,6 +64,7 @@ done
conn.close()
return status, data
env = fixture.runtime_stack(env, root) # no-op unless STRATA_TEST_FAKE_RUNTIME is set
with tempfile.TemporaryFile() as logs:
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True)
try:
+1
View File
@@ -80,6 +80,7 @@ done
return data
payload = {'model': 'fixture', 'input': 'Привіт 🌍', 'max_output_tokens': 8, 'reasoning': {'effort': 'none'}}
env = fixture.runtime_stack(env, root) # no-op unless STRATA_TEST_FAKE_RUNTIME is set
with tempfile.TemporaryFile() as logs:
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs)
try:
+1
View File
@@ -153,6 +153,7 @@ done
tool = {'name': 'lookup', 'input_schema': {'type': 'object', 'properties': {'key': {'type': 'string'}}}}
native_tool = {'type': 'function', 'name': 'lookup', 'parameters': tool['input_schema']}
tool_text = '<tool_call>\n<function=lookup>\n<parameter=key>\nvalue\n</parameter>\n</function>\n</tool_call>'
env = fixture.runtime_stack(env, root) # no-op unless STRATA_TEST_FAKE_RUNTIME is set
with tempfile.TemporaryFile() as logs:
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True)
try:
+1
View File
@@ -75,6 +75,7 @@ done
assert process.poll() is None and time.monotonic() < deadline, 'condition timed out'
time.sleep(0.02)
env = fixture.runtime_stack(env, root) # no-op unless STRATA_TEST_FAKE_RUNTIME is set
with tempfile.TemporaryFile() as logs:
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True)
conn = None
+1
View File
@@ -60,6 +60,7 @@ done
connection.close()
response_payload = {'model': 'strata-local', 'input': 'Hello', 'reasoning': {'effort': 'none'}}
env = fixture.runtime_stack(env, root) # no-op unless STRATA_TEST_FAKE_RUNTIME is set
with tempfile.TemporaryFile() as logs:
runtime = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True)
try:
+1
View File
@@ -80,6 +80,7 @@ done
assert code == 200, result
return result
env = fixture.runtime_stack(env, root) # no-op unless STRATA_TEST_FAKE_RUNTIME is set
with tempfile.TemporaryFile() as logs:
def start():
proc = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs)
+1
View File
@@ -101,6 +101,7 @@ while True:
assert 13 <= time.monotonic() - started < 22, (kind, 'idle interval')
return body.decode()
env = fixture.runtime_stack(env, root) # no-op unless STRATA_TEST_FAKE_RUNTIME is set
with tempfile.TemporaryFile() as logs:
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs,
start_new_session=True)
+1
View File
@@ -139,6 +139,7 @@ done
(allow_empty, True, custom_call, 1, False, 'stop', False, 0),
(allow_empty, True, 'OK', 0, True, 'length', False, 0),
])
env = fixture.runtime_stack(env, root) # no-op unless STRATA_TEST_FAKE_RUNTIME is set
with tempfile.TemporaryFile() as logs:
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True)
try:
+43
View File
@@ -36,6 +36,49 @@ def tokenizer(root):
(root / "merges.txt").write_text("")
def runtime_stack(env, root):
"""Test-only. With STRATA_TEST_FAKE_RUNTIME=<path of the fake_runtime example> in the environment, run
this script's scripted stdio engine behind the Rust runtime stack instead of as strata-next's own
child: strata-next (runtime backend) -> gRPC -> fake_runtime -> the same engine.sh. The fake runtime
ends when this process does (it exits when its stdin closes). Without the variable `env` is returned
unchanged, so every script that calls this keeps its original meaning.
Used by the smokes whose assertions do not depend on strata-next owning the engine process:
test-live-responses-replay, smoke-{custom-tools,chat-completions,messages,tool-policy,input-tokens,
response-history,sse-keepalive,native-drain,queue-deadline}. Not by smoke-worker-cancel (a wedged engine
ends the stdio supervisor; the runtime backend re-attaches instead), smoke-signal-drain (expects QUIT
on the engine's stdin) or smoke-generation-deadline."""
fake = os.environ.get("STRATA_TEST_FAKE_RUNTIME")
if not fake:
return env
env = dict(env)
engine = env.pop("STRATA_ENGINE_EXE")
arguments = json.loads(env.pop("STRATA_ENGINE_ARGS_JSON", "[]"))
directory = env.pop("STRATA_TOKENIZER_DIR")
env.pop("STRATA_MAX_WORKER_RESTARTS", None)
env.pop("STRATA_STARTUP_TIMEOUT_S", None)
token = "fixture-runtime-credential-" + os.urandom(8).hex()
command = [fake, "--listen", "127.0.0.1:0", "--token-env", "FAKE_RUNTIME_TOKEN",
"--engine", engine, "--tokenizer", directory]
for argument in arguments:
command += ["--engine-arg", argument]
child = subprocess.Popen(command, env={"PATH": os.defpath, "FAKE_RUNTIME_TOKEN": token},
stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
line = child.stdout.readline()
assert line.startswith("LISTENING "), "the fake runtime did not start: " + line
address = line.split()[1]
config = pathlib.Path(root) / "runtime-config.json"
config.write_text(json.dumps({"runtime": {
"address": address, "token_env": "FAKE_RUNTIME_TOKEN", "tokenizer_dir": str(directory),
"model": {"family": "fixture_family", "architecture": "fixture_arch",
"weight_format": "fixture:stdio", "artifact_digest": "sha256:" + "c" * 64},
"mode": {"type": "native"}, "max_context": 262144, "attach_retry_s": 0.05,
"health_interval_s": 0.2}}))
env["STRATA_CONFIG"] = str(config)
env["FAKE_RUNTIME_TOKEN"] = token
return env
def main():
binary = pathlib.Path(sys.argv[1]).resolve()
recovery = len(sys.argv) == 3 and sys.argv[2] == "--restart"
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""Run the repository's scripted-engine HTTP smokes through the Rust runtime stack.
cargo build -p strata-control --bin strata-next
cargo build -p strata-desktop-core --example fake_runtime
python3 scripts/test-api-over-runtime.py target/debug/strata-next target/debug/examples/fake_runtime
Each smoke keeps its own assertions; only the engine moves. Normally the smoke's scripted `engine.sh` is
strata-next's child process speaking token ids on stdio. With STRATA_TEST_FAKE_RUNTIME set (done here) the
smoke starts `fake_runtime` instead: a real `leleka.runtime.v1` gRPC server (`RuntimeServer`) whose engine
is the same `engine.sh`, and runs `strata-next` with a `runtime` block, so the HTTP API is exercised in
front of text-in/text-out gRPC. Test tooling only; nothing here is part of serving. Not a GPU or model result.
"""
import os
from pathlib import Path
import subprocess
import sys
import time
SMOKES = [
'test-live-responses-replay', # replay driver: SSE verifier, tool episode, corrupted-stream rejection
'smoke-custom-tools',
'smoke-chat-completions',
'smoke-messages',
'smoke-tool-policy', # 216 tool_choice / parallel_tool_calls / allowed_tools cases
'smoke-input-tokens',
'smoke-response-history', # stored responses, previous_response_id, restart of strata-next
'smoke-sse-keepalive',
'smoke-native-drain',
'smoke-queue-deadline',
]
def main():
if len(sys.argv) != 3:
sys.exit(__doc__)
binary, fake = (str(Path(arg).resolve()) for arg in sys.argv[1:])
scripts = Path(__file__).parent
env = dict(os.environ, STRATA_TEST_FAKE_RUNTIME=fake)
failed = []
for name in SMOKES:
started = time.monotonic()
result = subprocess.run([sys.executable, str(scripts / f'{name}.py'), binary], env=env,
capture_output=True, text=True, timeout=900)
seconds = time.monotonic() - started
print(f"{'PASS' if result.returncode == 0 else 'FAIL'} {name} ({seconds:.1f}s)", flush=True)
if result.returncode != 0:
failed.append(name)
print(result.stdout[-2000:], result.stderr[-2000:], sep='\n')
if failed:
sys.exit(f'{len(failed)} of {len(SMOKES)} failed: {", ".join(failed)}')
print(f'all {len(SMOKES)} smokes passed through the runtime stack')
if __name__ == '__main__':
main()
+1
View File
@@ -69,6 +69,7 @@ done
'tool_results': ['CONFIRMED-731'], 'expect': [{'type': 'text', 'text': 'CONFIRMED-731'}]}]}
suite = root / 'episode.json'
suite.write_text(json.dumps(episode))
env = fixture.runtime_stack(env, root) # no-op unless STRATA_TEST_FAKE_RUNTIME is set
with tempfile.TemporaryFile() as logs:
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True)
try: