Files
leleka/crates/backend-api/src/scripted.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 60b48d8225 runtime reconfiguration: reopen the serve stack with new context/cache/resource settings without reloading the model
serve_tuning (settings document, validation, effective settings), Command::Reconfigure in the Original serve loop with rollback,
Backend::reconfigure, gRPC Runtime.Reconfigure, POST /v1/reconfigure, telemetry.settings; tests for each layer.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:01:53 +01:00

706 lines
24 KiB
Rust

//! A scripted in-process engine implementing [`Backend`], for tests that must exercise everything
//! above the engine without a GPU, a model or a gRPC server.
//!
//! It is compiled only with the `scripted` feature; production crates never enable it. It speaks
//! the same contract as the real backend: one generation at a time, one terminal event per
//! generation, `cancel` ends the running generation with `Terminal(Cancelled)`, a generation whose
//! receiver is dropped stops, and a stale or unloaded handle is refused. What it returns is
//! whatever the test scripted: it computes nothing and makes no statement about any model.
//!
//! Faults are first-class steps ([`Step::DropWithoutTerminal`], [`Step::Fail`], ...) and engine
//! restarts are simulated with [`ScriptedHandle::restart_engine`] so the callers' terminal-event
//! guarantees can be checked.
use std::{
collections::VecDeque,
sync::{
Arc, Mutex,
atomic::{AtomicBool, AtomicU64, Ordering},
},
thread,
time::{Duration, Instant},
};
use crate::{
Backend, BackendCapabilities, BackendError, BackendIdentity, ErrorCode, FinishReason,
GenerationEvent, GenerationRequest, GenerationSink, GenerationStream, GenerationTerminal,
LoadedModel, ModelDescriptor, RuntimeConfig, SupportedModelTuple, Usage,
};
/// One scripted action of a generation, played in order on the engine's own thread.
#[derive(Clone, Debug)]
pub enum Step {
/// A text delta (valid UTF-8, as the real backend guarantees).
Text(String),
/// A usage report that is not the terminal.
Usage(Usage),
/// A native tool-call delta (the real backend advertises none; for protocol-violation tests).
ToolCall {
index: u32,
id: Option<String>,
name: Option<String>,
arguments_delta: String,
},
/// Sleep, ending early when the generation is cancelled.
Pause(Duration),
/// Sleep and ignore cancellation, a dropped stream and an engine restart: a wedged engine.
Unresponsive(Duration),
/// Block until cancelled, then end with `Terminal(Cancelled)`.
AwaitCancel,
/// `Terminal(Completed)`.
Finish { reason: FinishReason, usage: Usage },
/// `Terminal(Failed)`.
Fail {
code: ErrorCode,
message: String,
retryable: bool,
},
/// `Terminal(Cancelled)` that nobody asked for.
CancelledUnasked,
/// The engine dies: the stream ends without a terminal event.
DropWithoutTerminal,
}
/// The scripted events of one generation.
#[derive(Clone, Debug, Default)]
pub struct Script {
steps: Vec<Step>,
}
impl Script {
pub fn new(steps: Vec<Step>) -> Self {
Self { steps }
}
/// The deltas, then a `Stop` terminal with the given usage.
pub fn stop_with(chunks: &[&str], usage: Usage) -> Self {
Self::finishing(chunks, FinishReason::Stop, usage)
}
/// The deltas, then a terminal with the given reason.
pub fn finishing(chunks: &[&str], reason: FinishReason, usage: Usage) -> Self {
let mut steps: Vec<Step> = chunks.iter().map(|c| Step::Text((*c).to_owned())).collect();
steps.push(Step::Finish { reason, usage });
Self { steps }
}
/// The deltas, then the engine dies.
pub fn dying_after(chunks: &[&str]) -> Self {
let mut steps: Vec<Step> = chunks.iter().map(|c| Step::Text((*c).to_owned())).collect();
steps.push(Step::DropWithoutTerminal);
Self { steps }
}
/// The deltas, then a failed terminal.
pub fn failing_after(chunks: &[&str], code: ErrorCode, message: &str) -> Self {
let mut steps: Vec<Step> = chunks.iter().map(|c| Step::Text((*c).to_owned())).collect();
steps.push(Step::Fail {
code,
message: message.to_owned(),
retryable: false,
});
Self { steps }
}
/// The deltas, then silence until the generation is cancelled.
pub fn hanging_after(chunks: &[&str]) -> Self {
let mut steps: Vec<Step> = chunks.iter().map(|c| Step::Text((*c).to_owned())).collect();
steps.push(Step::AwaitCancel);
Self { steps }
}
}
type Responder = Box<dyn FnMut(&GenerationRequest) -> Script + Send>;
struct Shared {
descriptor: ModelDescriptor,
ready: AtomicBool,
/// Bumped by every load and every simulated restart; a handle from an older epoch is stale.
epoch: AtomicU64,
/// Set by `restart_engine`: the running generation ends without a terminal event.
kill: AtomicBool,
/// The engine process is down: `load` is refused until `reload_engine`.
down: AtomicBool,
queue: Mutex<VecDeque<Script>>,
responder: Mutex<Option<Responder>>,
requests: Mutex<Vec<GenerationRequest>>,
cancels: Mutex<Vec<String>>,
loads: Mutex<Vec<(ModelDescriptor, RuntimeConfig)>>,
active: Mutex<Option<ActiveGeneration>>,
/// What `prefix_cache_summary` reports (a pool summary as JSON).
prefix_summary: Mutex<Option<String>>,
/// What `memory_report` reports (a memory-governor report as JSON).
memory_report: Mutex<Option<String>>,
/// The settings documents `reconfigure` has accepted, in order.
settings: Mutex<Vec<String>>,
}
struct ActiveGeneration {
id: String,
cancel: Arc<AtomicBool>,
}
/// The test's view of a [`ScriptedEngine`] that was moved into a worker or a server.
#[derive(Clone)]
pub struct ScriptedHandle {
shared: Arc<Shared>,
}
/// The engine. Implements [`Backend`]; keep a [`ScriptedHandle`] to script and observe it.
pub struct ScriptedEngine {
shared: Arc<Shared>,
}
impl ScriptedEngine {
/// An engine that is not loaded yet; `load` must be given exactly `descriptor`.
pub fn new(descriptor: ModelDescriptor) -> (Self, ScriptedHandle) {
let shared = Arc::new(Shared {
descriptor,
ready: AtomicBool::new(false),
epoch: AtomicU64::new(0),
kill: AtomicBool::new(false),
down: AtomicBool::new(false),
queue: Mutex::new(VecDeque::new()),
responder: Mutex::new(None),
requests: Mutex::new(Vec::new()),
cancels: Mutex::new(Vec::new()),
loads: Mutex::new(Vec::new()),
active: Mutex::new(None),
prefix_summary: Mutex::new(None),
memory_report: Mutex::new(None),
settings: Mutex::new(Vec::new()),
});
(
Self {
shared: shared.clone(),
},
ScriptedHandle { shared },
)
}
/// A valid descriptor for tests that do not care which model they name.
pub fn fixture_descriptor() -> ModelDescriptor {
ModelDescriptor {
family: "scripted_family".into(),
architecture: "scripted_arch".into(),
artifact_digest: format!("sha256:{}", "c".repeat(64)),
weight_format: "scripted:format".into(),
}
}
}
impl ScriptedHandle {
/// The next generation plays this script (FIFO).
pub fn push(&self, script: Script) {
self.shared.queue.lock().unwrap().push_back(script);
}
/// Every generation plays what `responder` returns for its request; the FIFO is used only
/// while no responder is installed.
pub fn respond_with(
&self,
responder: impl FnMut(&GenerationRequest) -> Script + Send + 'static,
) {
*self.shared.responder.lock().unwrap() = Some(Box::new(responder));
}
/// Every request accepted so far, in order.
pub fn requests(&self) -> Vec<GenerationRequest> {
self.shared.requests.lock().unwrap().clone()
}
/// The ids passed to `Backend::cancel`, in order.
pub fn cancels(&self) -> Vec<String> {
self.shared.cancels.lock().unwrap().clone()
}
pub fn loads(&self) -> Vec<(ModelDescriptor, RuntimeConfig)> {
self.shared.loads.lock().unwrap().clone()
}
/// The engine reports this prefix-cache summary (JSON) from now on; `None` = it has no such cache.
pub fn set_memory_report(&self, report: Option<String>) {
*self.shared.memory_report.lock().unwrap() = report;
}
pub fn set_prefix_summary(&self, summary: Option<String>) {
*self.shared.prefix_summary.lock().unwrap() = summary;
}
pub fn is_ready(&self) -> bool {
self.shared.ready.load(Ordering::Acquire)
}
pub fn is_generating(&self) -> bool {
self.shared.active.lock().unwrap().is_some()
}
/// The engine process dies: a running generation ends without a terminal event, the model is
/// no longer loaded and every handle issued before is stale.
pub fn restart_engine(&self) {
self.shared.kill.store(true, Ordering::Release);
self.shared.down.store(true, Ordering::Release);
self.shared.ready.store(false, Ordering::Release);
self.shared.epoch.fetch_add(1, Ordering::AcqRel);
}
/// The engine process is back and has the model loaded again (a new handle, a new epoch).
pub fn reload_engine(&self) {
self.shared.kill.store(false, Ordering::Release);
self.shared.down.store(false, Ordering::Release);
self.shared.epoch.fetch_add(1, Ordering::AcqRel);
self.shared.ready.store(true, Ordering::Release);
}
}
fn error(code: ErrorCode, message: &str, retryable: bool) -> BackendError {
BackendError {
code,
message: message.to_owned(),
retryable,
}
}
fn handle_name(epoch: u64) -> String {
format!("scripted-handle-{epoch}")
}
impl Backend for ScriptedEngine {
fn identity(&self) -> BackendIdentity {
BackendIdentity {
name: "scripted".into(),
implementation_version: "test".into(),
api_version: crate::BACKEND_API_VERSION,
}
}
fn prefix_cache_summary(&self) -> Option<String> {
self.shared.prefix_summary.lock().unwrap().clone()
}
fn memory_report(&self) -> Option<String> {
self.shared.memory_report.lock().unwrap().clone()
}
/// Accepts any document that looks like a JSON object unless it names a member `"bad"` (refused as an invalid request) and echoes it.
fn reconfigure(&mut self, settings_json: &str) -> Result<String, BackendError> {
let invalid = |message: &str| BackendError { code: ErrorCode::InvalidRequest, message: message.into(), retryable: false };
let trimmed = settings_json.trim();
if !(trimmed.starts_with('{') && trimmed.ends_with('}')) {
return Err(invalid("not an object"));
}
if trimmed.contains("\"bad\"") {
return Err(invalid("bad setting"));
}
self.shared.settings.lock().unwrap().push(trimmed.to_owned());
Ok(trimmed.to_owned())
}
fn capabilities(&self) -> BackendCapabilities {
let d = &self.shared.descriptor;
BackendCapabilities {
supported_models: if self.shared.ready.load(Ordering::Acquire) {
vec![SupportedModelTuple {
family: d.family.clone(),
architecture: d.architecture.clone(),
weight_format: d.weight_format.clone(),
}]
} else {
Vec::new()
},
max_concurrent_generations: 1,
supports_cancellation: true,
supports_tool_call_streaming: false,
}
}
fn load(
&mut self,
model: ModelDescriptor,
config: RuntimeConfig,
) -> Result<LoadedModel, BackendError> {
self.shared
.loads
.lock()
.unwrap()
.push((model.clone(), config.clone()));
config.validate().map_err(|_| {
error(
ErrorCode::InvalidRequest,
"invalid load configuration",
false,
)
})?;
if self.shared.down.load(Ordering::Acquire) {
return Err(error(ErrorCode::BackendUnavailable, "engine is down", true));
}
if model != self.shared.descriptor {
return Err(error(
ErrorCode::UnsupportedModel,
"unsupported model",
false,
));
}
self.shared.kill.store(false, Ordering::Release);
let epoch = self.shared.epoch.fetch_add(1, Ordering::AcqRel) + 1;
self.shared.ready.store(true, Ordering::Release);
Ok(LoadedModel {
handle: handle_name(epoch),
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,
model: &LoadedModel,
request: GenerationRequest,
) -> Result<GenerationStream, BackendError> {
let shared = &self.shared;
if !shared.ready.load(Ordering::Acquire) {
return Err(error(
ErrorCode::BackendUnavailable,
"model is not loaded",
true,
));
}
if model.handle != handle_name(shared.epoch.load(Ordering::Acquire)) {
return Err(error(
ErrorCode::BackendUnavailable,
"stale model handle",
true,
));
}
if request.request_id.is_empty() || request.max_output_tokens == 0 {
return Err(error(ErrorCode::InvalidRequest, "invalid request", false));
}
let cancel = Arc::new(AtomicBool::new(false));
{
let mut active = shared.active.lock().unwrap();
if active.is_some() {
return Err(error(
ErrorCode::ResourceExhausted,
"a generation is already running",
true,
));
}
*active = Some(ActiveGeneration {
id: request.request_id.clone(),
cancel: cancel.clone(),
});
}
shared.requests.lock().unwrap().push(request.clone());
let script = {
let mut responder = shared.responder.lock().unwrap();
match responder.as_mut() {
Some(responder) => responder(&request),
None => shared.queue.lock().unwrap().pop_front().unwrap_or_else(|| {
Script::new(vec![Step::Fail {
code: ErrorCode::Internal,
message: "no script queued".into(),
retryable: false,
}])
}),
}
};
let (sink, stream) = GenerationSink::channel();
let shared = Arc::clone(&self.shared);
thread::spawn(move || play(&shared, &cancel, sink, script));
Ok(stream)
}
fn cancel(&mut self, request_id: &str) -> Result<(), BackendError> {
self.shared
.cancels
.lock()
.unwrap()
.push(request_id.to_owned());
match self.shared.active.lock().unwrap().as_ref() {
Some(active) if active.id == request_id => {
active.cancel.store(true, Ordering::Release);
Ok(())
}
_ => Err(error(
ErrorCode::InvalidRequest,
"generation is not active",
false,
)),
}
}
fn unload(&mut self, model: LoadedModel) -> Result<(), BackendError> {
if model.handle != handle_name(self.shared.epoch.load(Ordering::Acquire)) {
return Err(error(
ErrorCode::InvalidRequest,
"stale model handle",
false,
));
}
self.shared.ready.store(false, Ordering::Release);
Ok(())
}
}
/// Plays one script. The active slot is released before the terminal event is published, so a
/// caller that reacts to the terminal can start the next generation at once.
fn play(shared: &Shared, cancel: &AtomicBool, sink: GenerationSink, script: Script) {
let release = || {
*shared.active.lock().unwrap() = None;
};
let killed = || shared.kill.load(Ordering::Acquire);
for step in script.steps {
if killed() {
release();
return; // the sink drops without a terminal event
}
if cancel.load(Ordering::Acquire) || sink.is_closed() {
release();
let _ = sink.cancel();
return;
}
let sent = match step {
Step::Text(text) => sink.emit(GenerationEvent::TextDelta { text }),
Step::Usage(usage) => sink.emit(GenerationEvent::Usage(usage)),
Step::ToolCall {
index,
id,
name,
arguments_delta,
} => sink.emit(GenerationEvent::ToolCallDelta {
index,
id,
name,
arguments_delta,
}),
Step::Pause(duration) => {
let until = Instant::now() + duration;
while Instant::now() < until
&& !cancel.load(Ordering::Acquire)
&& !killed()
&& !sink.is_closed()
{
thread::sleep(Duration::from_millis(2));
}
Ok(())
}
Step::Unresponsive(duration) => {
thread::sleep(duration);
Ok(())
}
Step::AwaitCancel => {
while !cancel.load(Ordering::Acquire) && !killed() && !sink.is_closed() {
thread::sleep(Duration::from_millis(2));
}
if killed() {
release();
return;
}
release();
let _ = sink.cancel();
return;
}
Step::Finish { reason, usage } => {
release();
let _ = sink.emit(GenerationEvent::Terminal(GenerationTerminal::Completed {
reason,
usage,
}));
return;
}
Step::Fail {
code,
message,
retryable,
} => {
release();
let _ = sink.emit(GenerationEvent::Terminal(GenerationTerminal::Failed {
code,
message,
retryable,
}));
return;
}
Step::CancelledUnasked => {
release();
let _ = sink.cancel();
return;
}
Step::DropWithoutTerminal => {
release();
return;
}
};
if sent.is_err() {
release();
return;
}
}
// A script that ends without a terminal step is an engine that died.
release();
}
#[cfg(test)]
mod tests {
use super::*;
use crate::InferenceMode;
fn config() -> RuntimeConfig {
RuntimeConfig {
load_config_version: crate::LOAD_CONFIG_VERSION,
inference_mode: InferenceMode::Native,
gpu_memory_limit_bytes: None,
allow_experimental: false,
}
}
fn request(id: &str) -> GenerationRequest {
GenerationRequest {
request_id: id.into(),
prompt: "p".into(),
max_output_tokens: 8,
temperature_milli: 0,
sampling: Default::default(),
}
}
fn loaded() -> (ScriptedEngine, ScriptedHandle, LoadedModel) {
let (mut engine, handle) = ScriptedEngine::new(ScriptedEngine::fixture_descriptor());
let model = engine
.load(ScriptedEngine::fixture_descriptor(), config())
.unwrap();
(engine, handle, model)
}
fn drain(stream: &mut GenerationStream) -> (Vec<GenerationEvent>, bool) {
let mut events = Vec::new();
loop {
match stream.recv() {
Ok(Some(event)) => events.push(event),
Ok(None) => return (events, true),
Err(_) => return (events, false),
}
}
}
#[test]
fn plays_text_then_exactly_one_terminal_and_records_the_request() {
let (mut engine, handle, model) = loaded();
let usage = Usage {
input_tokens: 3,
output_tokens: 2,
reused_input_tokens: 1,
};
handle.push(Script::stop_with(&["a", "b"], usage.clone()));
let mut stream = engine.start_generation(&model, request("r1")).unwrap();
let (events, terminated) = drain(&mut stream);
assert!(terminated);
assert_eq!(
events,
vec![
GenerationEvent::TextDelta { text: "a".into() },
GenerationEvent::TextDelta { text: "b".into() },
GenerationEvent::Terminal(GenerationTerminal::Completed {
reason: FinishReason::Stop,
usage
}),
]
);
assert_eq!(handle.requests().len(), 1);
assert_eq!(handle.requests()[0].request_id, "r1");
// The slot is free as soon as the terminal event was published.
handle.push(Script::stop_with(&[], Usage::default()));
assert!(engine.start_generation(&model, request("r2")).is_ok());
}
#[test]
fn refuses_a_second_concurrent_generation_unloaded_and_stale_handles() {
let (mut engine, handle, model) = loaded();
handle.push(Script::hanging_after(&["x"]));
let _stream = engine.start_generation(&model, request("r1")).unwrap();
assert_eq!(
engine
.start_generation(&model, request("r2"))
.err()
.unwrap()
.code,
ErrorCode::ResourceExhausted
);
engine.cancel("r1").unwrap();
handle.restart_engine();
let refused = engine
.start_generation(&model, request("r3"))
.err()
.unwrap();
assert_eq!(refused.code, ErrorCode::BackendUnavailable);
handle.reload_engine();
// The old handle is stale after a restart even though the model is ready again.
let stale = engine
.start_generation(&model, request("r4"))
.err()
.unwrap();
assert_eq!(stale.message, "stale model handle");
}
#[test]
fn cancel_ends_a_hanging_generation_with_a_cancelled_terminal() {
let (mut engine, handle, model) = loaded();
handle.push(Script::hanging_after(&["x"]));
let mut stream = engine.start_generation(&model, request("r1")).unwrap();
assert!(matches!(
stream.recv().unwrap(),
Some(GenerationEvent::TextDelta { .. })
));
engine.cancel("r1").unwrap();
assert!(matches!(
stream.recv().unwrap(),
Some(GenerationEvent::Terminal(GenerationTerminal::Cancelled))
));
assert_eq!(handle.cancels(), vec!["r1".to_owned()]);
assert!(engine.cancel("r1").is_err());
}
#[test]
fn a_dead_engine_ends_the_stream_without_a_terminal_event() {
let (mut engine, handle, model) = loaded();
handle.push(Script::dying_after(&["x"]));
let mut stream = engine.start_generation(&model, request("r1")).unwrap();
let (events, terminated) = drain(&mut stream);
assert!(!terminated);
assert_eq!(events.len(), 1);
handle.push(Script::hanging_after(&["y"]));
let mut stream = engine.start_generation(&model, request("r2"));
// r1's slot was released when the engine died, so r2 started.
let stream = stream.as_mut().unwrap();
let _ = stream.recv();
handle.restart_engine();
let (_, terminated) = drain(stream);
assert!(!terminated);
}
#[test]
fn a_responder_sees_the_request_and_dropping_the_stream_stops_the_script() {
let (mut engine, handle, model) = loaded();
handle.respond_with(|request| {
Script::stop_with(&[request.prompt.as_str()], Usage::default())
});
let mut stream = engine.start_generation(&model, request("r1")).unwrap();
let (events, _) = drain(&mut stream);
assert_eq!(events[0], GenerationEvent::TextDelta { text: "p".into() });
drop(stream);
handle.respond_with(|_| Script::hanging_after(&["z"]));
let stream = engine.start_generation(&model, request("r2")).unwrap();
drop(stream);
for _ in 0..200 {
if !handle.is_generating() {
return;
}
thread::sleep(Duration::from_millis(5));
}
panic!("a dropped stream must release the generation");
}
}