Files
leleka/crates/backend-api/src/scripted.rs
T
Pavlo Ratushnyi 6b5fcd242e STRA-338 S12b: fns and impl blocks of 59 cold oversize modules move into child modules (model-format, gateway, desktop-core, leaf libraries)
scripts/dev/split_module.py (lexer-based, with 16 self-tests) moves the top-level fn and impl items of 59 oversize module files in control-plane, desktop-core, model-format, gateway-text, leleka-memory, experimental-ref, context, serving-policy, tokenizer, backend-api, quant-core, harmony, igpu, libc-shim, npu-service and runtime-client into foo/<name>.rs groups of about 250 lines; types, constants, macros, nested modules and tests stay, every path stays valid through pub use re-exports, restricted visibilities keep their scope one level down, include paths and super:: paths are shifted. Not touched: leleka-runtime, cuda-driver, native-cpu-expert, sampler-ref and cpu-* (hot path, next wave) and the files kar-off-ab edits.

The baseline drops from 311 to 263 oversize files and from 273,600 to about 233,000 lines; the path-include ratchet ignores dir/name.rs child declarations.
2026-11-05 15:29:39 +01:00

123 lines
4.2 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>,
}
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>,
}
#[cfg(test)]
mod tests;
mod impl_script;
#[allow(unused_imports)]
pub use impl_script::*;
mod impl_backend_for_scriptedengine;
#[allow(unused_imports)]
pub use impl_backend_for_scriptedengine::*;
mod play;
#[allow(unused_imports)]
pub use play::*;