//! End-to-end tests of the OpenAI surface: HTTP request -> engine (mock) -> //! HTTP response, non-stream and stream, driven through a trivial formatter so //! the whole API layer is exercised without the real tokenizer. use std::sync::Arc; use std::time::Duration; use axum::body::Body; use axum::http::{header::CONTENT_TYPE, Method, Request, StatusCode}; use tower::ServiceExt; // for `oneshot` use strata_ctl::api::formatter::{Decoder, Formatter, Piece, Prompt}; use strata_ctl::api::service::ChatService; use strata_ctl::api::types::{ApiErrorEnvelope, ChatRequest}; use strata_ctl::engine::Engine; const MOCK: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py"); /// A formatter with no dialect: the prompt is the last message's bytes; each /// token id < 256 decodes to that byte as a char, always as "content". struct ByteFormatter; impl Formatter for ByteFormatter { fn model_name(&self) -> &str { "test-model" } fn build_prompt(&self, req: &ChatRequest) -> Result { let text = req .messages .iter() .rev() .find_map(|m| m.text()) .unwrap_or("") .to_string(); Ok(Prompt { ids: text.bytes().map(u32::from).collect(), max_new: req.max_new(64), sampling: Default::default(), temp_files: Vec::new(), }) } fn decoder(&self) -> Box { Box::new(ByteDecoder) } } struct ByteDecoder; impl Decoder for ByteDecoder { fn push(&mut self, id: u32) -> Vec { if id < 256 { vec![Piece::Content(char::from(id as u8).to_string())] } else { Vec::new() } } fn finish(&mut self, _reason: Option<&str>) -> Vec { Vec::new() } } /// Drives the mock's long, STOP-interruptible generation (ids contain 888888). struct LongFormatter; impl Formatter for LongFormatter { fn model_name(&self) -> &str { "test-model" } fn build_prompt(&self, _req: &ChatRequest) -> Result { Ok(Prompt { ids: vec![888888], max_new: 100000, sampling: Default::default(), temp_files: Vec::new(), }) } fn decoder(&self) -> Box { Box::new(ByteDecoder) } } async fn build_app() -> axum::Router { let engine = Arc::new( Engine::start( "python3", &[MOCK.to_string()], None, Duration::from_secs(10), ) .await .expect("mock engine starts"), ); let svc = ChatService::new(engine, Arc::new(ByteFormatter)); strata_ctl::api::router(svc) } async fn post_json(app: &axum::Router, body: serde_json::Value) -> (StatusCode, String) { let req = Request::builder() .method(Method::POST) .uri("/v1/chat/completions") .header(CONTENT_TYPE, "application/json") .body(Body::from(body.to_string())) .unwrap(); let resp = app.clone().oneshot(req).await.unwrap(); let status = resp.status(); let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX) .await .unwrap(); (status, String::from_utf8_lossy(&bytes).into_owned()) } #[tokio::test] async fn models_lists_the_served_model() { let app = build_app().await; let resp = app .oneshot( Request::builder() .uri("/v1/models") .body(Body::empty()) .unwrap(), ) .await .unwrap(); assert_eq!(resp.status(), StatusCode::OK); let body = axum::body::to_bytes(resp.into_body(), usize::MAX) .await .unwrap(); let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); assert_eq!(json["object"], "list"); assert_eq!(json["data"][0]["id"], "test-model"); } #[tokio::test] async fn non_stream_completion() { let app = build_app().await; let (status, text) = post_json( &app, serde_json::json!({ "model": "test-model", "messages": [{"role": "user", "content": "hi"}] }), ) .await; assert_eq!(status, StatusCode::OK, "body: {text}"); let json: serde_json::Value = serde_json::from_str(&text).unwrap(); assert_eq!(json["object"], "chat.completion"); // the mock's default path emits ids 101..105 -> 'e','f','g','h','i' assert_eq!(json["choices"][0]["message"]["content"], "efghi"); assert_eq!(json["choices"][0]["message"]["role"], "assistant"); assert_eq!(json["choices"][0]["finish_reason"], "stop"); assert_eq!(json["usage"]["completion_tokens"], 5); assert_eq!( json["usage"]["total_tokens"], json["usage"]["prompt_tokens"].as_u64().unwrap() + 5 ); assert!(json["id"].as_str().unwrap().starts_with("chatcmpl-")); } #[tokio::test] async fn stream_completion_is_sse() { let app = build_app().await; let (status, text) = post_json( &app, serde_json::json!({ "model": "test-model", "messages": [{"role": "user", "content": "hi"}], "stream": true }), ) .await; assert_eq!(status, StatusCode::OK, "body: {text}"); // every payload line is `data: ...`; the stream ends with `data: [DONE]` let data_lines: Vec<&str> = text .lines() .filter(|l| l.starts_with("data: ")) .map(|l| &l["data: ".len()..]) .collect(); assert!( data_lines.last().copied() == Some("[DONE]"), "no [DONE]: {text}" ); // first chunk announces the role, the last (before [DONE]) the finish reason let first: serde_json::Value = serde_json::from_str(data_lines[0]).unwrap(); assert_eq!(first["object"], "chat.completion.chunk"); assert_eq!(first["choices"][0]["delta"]["role"], "assistant"); // reassemble content across the middle chunks let mut content = String::new(); let mut finish = None; for line in &data_lines[..data_lines.len() - 1] { let v: serde_json::Value = serde_json::from_str(line).unwrap(); if let Some(c) = v["choices"][0]["delta"]["content"].as_str() { content.push_str(c); } if let Some(f) = v["choices"][0]["finish_reason"].as_str() { finish = Some(f.to_string()); } } assert_eq!(content, "efghi"); assert_eq!(finish.as_deref(), Some("stop")); } #[tokio::test] async fn empty_messages_is_bad_request() { let app = build_app().await; let (status, text) = post_json( &app, serde_json::json!({"model": "test-model", "messages": []}), ) .await; assert_eq!(status, StatusCode::BAD_REQUEST); let json: serde_json::Value = serde_json::from_str(&text).unwrap(); assert_eq!(json["error"]["type"], "invalid_request_error"); } #[tokio::test] async fn malformed_json_is_openai_error() { let app = build_app().await; let req = Request::builder() .method(Method::POST) .uri("/v1/chat/completions") .header(CONTENT_TYPE, "application/json") .body(Body::from("{not json")) .unwrap(); let resp = app.oneshot(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let body = axum::body::to_bytes(resp.into_body(), usize::MAX) .await .unwrap(); let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); assert!(json["error"]["message"] .as_str() .unwrap() .contains("invalid JSON")); } #[tokio::test] async fn stream_aborts_on_client_disconnect() { let engine = Arc::new( Engine::start( "python3", &[MOCK.to_string()], None, Duration::from_secs(10), ) .await .expect("mock engine starts"), ); let svc = ChatService::new(engine.clone(), Arc::new(LongFormatter)); let app = strata_ctl::api::router(svc); let req = Request::builder() .method(Method::POST) .uri("/v1/chat/completions") .header(CONTENT_TYPE, "application/json") .body(Body::from( serde_json::json!({ "model": "test-model", "messages": [{"role": "user", "content": "go"}], "stream": true }) .to_string(), )) .unwrap(); let resp = app.oneshot(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); // Simulate the client vanishing: drop the SSE body without reading it. The // receiver is dropped, the disconnect select fires, the engine is aborted. drop(resp); // Poll (non-mutating) until the engine is idle: the long generation must // have been stopped, not left running for the full 100000 tokens. Bounded // wait so the test is robust under parallel load. let mut idle = false; for _ in 0..100 { if engine.is_idle() { idle = true; break; } tokio::time::sleep(Duration::from_millis(50)).await; } assert!(idle, "engine still busy after client disconnect"); let _ = engine.shutdown().await; } #[tokio::test] async fn stop_sequence_truncates_content() { let app = build_app().await; // the mock's default answer is "efghi"; stop "gh" cuts it to "ef" let (status, text) = post_json( &app, serde_json::json!({ "model": "test-model", "messages": [{"role": "user", "content": "hi"}], "stop": ["gh"] }), ) .await; assert_eq!(status, StatusCode::OK, "body: {text}"); let json: serde_json::Value = serde_json::from_str(&text).unwrap(); assert_eq!(json["choices"][0]["message"]["content"], "ef"); assert_eq!(json["choices"][0]["finish_reason"], "stop"); } #[tokio::test] async fn stop_sequence_truncates_stream() { let app = build_app().await; let (status, text) = post_json( &app, serde_json::json!({ "model": "test-model", "messages": [{"role": "user", "content": "hi"}], "stop": ["gh"], "stream": true }), ) .await; assert_eq!(status, StatusCode::OK, "body: {text}"); let data_lines: Vec<&str> = text .lines() .filter(|l| l.starts_with("data: ")) .map(|l| &l["data: ".len()..]) .collect(); assert_eq!(data_lines.last().copied(), Some("[DONE]")); let mut content = String::new(); let mut finish = None; for line in &data_lines[..data_lines.len() - 1] { let v: serde_json::Value = serde_json::from_str(line).unwrap(); if let Some(c) = v["choices"][0]["delta"]["content"].as_str() { content.push_str(c); } if let Some(f) = v["choices"][0]["finish_reason"].as_str() { finish = Some(f.to_string()); } } assert_eq!(content, "ef"); assert_eq!(finish.as_deref(), Some("stop")); }