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>
678 lines
24 KiB
Rust
678 lines
24 KiB
Rust
//! `GrpcBackend` against a scripted `leleka.runtime.v1` server over real loopback HTTP/2.
|
|
//!
|
|
//! The server here is a stand-in: it answers snapshots, replays the frames a test gives it and counts
|
|
//! cancels. The full chain with the real `RuntimeServer` and a scripted engine behind it is exercised
|
|
//! in `strata-desktop-core` (`tests/api_over_runtime.rs`). Nothing here loads a model.
|
|
|
|
use std::{
|
|
net::SocketAddr,
|
|
pin::Pin,
|
|
sync::{
|
|
Arc, Mutex,
|
|
atomic::{AtomicUsize, Ordering},
|
|
},
|
|
time::Duration,
|
|
};
|
|
|
|
use futures_util::Stream;
|
|
use leleka_backend_api::{
|
|
Backend, ErrorCode, FinishReason, GenerationEvent, GenerationRequest, GenerationTerminal,
|
|
InferenceMode, LoadedModel, ModelDescriptor, RuntimeConfig, SamplingOptions, StreamError,
|
|
Usage,
|
|
};
|
|
use leleka_runtime_client::{
|
|
backend::GrpcBackend,
|
|
convert,
|
|
proto::{self, generation_frame::Payload},
|
|
};
|
|
use tonic::{Request, Response, Status};
|
|
|
|
const TOKEN: &str = "synthetic-grpc-backend-token-000000000";
|
|
type Frames = Vec<Result<Payload, Status>>;
|
|
|
|
fn descriptor() -> ModelDescriptor {
|
|
ModelDescriptor {
|
|
family: "fixture_family".into(),
|
|
architecture: "fixture_arch".into(),
|
|
artifact_digest: format!("sha256:{}", "e".repeat(64)),
|
|
weight_format: "fixture:format".into(),
|
|
}
|
|
}
|
|
|
|
fn config() -> RuntimeConfig {
|
|
RuntimeConfig {
|
|
load_config_version: leleka_backend_api::LOAD_CONFIG_VERSION,
|
|
inference_mode: InferenceMode::Native,
|
|
gpu_memory_limit_bytes: None,
|
|
allow_experimental: false,
|
|
}
|
|
}
|
|
|
|
fn loaded(handle: &str) -> LoadedModel {
|
|
LoadedModel {
|
|
handle: handle.into(),
|
|
descriptor: descriptor(),
|
|
load_config_version: leleka_backend_api::LOAD_CONFIG_VERSION,
|
|
effective_mode: InferenceMode::Native,
|
|
mode_identity_digest: format!("sha256:{}", "f".repeat(64)),
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
struct Fake {
|
|
state: Arc<Mutex<FakeState>>,
|
|
cancels: Arc<AtomicUsize>,
|
|
}
|
|
|
|
struct FakeState {
|
|
epoch: String,
|
|
sequence: u64,
|
|
loaded: Option<LoadedModel>,
|
|
scripts: Vec<Frames>,
|
|
requests: Vec<proto::GenerateRequest>,
|
|
cancel_requests: Vec<proto::CancelRequest>,
|
|
}
|
|
|
|
impl Fake {
|
|
fn new(loaded: Option<LoadedModel>) -> Self {
|
|
Self {
|
|
state: Arc::new(Mutex::new(FakeState {
|
|
epoch: uuid::Uuid::new_v4().to_string(),
|
|
sequence: 1,
|
|
loaded,
|
|
scripts: Vec::new(),
|
|
requests: Vec::new(),
|
|
cancel_requests: Vec::new(),
|
|
})),
|
|
cancels: Arc::new(AtomicUsize::new(0)),
|
|
}
|
|
}
|
|
|
|
fn snapshot(&self) -> proto::Snapshot {
|
|
let mut state = self.state.lock().unwrap();
|
|
state.sequence += 1;
|
|
proto::Snapshot {
|
|
protocol_version: 1,
|
|
backend_api_version: 2,
|
|
epoch: state.epoch.clone(),
|
|
sequence: state.sequence,
|
|
full_snapshot: true,
|
|
transport_ready: true,
|
|
model_ready: state.loaded.is_some(),
|
|
loaded: state.loaded.as_ref().map(convert::loaded_to_proto),
|
|
capabilities: Some(proto::Capabilities {
|
|
models: if state.loaded.is_some() {
|
|
vec![proto::SupportedModelTuple {
|
|
family: descriptor().family,
|
|
architecture: descriptor().architecture,
|
|
weight_format: descriptor().weight_format,
|
|
}]
|
|
} else {
|
|
Vec::new()
|
|
},
|
|
max_concurrent_generations: 1,
|
|
cancellation: true,
|
|
tool_call_streaming: false,
|
|
}),
|
|
active_request_id: String::new(),
|
|
prefix_cache_json: String::new(),
|
|
memory_json: String::new(),
|
|
telemetry_json: String::new(),
|
|
}
|
|
}
|
|
|
|
/// A new process: new epoch, model gone until `set_loaded`.
|
|
fn restart(&self) {
|
|
let mut state = self.state.lock().unwrap();
|
|
state.epoch = uuid::Uuid::new_v4().to_string();
|
|
state.loaded = None;
|
|
}
|
|
|
|
fn set_loaded(&self, loaded: Option<LoadedModel>) {
|
|
self.state.lock().unwrap().loaded = loaded;
|
|
}
|
|
|
|
fn push(&self, frames: Frames) {
|
|
self.state.lock().unwrap().scripts.push(frames);
|
|
}
|
|
}
|
|
|
|
#[tonic::async_trait]
|
|
impl proto::runtime_server::Runtime for Fake {
|
|
async fn handshake(
|
|
&self,
|
|
_: Request<proto::Hello>,
|
|
) -> Result<Response<proto::Snapshot>, Status> {
|
|
Ok(Response::new(self.snapshot()))
|
|
}
|
|
async fn snapshot(
|
|
&self,
|
|
_: Request<proto::Empty>,
|
|
) -> Result<Response<proto::Snapshot>, Status> {
|
|
Ok(Response::new(self.snapshot()))
|
|
}
|
|
type WatchStream = Pin<Box<dyn Stream<Item = Result<proto::Snapshot, Status>> + Send>>;
|
|
async fn watch(
|
|
&self,
|
|
_: Request<proto::Cursor>,
|
|
) -> Result<Response<Self::WatchStream>, Status> {
|
|
Err(Status::unimplemented("fixture"))
|
|
}
|
|
async fn load(
|
|
&self,
|
|
_: Request<proto::LoadRequest>,
|
|
) -> Result<Response<proto::OperationResult>, Status> {
|
|
panic!("an attach-only backend must never send Load");
|
|
}
|
|
async fn unload(
|
|
&self,
|
|
_: Request<proto::UnloadRequest>,
|
|
) -> Result<Response<proto::OperationResult>, Status> {
|
|
panic!("an attach-only backend must never send Unload");
|
|
}
|
|
async fn operation(
|
|
&self,
|
|
_: Request<proto::OperationQuery>,
|
|
) -> Result<Response<proto::OperationResult>, Status> {
|
|
Err(Status::unimplemented("fixture"))
|
|
}
|
|
async fn reconfigure(
|
|
&self,
|
|
request: Request<proto::ReconfigureRequest>,
|
|
) -> Result<Response<proto::ReconfigureReply>, Status> {
|
|
let request = request.into_inner();
|
|
let refuse = request.settings_json.contains("bad");
|
|
Ok(Response::new(proto::ReconfigureReply {
|
|
operation_id: request.operation_id,
|
|
epoch: request.expected_epoch,
|
|
ok: !refuse,
|
|
effective_json: request.settings_json,
|
|
error_code: if refuse { "invalid".into() } else { String::new() },
|
|
error: if refuse { "context_tokens must be 1..=262144".into() } else { String::new() },
|
|
retryable: false,
|
|
}))
|
|
}
|
|
async fn cancel(
|
|
&self,
|
|
request: Request<proto::CancelRequest>,
|
|
) -> Result<Response<proto::CancelAck>, Status> {
|
|
self.cancels.fetch_add(1, Ordering::SeqCst);
|
|
let request = request.into_inner();
|
|
let ack = proto::CancelAck {
|
|
request_id: request.request_id.clone(),
|
|
epoch: request.expected_epoch.clone(),
|
|
acknowledged: true,
|
|
};
|
|
self.state.lock().unwrap().cancel_requests.push(request);
|
|
Ok(Response::new(ack))
|
|
}
|
|
type GenerateStream =
|
|
Pin<Box<dyn Stream<Item = Result<proto::GenerationFrame, Status>> + Send>>;
|
|
async fn generate(
|
|
&self,
|
|
request: Request<proto::GenerateRequest>,
|
|
) -> Result<Response<Self::GenerateStream>, Status> {
|
|
let request = request.into_inner();
|
|
let (epoch, frames) = {
|
|
let mut state = self.state.lock().unwrap();
|
|
state.requests.push(request.clone());
|
|
let frames = if state.scripts.is_empty() {
|
|
Vec::new()
|
|
} else {
|
|
state.scripts.remove(0)
|
|
};
|
|
(state.epoch.clone(), frames)
|
|
};
|
|
let id = request.request_id;
|
|
let mut out: Vec<Result<proto::GenerationFrame, Status>> = Vec::new();
|
|
let sequence = 1;
|
|
let frame = |sequence, payload| proto::GenerationFrame {
|
|
request_id: id.clone(),
|
|
epoch: epoch.clone(),
|
|
sequence,
|
|
payload: Some(payload),
|
|
};
|
|
out.push(Ok(frame(
|
|
sequence,
|
|
Payload::Accepted(proto::Accepted { accepted: true }),
|
|
)));
|
|
for (sequence, item) in (2..).zip(frames) {
|
|
out.push(item.map(|payload| frame(sequence, payload)));
|
|
}
|
|
// A trailing `Aborted("hang")` means: stay open and silent after the scripted frames.
|
|
let hang = matches!(out.last(), Some(Err(s)) if s.code() == tonic::Code::Aborted && s.message() == "hang");
|
|
if hang {
|
|
out.pop();
|
|
}
|
|
let stream: Self::GenerateStream = if hang {
|
|
Box::pin(tokio_stream::StreamExt::chain(
|
|
tokio_stream::iter(out),
|
|
futures_util::stream::pending(),
|
|
))
|
|
} else {
|
|
Box::pin(tokio_stream::iter(out))
|
|
};
|
|
let mut response = Response::new(stream);
|
|
response
|
|
.metadata_mut()
|
|
.insert("x-leleka-accepted", "true".parse().unwrap());
|
|
Ok(response)
|
|
}
|
|
}
|
|
|
|
struct Server {
|
|
address: SocketAddr,
|
|
fake: Fake,
|
|
stop: Option<tokio::sync::oneshot::Sender<()>>,
|
|
task: tokio::task::JoinHandle<()>,
|
|
}
|
|
|
|
impl Server {
|
|
async fn start(loaded: Option<LoadedModel>) -> Self {
|
|
let fake = Fake::new(loaded);
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
let address = listener.local_addr().unwrap();
|
|
let (stop, stopped) = tokio::sync::oneshot::channel();
|
|
let service = fake.clone();
|
|
let task = tokio::spawn(async move {
|
|
tonic::transport::Server::builder()
|
|
.add_service(proto::runtime_server::RuntimeServer::new(service))
|
|
.serve_with_incoming_shutdown(
|
|
tokio_stream::wrappers::TcpListenerStream::new(listener),
|
|
async {
|
|
let _ = stopped.await;
|
|
},
|
|
)
|
|
.await
|
|
.unwrap();
|
|
});
|
|
Self {
|
|
address,
|
|
fake,
|
|
stop: Some(stop),
|
|
task,
|
|
}
|
|
}
|
|
|
|
fn backend(&self) -> GrpcBackend {
|
|
GrpcBackend::new(
|
|
tokio::runtime::Handle::current(),
|
|
self.address,
|
|
TOKEN.into(),
|
|
)
|
|
}
|
|
|
|
async fn finish(mut self) {
|
|
let _ = self.stop.take().unwrap().send(());
|
|
if tokio::time::timeout(Duration::from_millis(300), &mut self.task)
|
|
.await
|
|
.is_err()
|
|
{
|
|
self.task.abort();
|
|
}
|
|
}
|
|
}
|
|
|
|
fn usage(i: u64, o: u64, r: u64) -> proto::Usage {
|
|
proto::Usage {
|
|
input_tokens: i,
|
|
output_tokens: o,
|
|
reused_input_tokens: r,
|
|
}
|
|
}
|
|
|
|
fn terminal(state: i32, reason: &str, with_usage: bool) -> Payload {
|
|
Payload::Terminal(proto::Terminal {
|
|
state,
|
|
reason: reason.into(),
|
|
usage: with_usage.then(|| usage(10, 3, 2)),
|
|
error_code: if state == 2 {
|
|
"resource_exhausted".into()
|
|
} else {
|
|
String::new()
|
|
},
|
|
retryable: false,
|
|
})
|
|
}
|
|
|
|
fn text(s: &str) -> Payload {
|
|
Payload::Text(proto::TextDelta { text: s.into() })
|
|
}
|
|
|
|
fn request(id: &str) -> GenerationRequest {
|
|
GenerationRequest {
|
|
request_id: id.into(),
|
|
prompt: "<|im_start|>user\nhi<|im_end|>\n".into(),
|
|
max_output_tokens: 64,
|
|
temperature_milli: 700,
|
|
sampling: SamplingOptions {
|
|
top_p_micro: Some(900_000),
|
|
top_k: Some(20),
|
|
min_p_micro: Some(50_000),
|
|
repetition_penalty_micro: Some(1_100_000),
|
|
frequency_penalty_micro: Some(-500_000),
|
|
presence_penalty_micro: Some(250_000),
|
|
penalty_last_n: Some(64),
|
|
seed: Some(42),
|
|
},
|
|
}
|
|
}
|
|
|
|
/// Run a blocking backend call on a blocking thread, as the control plane does.
|
|
async fn blocking<T: Send + 'static>(
|
|
mut backend: GrpcBackend,
|
|
call: impl FnOnce(&mut GrpcBackend) -> T + Send + 'static,
|
|
) -> (GrpcBackend, T) {
|
|
tokio::task::spawn_blocking(move || {
|
|
let value = call(&mut backend);
|
|
(backend, value)
|
|
})
|
|
.await
|
|
.unwrap()
|
|
}
|
|
|
|
fn id() -> String {
|
|
uuid::Uuid::new_v4().to_string()
|
|
}
|
|
|
|
fn drain(stream: &mut leleka_backend_api::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(StreamError::MissingTerminal) => return (events, false),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn attach_returns_the_loaded_model_and_never_sends_load() {
|
|
let server = Server::start(Some(loaded("h-1"))).await;
|
|
let backend = server.backend();
|
|
let (_backend, result) = blocking(backend, |b| b.load(descriptor(), config())).await;
|
|
let attached = result.unwrap();
|
|
assert_eq!(attached.handle, "h-1");
|
|
assert_eq!(attached.descriptor, descriptor());
|
|
server.finish().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn reconfigure_reaches_the_runtime_and_returns_the_effective_settings_or_the_refusal() {
|
|
let server = Server::start(Some(loaded("h-1"))).await;
|
|
let backend = server.backend();
|
|
let (backend, attached) = blocking(backend, |b| b.load(descriptor(), config())).await;
|
|
attached.unwrap();
|
|
let (backend, reply) = blocking(backend, |b| b.reconfigure("{\"context_tokens\":65536}")).await;
|
|
assert_eq!(reply.unwrap(), "{\"context_tokens\":65536}");
|
|
let (_backend, refused) = blocking(backend, |b| b.reconfigure("{\"bad\":1}")).await;
|
|
let error = refused.unwrap_err();
|
|
assert_eq!(error.code, leleka_backend_api::ErrorCode::InvalidRequest);
|
|
assert!(error.message.contains("context_tokens"), "{}", error.message);
|
|
server.finish().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn attach_refuses_what_it_did_not_expect() {
|
|
// No model loaded: retryable, so the caller waits and tries again.
|
|
let server = Server::start(None).await;
|
|
let (_b, result) = blocking(server.backend(), |b| b.load(descriptor(), config())).await;
|
|
let error = result.unwrap_err();
|
|
assert_eq!(error.code, ErrorCode::BackendUnavailable);
|
|
assert!(error.retryable);
|
|
|
|
// A different artifact digest, and a different mode, are not silently accepted.
|
|
server.fake.set_loaded(Some(loaded("h-1")));
|
|
let other = ModelDescriptor {
|
|
artifact_digest: format!("sha256:{}", "0".repeat(64)),
|
|
..descriptor()
|
|
};
|
|
let (_b, result) = blocking(server.backend(), move |b| b.load(other, config())).await;
|
|
assert_eq!(result.unwrap_err().code, ErrorCode::UnsupportedModel);
|
|
let mtp = RuntimeConfig {
|
|
inference_mode: InferenceMode::ExperimentalMtp {
|
|
profile_id: "qwen4exp-kar-ple-mtp-v1".into(),
|
|
},
|
|
allow_experimental: true,
|
|
..config()
|
|
};
|
|
let (_b, result) = blocking(server.backend(), move |b| b.load(descriptor(), mtp)).await;
|
|
assert_eq!(result.unwrap_err().code, ErrorCode::UnsupportedModel);
|
|
server.finish().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn a_generation_sends_the_identity_and_every_sampling_field_and_maps_frames() {
|
|
let server = Server::start(Some(loaded("h-1"))).await;
|
|
server.fake.push(vec![
|
|
Ok(text("hel")),
|
|
Ok(text("lo")),
|
|
Ok(Payload::Usage(usage(10, 2, 2))),
|
|
Ok(terminal(1, "stop", true)),
|
|
]);
|
|
let (backend, attached) = blocking(server.backend(), |b| b.load(descriptor(), config())).await;
|
|
let attached = attached.unwrap();
|
|
let request_id = id();
|
|
let sent = request(&request_id);
|
|
let (_backend, stream) = blocking(backend, move |b| b.start_generation(&attached, sent)).await;
|
|
let mut stream = stream.unwrap();
|
|
let (events, terminated) = tokio::task::spawn_blocking(move || drain(&mut stream))
|
|
.await
|
|
.unwrap();
|
|
assert!(terminated);
|
|
assert_eq!(
|
|
events,
|
|
vec![
|
|
GenerationEvent::TextDelta { text: "hel".into() },
|
|
GenerationEvent::TextDelta { text: "lo".into() },
|
|
GenerationEvent::Usage(Usage {
|
|
input_tokens: 10,
|
|
output_tokens: 2,
|
|
reused_input_tokens: 2
|
|
}),
|
|
GenerationEvent::Terminal(GenerationTerminal::Completed {
|
|
reason: FinishReason::Stop,
|
|
usage: Usage {
|
|
input_tokens: 10,
|
|
output_tokens: 3,
|
|
reused_input_tokens: 2
|
|
}
|
|
}),
|
|
]
|
|
);
|
|
let seen = server.fake.state.lock().unwrap().requests[0].clone();
|
|
assert_eq!(seen.request_id, request_id);
|
|
assert_eq!(seen.handle, "h-1");
|
|
assert_eq!(seen.expected_epoch, server.fake.state.lock().unwrap().epoch);
|
|
assert_eq!(seen.prompt, "<|im_start|>user\nhi<|im_end|>\n");
|
|
assert_eq!((seen.max_output_tokens, seen.temperature_milli), (64, 700));
|
|
assert_eq!(seen.top_p_micro, Some(900_000));
|
|
assert_eq!(seen.top_k, Some(20));
|
|
assert_eq!(seen.min_p_micro, Some(50_000));
|
|
assert_eq!(seen.repetition_penalty_micro, Some(1_100_000));
|
|
assert_eq!(seen.frequency_penalty_micro, Some(-500_000));
|
|
assert_eq!(seen.presence_penalty_micro, Some(250_000));
|
|
assert_eq!(seen.penalty_last_n, Some(64));
|
|
assert_eq!(seen.seed, Some(42));
|
|
server.finish().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn failed_and_cancelled_terminals_keep_their_meaning() {
|
|
let server = Server::start(Some(loaded("h-1"))).await;
|
|
server.fake.push(vec![
|
|
Ok(text("x")),
|
|
Ok(terminal(2, "engine exploded", false)),
|
|
]);
|
|
server.fake.push(vec![Ok(terminal(3, "cancelled", false))]);
|
|
let (mut backend, attached) =
|
|
blocking(server.backend(), |b| b.load(descriptor(), config())).await;
|
|
let attached = attached.unwrap();
|
|
for expected in ["failed", "cancelled"] {
|
|
let (b, stream) = {
|
|
let attached = attached.clone();
|
|
blocking(backend, move |b| {
|
|
b.start_generation(&attached, request(&id()))
|
|
})
|
|
.await
|
|
};
|
|
backend = b;
|
|
let mut stream = stream.unwrap();
|
|
let (events, terminated) = tokio::task::spawn_blocking(move || drain(&mut stream))
|
|
.await
|
|
.unwrap();
|
|
assert!(terminated, "{expected}");
|
|
match (expected, events.last().unwrap()) {
|
|
(
|
|
"failed",
|
|
GenerationEvent::Terminal(GenerationTerminal::Failed { code, message, .. }),
|
|
) => {
|
|
assert_eq!(*code, ErrorCode::ResourceExhausted);
|
|
assert_eq!(message, "engine exploded");
|
|
}
|
|
("cancelled", GenerationEvent::Terminal(GenerationTerminal::Cancelled)) => {}
|
|
other => panic!("{other:?}"),
|
|
}
|
|
}
|
|
server.finish().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn a_stream_that_ends_without_a_terminal_or_with_a_transport_error_has_no_terminal() {
|
|
let server = Server::start(Some(loaded("h-1"))).await;
|
|
server.fake.push(vec![Ok(text("half"))]);
|
|
server
|
|
.fake
|
|
.push(vec![Ok(text("half")), Err(Status::internal("reset"))]);
|
|
// A frame the contract cannot express (unknown finish reason) is not turned into a success.
|
|
server.fake.push(vec![Ok(terminal(1, "weird", true))]);
|
|
let (mut backend, attached) =
|
|
blocking(server.backend(), |b| b.load(descriptor(), config())).await;
|
|
let attached = attached.unwrap();
|
|
for case in 0..3 {
|
|
let (b, stream) = {
|
|
let attached = attached.clone();
|
|
blocking(backend, move |b| {
|
|
b.start_generation(&attached, request(&id()))
|
|
})
|
|
.await
|
|
};
|
|
backend = b;
|
|
let mut stream = stream.unwrap();
|
|
let (_, terminated) = tokio::task::spawn_blocking(move || drain(&mut stream))
|
|
.await
|
|
.unwrap();
|
|
assert!(
|
|
!terminated,
|
|
"case {case}: no terminal event may be invented"
|
|
);
|
|
}
|
|
server.finish().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn dropping_the_stream_cancels_the_request_on_the_runtime() {
|
|
let server = Server::start(Some(loaded("h-1"))).await;
|
|
// The runtime stays silent after one delta; the consumer goes away while the pump waits.
|
|
server
|
|
.fake
|
|
.push(vec![Ok(text("a")), Err(Status::aborted("hang"))]);
|
|
let (backend, attached) = blocking(server.backend(), |b| b.load(descriptor(), config())).await;
|
|
let attached = attached.unwrap();
|
|
let (_backend, stream) = blocking(backend, move |b| {
|
|
b.start_generation(&attached, request(&id()))
|
|
})
|
|
.await;
|
|
let mut stream = stream.unwrap();
|
|
let first = tokio::task::spawn_blocking(move || {
|
|
let first = stream.recv();
|
|
drop(stream);
|
|
first
|
|
})
|
|
.await
|
|
.unwrap();
|
|
assert!(matches!(first, Ok(Some(GenerationEvent::TextDelta { .. }))));
|
|
for _ in 0..200 {
|
|
if server.fake.cancels.load(Ordering::SeqCst) > 0 {
|
|
break;
|
|
}
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
|
}
|
|
assert_eq!(server.fake.cancels.load(Ordering::SeqCst), 1);
|
|
server.finish().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn explicit_cancel_addresses_the_active_request_and_unknown_ids_are_refused() {
|
|
let server = Server::start(Some(loaded("h-1"))).await;
|
|
// The scripted stream never terminates; the request stays active until cancelled.
|
|
server
|
|
.fake
|
|
.push(vec![Ok(text("a")), Err(Status::aborted("hang"))]);
|
|
let (backend, attached) = blocking(server.backend(), |b| b.load(descriptor(), config())).await;
|
|
let attached = attached.unwrap();
|
|
let request_id = id();
|
|
let sent = request(&request_id);
|
|
let (backend, stream) = blocking(backend, move |b| b.start_generation(&attached, sent)).await;
|
|
let _stream = stream.unwrap();
|
|
let wanted = request_id.clone();
|
|
let (backend, result) = blocking(backend, move |b| b.cancel(&wanted)).await;
|
|
result.unwrap();
|
|
let (_backend, result) = blocking(backend, |b| b.cancel("not-the-request")).await;
|
|
assert_eq!(result.unwrap_err().code, ErrorCode::InvalidRequest);
|
|
{
|
|
let state = server.fake.state.lock().unwrap();
|
|
assert_eq!(state.cancel_requests[0].request_id, request_id);
|
|
assert_eq!(state.cancel_requests[0].expected_epoch, state.epoch);
|
|
}
|
|
server.finish().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn a_restarted_runtime_is_refused_before_dispatch_and_reattach_follows_the_new_epoch() {
|
|
let server = Server::start(Some(loaded("h-1"))).await;
|
|
let (backend, attached) = blocking(server.backend(), |b| b.load(descriptor(), config())).await;
|
|
let attached = attached.unwrap();
|
|
let (backend, empty) =
|
|
blocking(backend, |b| b.capabilities().supported_models.is_empty()).await;
|
|
assert!(!empty, "a healthy attached runtime advertises its model");
|
|
|
|
// The runtime process restarts and loads the same model again: same handle, new epoch.
|
|
server.fake.restart();
|
|
server.fake.set_loaded(Some(loaded("h-1")));
|
|
let (backend, result) = blocking(backend, move |b| {
|
|
b.start_generation(&attached, request(&id()))
|
|
})
|
|
.await;
|
|
let error = result.err().expect("a stale epoch must not be dispatched");
|
|
assert_eq!(error.code, ErrorCode::BackendUnavailable);
|
|
assert!(error.retryable);
|
|
assert!(server.fake.state.lock().unwrap().requests.is_empty());
|
|
|
|
// The health probe reports the model as gone until the caller attaches again.
|
|
let (backend, empty) =
|
|
blocking(backend, |b| b.capabilities().supported_models.is_empty()).await;
|
|
assert!(empty);
|
|
let (backend, again) = blocking(backend, |b| b.load(descriptor(), config())).await;
|
|
let again = again.unwrap();
|
|
server.fake.push(vec![Ok(terminal(1, "stop", true))]);
|
|
let (_backend, stream) =
|
|
blocking(backend, move |b| b.start_generation(&again, request(&id()))).await;
|
|
assert!(stream.is_ok());
|
|
server.finish().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn an_unreachable_runtime_is_a_retryable_unavailable_and_unload_is_refused() {
|
|
let address = {
|
|
let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
|
probe.local_addr().unwrap()
|
|
};
|
|
let backend = GrpcBackend::new(tokio::runtime::Handle::current(), address, TOKEN.into());
|
|
let (backend, result) = blocking(backend, |b| b.load(descriptor(), config())).await;
|
|
let error = result.unwrap_err();
|
|
assert_eq!(error.code, ErrorCode::BackendUnavailable);
|
|
let (_backend, result) = blocking(backend, |b| b.unload(loaded("h"))).await;
|
|
assert_eq!(result.unwrap_err().code, ErrorCode::InvalidRequest);
|
|
}
|