Files
leleka/crates/runtime-client/src/client/tests.rs
T

295 lines
9.5 KiB
Rust

//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::*;
use futures_util::Stream;
use std::{
pin::Pin,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
};
use tonic::Response;
/// The snapshot of a runtime at `epoch` that reports `loaded` (and is not ready).
fn snapshot_of(epoch: String, loaded: Option<proto::LoadedModel>) -> proto::Snapshot {
proto::Snapshot {
protocol_version: 1,
backend_api_version: 2,
epoch,
sequence: 1,
full_snapshot: true,
transport_ready: true,
model_ready: false,
loaded,
capabilities: Some(proto::Capabilities::default()),
active_request_id: String::new(),
prefix_cache_json: String::new(),
memory_json: String::new(),
telemetry_json: String::new(),
}
}
fn retained_loaded() -> leleka_backend_api::LoadedModel {
let model = leleka_backend_api::ModelDescriptor {
family: "fixture".into(),
architecture: "fixture".into(),
weight_format: "fixture".into(),
artifact_digest: format!("sha256:{}", "a".repeat(64)),
};
leleka_backend_api::LoadedModel {
handle: "retained-fixture".into(),
descriptor: model,
load_config_version: 1,
effective_mode: leleka_backend_api::InferenceMode::Native,
mode_identity_digest: format!("sha256:{}", "b".repeat(64)),
}
}
fn fixture_model_tuple() -> proto::SupportedModelTuple {
proto::SupportedModelTuple {
family: "fixture".into(),
architecture: "fixture".into(),
weight_format: "fixture".into(),
}
}
#[test]
fn runtime_client_retained_handle_is_not_ready() {
let loaded = convert::loaded_to_proto(&retained_loaded());
let mut snapshot = snapshot_of(uuid::Uuid::new_v4().to_string(), Some(loaded));
assert!(validate_snapshot(&snapshot).is_ok());
let capabilities = snapshot.capabilities.as_mut().unwrap();
capabilities.models.push(fixture_model_tuple());
assert!(validate_snapshot(&snapshot).is_err());
snapshot.capabilities = Some(proto::Capabilities::default());
snapshot.loaded = None;
snapshot.model_ready = true;
assert!(validate_snapshot(&snapshot).is_err());
}
#[derive(Clone)]
struct FaultServer {
epoch: String,
fault: u8,
cancels: Arc<AtomicUsize>,
}
impl FaultServer {
fn snapshot(&self) -> proto::Snapshot {
snapshot_of(self.epoch.clone(), None)
}
/// The accepted frame, a terminal and then what the fault adds (0: nothing; 1: no terminal; 2: data after it;
/// 3: a stream error after it; 4: a terminal out of sequence).
fn fault_frames(&self, id: &str) -> Vec<Result<proto::GenerationFrame, Status>> {
let frame = |sequence, payload| fault_frame(id, &self.epoch, sequence, payload);
let accepted =
proto::generation_frame::Payload::Accepted(proto::Accepted { accepted: true });
let mut frames = vec![Ok(frame(1, accepted))];
if self.fault != 1 {
frames.push(Ok(frame(
if self.fault == 4 { 5 } else { 2 },
stop_terminal(),
)));
}
if self.fault == 2 {
let text = proto::TextDelta {
text: "must-not-publish".into(),
};
frames.push(Ok(frame(3, proto::generation_frame::Payload::Text(text))));
}
if self.fault == 3 {
frames.push(Err(Status::internal("fixture_trailer_error")));
}
frames
}
}
fn fault_frame(
id: &str,
epoch: &str,
sequence: u64,
payload: proto::generation_frame::Payload,
) -> proto::GenerationFrame {
proto::GenerationFrame {
request_id: id.to_owned(),
epoch: epoch.to_owned(),
sequence,
payload: Some(payload),
}
}
fn stop_terminal() -> proto::generation_frame::Payload {
proto::generation_frame::Payload::Terminal(proto::Terminal {
state: 1,
reason: "stop".into(),
usage: Some(proto::Usage::default()),
error_code: String::new(),
retryable: false,
})
}
#[tonic::async_trait]
impl proto::runtime_server::Runtime for FaultServer {
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> {
Err(Status::unimplemented("fixture"))
}
async fn unload(
&self,
_: Request<proto::UnloadRequest>,
) -> Result<Response<proto::OperationResult>, Status> {
Err(Status::unimplemented("fixture"))
}
async fn operation(
&self,
_: Request<proto::OperationQuery>,
) -> Result<Response<proto::OperationResult>, Status> {
Err(Status::unimplemented("fixture"))
}
async fn reconfigure(
&self,
_: Request<proto::ReconfigureRequest>,
) -> Result<Response<proto::ReconfigureReply>, Status> {
Err(Status::unimplemented("fixture"))
}
async fn cancel(
&self,
request: Request<proto::CancelRequest>,
) -> Result<Response<proto::CancelAck>, Status> {
self.cancels.fetch_add(1, Ordering::SeqCst);
Ok(Response::new(proto::CancelAck {
request_id: request.get_ref().request_id.clone(),
epoch: self.epoch.clone(),
acknowledged: true,
}))
}
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 id = request.into_inner().request_id;
let frames = self.fault_frames(&id);
let stream = Box::pin(tokio_stream::iter(frames)) as Self::GenerateStream;
let mut response = Response::new(stream);
response
.metadata_mut()
.insert("x-leleka-accepted", "true".parse().unwrap());
Ok(response)
}
}
#[tokio::test(flavor = "current_thread")]
async fn runtime_client_requires_terminal_eof_and_rejects_trailing_data_or_status() {
for fault in 0..=4 {
run_fault_case(fault).await;
}
}
/// Serves `service` on a loopback port until the returned sender fires.
async fn serve_fault(
service: FaultServer,
) -> (
std::net::SocketAddr,
tokio::sync::oneshot::Sender<()>,
tokio::task::JoinHandle<()>,
) {
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 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();
});
(address, stop, task)
}
fn fault_request(epoch: String) -> proto::GenerateRequest {
proto::GenerateRequest {
request_id: uuid::Uuid::new_v4().to_string(),
expected_epoch: epoch,
handle: "fixture".into(),
prompt: String::new(),
max_output_tokens: 1,
temperature_milli: 0,
..Default::default()
}
}
/// Reads the stream of one fault: whole when there is none, an error at the fault otherwise.
async fn expect_stream(stream: &mut RuntimeGeneration, fault: u8) {
assert!(matches!(
stream.message().await.unwrap().unwrap().payload,
Some(proto::generation_frame::Payload::Accepted(_))
));
if fault == 0 {
assert!(matches!(
stream.message().await.unwrap().unwrap().payload,
Some(proto::generation_frame::Payload::Terminal(_))
));
assert!(stream.message().await.unwrap().is_none());
} else {
assert!(stream.message().await.is_err());
}
}
/// A faulty stream dropped before its end makes the client ask the runtime to cancel, exactly once.
async fn expect_one_cancel(cancels: &AtomicUsize) {
for _ in 0..50 {
if cancels.load(Ordering::SeqCst) > 0 {
break;
}
tokio::time::sleep(Duration::from_millis(2)).await;
}
assert_eq!(cancels.load(Ordering::SeqCst), 1);
}
async fn run_fault_case(fault: u8) {
let epoch = uuid::Uuid::new_v4().to_string();
let cancels = Arc::new(AtomicUsize::new(0));
let service = FaultServer {
epoch: epoch.clone(),
fault,
cancels: cancels.clone(),
};
let (address, stop, task) = serve_fault(service).await;
let token = "synthetic-runtime-test-token-00000000".into();
let mut client = RuntimeClient::connect(address, token).await.unwrap();
let mut stream = client.generate(fault_request(epoch)).await.unwrap();
expect_stream(&mut stream, fault).await;
drop(stream);
if fault != 0 {
expect_one_cancel(&cancels).await;
}
drop(client);
stop.send(()).unwrap();
task.await.unwrap();
}