diff --git a/backend/crates/gateway-api/tests/data_plane/chat_completions/delivery.rs b/backend/crates/gateway-api/tests/data_plane/chat_completions/delivery.rs index d15747db7..4bdd26e2b 100644 --- a/backend/crates/gateway-api/tests/data_plane/chat_completions/delivery.rs +++ b/backend/crates/gateway-api/tests/data_plane/chat_completions/delivery.rs @@ -25,7 +25,7 @@ pub(super) async fn sse_body(response: Response) -> (String, Vec) { } #[tokio::test] -async fn returns_chat_json_from_chat_chunks_without_responses_projection() { +async fn buffers_chat_chunks_as_json() { let fixture = Fixture::new(Session::new(vec![ created(), chunk(json!({"content":"你好 "}), Value::Null), @@ -38,15 +38,17 @@ async fn returns_chat_json_from_chat_chunks_without_responses_projection() { assert_eq!(body["object"], "chat.completion"); assert_eq!(body["choices"][0]["message"]["content"], "你好 🌍"); assert_eq!(body["choices"][0]["finish_reason"], "stop"); - assert_eq!(fixture.captured().protocol, "chat_completions"); - assert!(fixture.captured().body.get("input").is_none()); } #[tokio::test] async fn returns_chat_sse_with_one_terminal_and_one_done() { let fixture = Fixture::new(Session::new(vec![created(), completed("answer")])).await; - let (text, chunks) = sse_body(fixture.post(chat_request(true)).await).await; - assert!(!text.contains("response.completed")); + let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await; + assert!( + chunks + .iter() + .all(|value| value["object"] == "chat.completion.chunk") + ); assert_eq!( chunks .iter() @@ -75,19 +77,13 @@ async fn truncation_produces_error_without_success_finish() { #[tokio::test] async fn rejects_invalid_chat_input_before_starting_execution() { - for (field, value) in [ - ("n", json!(2)), - ("store", json!(true)), - ("previous_response_id", json!("opaque")), - ] { - let fixture = Fixture::new(Session::new(Vec::new())).await; - let mut body = chat_request(false); - body[field] = value; - let response = fixture.post(body).await; - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - assert_eq!(json_body(response).await["error"]["param"], field); - assert!(fixture.execution.captured.lock().unwrap().is_none()); - } + let fixture = Fixture::new(Session::new(Vec::new())).await; + let mut body = chat_request(false); + body["n"] = json!(2); + let response = fixture.post(body).await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!(json_body(response).await["error"]["param"], "n"); + assert!(fixture.execution.captured.lock().unwrap().is_none()); } #[tokio::test] diff --git a/backend/crates/gateway-api/tests/data_plane/chat_completions/http.rs b/backend/crates/gateway-api/tests/data_plane/chat_completions/http.rs index ec922c6ee..107b15962 100644 --- a/backend/crates/gateway-api/tests/data_plane/chat_completions/http.rs +++ b/backend/crates/gateway-api/tests/data_plane/chat_completions/http.rs @@ -261,8 +261,7 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() { let downstream = json_body(response).await; assert_eq!(downstream["object"], "chat.completion"); let observed = middleware.requests.lock().unwrap(); - assert!(observed[0].get("input").is_none()); - assert_eq!(observed[0]["messages"][0]["role"], "user"); + assert_eq!(observed.as_slice(), [chat_request(false)]); assert_eq!( middleware.inner.endpoints.lock().unwrap().as_slice(), [PATH] @@ -430,39 +429,6 @@ async fn commit_failure_does_not_deliver_buffered_or_first_terminal_chat_success } } -#[tokio::test] -async fn the_same_execution_fixture_finishes_native_responses_with_one_commit() { - for already_started in [false, true] { - let native = |kind: &str, status: &str| { - gateway_core::event::ProviderEvent::wire( - gateway_core::event::ProtocolWireEvent::json("openai", Some(kind.to_owned()), json!({ - "type":kind,"response":{"id":"resp_native","object":"response","model":"model-a","status":status, - "output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"native baseline"}]}]} - })).unwrap()) - }; - let mut events = Vec::new(); - if already_started { - events.push(native("response.created", "in_progress")); - } - events.push(native("response.completed", "completed")); - let fixture = Fixture::new(Session::new(events)).await; - let mut request = request(json!({"model":"model-a","input":"hello","stream":true})); - *request.uri_mut() = "/v1/responses".parse().unwrap(); - let response = fixture.router.clone().oneshot(request).await.unwrap(); - assert_eq!(response.status(), StatusCode::OK); - let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap(); - let text = String::from_utf8(bytes.to_vec()).unwrap(); - assert!(text.contains("event: response.completed"), "{text}"); - assert!(text.contains("native baseline"), "{text}"); - assert!(!text.contains("response.failed"), "{text}"); - assert_eq!(text.matches("data: [DONE]").count(), 1, "{text}"); - assert!(text.ends_with("data: [DONE]\n\n"), "{text}"); - assert!(fixture.trace.finalized.load(Ordering::SeqCst)); - assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 1); - assert_eq!(fixture.trace.response_commit.status_code(), Some(200)); - } -} - #[tokio::test] async fn finalization_failure_never_leaks_success_finish_or_usage() { for already_started in [false, true] { diff --git a/backend/crates/gateway-api/tests/data_plane/responses/http.rs b/backend/crates/gateway-api/tests/data_plane/responses/http.rs index fedc74b7b..1f768c35d 100644 --- a/backend/crates/gateway-api/tests/data_plane/responses/http.rs +++ b/backend/crates/gateway-api/tests/data_plane/responses/http.rs @@ -1967,35 +1967,47 @@ async fn streaming_success_should_emit_terminal_event_and_done_marker() { } #[tokio::test] -async fn streaming_finalized_unknown_wire_should_end_cleanly_without_synthetic_failure() { - let trace = Arc::new(Trace::default()); - let raw = Bytes::from_static( - b"event: response.future_terminal\ndata: {\"type\":\"response.future_terminal\",\"opaque\":true}\n\n", - ); - let event = ProviderEvent::wire( - ProtocolWireEvent::raw_sse("openai", raw.clone()).expect("raw future event"), - ); - let session = FakeSession::streaming( - Arc::clone(&trace), - vec![ - NextStep::Event(delivery_provider( - event, - CommitRequirement::CommitBeforeDelivery, - )), - NextStep::FinalizeSuccess, - ], - ); +async fn streaming_finalized_native_wire_should_end_cleanly() { + let completed = json!({ + "type": "response.completed", + "response": { + "id": "resp_test", "object": "response", "model": "public-model", "status": "completed", + "output": [{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "native baseline"}]}] + } + }); + let frames = [ + Bytes::from_static( + b"event: response.future_terminal\ndata: {\"type\":\"response.future_terminal\",\"opaque\":true}\n\n", + ), + Bytes::from(format!("event: response.completed\ndata: {completed}\n\n")), + ]; + for raw in frames { + let trace = Arc::new(Trace::default()); + let event = ProviderEvent::wire( + ProtocolWireEvent::raw_sse("openai", raw.clone()).expect("native wire event"), + ); + let session = FakeSession::streaming( + Arc::clone(&trace), + vec![ + NextStep::Event(delivery_provider( + event, + CommitRequirement::CommitBeforeDelivery, + )), + NextStep::FinalizeSuccess, + ], + ); - let response = stream_execution_response(Box::new(session), None).await; - let body = to_bytes(response.into_body(), usize::MAX) - .await - .expect("read transparent SSE body"); + let response = stream_execution_response(Box::new(session), None).await; + let body = to_bytes(response.into_body(), usize::MAX) + .await + .expect("read transparent SSE body"); - assert!(body.as_ref().starts_with(raw.as_ref())); - assert!(body.as_ref().ends_with(b"data: [DONE]\n\n")); - assert!(!String::from_utf8_lossy(&body).contains("response.failed")); - assert!(!trace.is_cancelled()); - assert_eq!(trace.snapshot(), vec!["next_event", "commit", "next_end"]); + let expected = [raw.as_ref(), b"data: [DONE]\n\n"].concat(); + assert_eq!(body.as_ref(), expected.as_slice()); + assert!(!trace.is_cancelled()); + assert_eq!(trace.snapshot(), vec!["next_event", "commit", "next_end"]); + assert_eq!(trace.detached_finalizations(), 0); + } } #[tokio::test] @@ -2656,7 +2668,7 @@ async fn native_responses_route_preserves_images_and_encrypted_reasoning_in_json } else { FakeSession::buffered_provider(Arc::clone(&trace), events) }; - // 使用真实 /v1/responses 入口,覆盖共享执行函数的可选适配器为空分支 + // 使用真实 /v1/responses 入口验证原生字段与 SSE 字节交付 let response = response(&admin, "openai", session, streaming).await; assert_eq!(response.status(), StatusCode::OK); let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); diff --git a/backend/crates/gateway-protocol/tests/chat_completions/request.rs b/backend/crates/gateway-protocol/tests/chat_completions/request.rs index 07a5b4c70..0f1bdf168 100644 --- a/backend/crates/gateway-protocol/tests/chat_completions/request.rs +++ b/backend/crates/gateway-protocol/tests/chat_completions/request.rs @@ -36,11 +36,13 @@ fn facts_are_extracted_from_chat_fields_directly() { } #[test] -fn invalid_envelopes_and_stream_options_keep_safe_field_errors() { +fn invalid_envelopes_and_chat_controls_keep_safe_field_errors() { assert_eq!(parse_request(b"[").err(), Some(ChatError::MalformedJson)); assert_eq!(parse_request(b"[]").err(), Some(ChatError::ExpectedObject)); for (field, value) in [ ("n", json!(2)), + ("store", json!(true)), + ("previous_response_id", json!("resp_previous")), ("stream_options", json!({"include_usage":true})), ] { let mut request = super::request(); diff --git a/backend/crates/gateway-protocol/tests/chat_completions/responses/request.rs b/backend/crates/gateway-protocol/tests/chat_completions/responses/request.rs index 1856934cd..f29d1437d 100644 --- a/backend/crates/gateway-protocol/tests/chat_completions/responses/request.rs +++ b/backend/crates/gateway-protocol/tests/chat_completions/responses/request.rs @@ -72,20 +72,6 @@ fn web_search_options_require_a_hosted_search_and_flatten_location() { } } -#[test] -fn maps_inline_user_pdf_without_reencoding_its_data() { - let data = "data:application/pdf;base64,JVBERi0xLjQ="; - let converted = convert(json!({"model":"model-a","messages":[ - {"role":"user","content":[{"type":"text","text":"Read the attachment"}, - {"type":"file","file":{"filename":"document.pdf","file_data":data}}]} - ]})); - assert_eq!( - converted["input"][0]["content"], - json!([{"type":"input_text","text":"Read the attachment"}, - {"type":"input_file","filename":"document.pdf","file_data":data}]) - ); -} - #[test] fn assistant_history_uses_output_content_for_text_and_refusals() { for content in [ @@ -312,19 +298,23 @@ fn files_and_audio_are_preserved_as_inputs_instead_of_losing_the_user_turn() { for file in [ json!({"file_id":"file_test"}), json!({"file_url":"https://example.com/report.txt"}), - json!({"file_data":"data:text/plain;base64,aGk=", "filename":"report.txt", "detail":"high"}), + json!({"file_data":"data:application/pdf;base64,JVBERi0xLjQ=", "filename":"document.pdf", "detail":"high"}), ] { let converted = convert( json!({"model":"model-a", "messages":[{"role":"user", "content":[ + {"type":"text","text":"Read the attachment"}, {"type":"file", "file":file}, {"type":"input_audio", "input_audio":{"data":"aGk=", "format":"mp3"}} ]}]}), ); let mut expected = file; expected["type"] = json!("input_file"); - assert_eq!(converted["input"][0]["content"][0], expected); assert_eq!( - converted["input"][0]["content"][1], - json!({"type":"input_audio","audio_url":"data:audio/mpeg;base64,aGk="}) + converted["input"][0]["content"], + json!([ + {"type":"input_text","text":"Read the attachment"}, + expected, + {"type":"input_audio","audio_url":"data:audio/mpeg;base64,aGk="} + ]) ); } } diff --git a/backend/crates/gateway-protocol/tests/chat_completions/responses/response.rs b/backend/crates/gateway-protocol/tests/chat_completions/responses/response.rs index a167d5b5e..8ebec43aa 100644 --- a/backend/crates/gateway-protocol/tests/chat_completions/responses/response.rs +++ b/backend/crates/gateway-protocol/tests/chat_completions/responses/response.rs @@ -28,11 +28,7 @@ impl Fixture { Self(events) } fn post(&self, request: Value) -> Projection { - let identity = ChatIdentity { - id: "chatcmpl-test".to_owned(), - created: 100, - model: "model-a".to_owned(), - }; + let identity = chat_identity(); let mut result = Projection { json: None, chunks: Vec::new(), @@ -97,6 +93,13 @@ fn sse_body(response: Projection) -> (String, Vec) { response.chunks, ) } +fn chat_identity() -> ChatIdentity { + ChatIdentity { + id: "chatcmpl-test".to_owned(), + created: 100, + model: "model-a".to_owned(), + } +} fn chat_request(stream: bool) -> Value { json!({"model":"model-a","messages":[{"role":"user","content":"hello"}],"stream":stream}) } @@ -134,7 +137,6 @@ fn tool(id: &str, call_id: &str, name: &str, arguments: &str) -> Value { fn json_projects_public_identity_text_and_actual_usage() { let fixture = Fixture::new(Session::new(vec![completed(json!([message("你好 🌍")]))])); let response = fixture.post(chat_request(false)); - assert!(response.error.is_none(), "{:?}", response.error); let body = json_body(response); assert_eq!(body["object"], "chat.completion"); assert!(body["id"].as_str().unwrap().starts_with("chatcmpl-")); @@ -191,7 +193,6 @@ fn web_search_projects_citations_in_json_and_streams_the_original_links() { let mut request = chat_request(stream); request["web_search_options"] = json!({}); let response = fixture.post(request); - assert!(response.error.is_none(), "{:?}", response.error); let expected = format!("🌍 {text}"); if stream { let (_, chunks) = sse_body(response); @@ -224,7 +225,6 @@ fn json_tool_arguments_and_refusal_do_not_become_assistant_text() { ] { let fixture = Fixture::new(Session::new(vec![completed(output.clone())])); let response = fixture.post(chat_request(false)); - assert!(response.error.is_none(), "{:?}", response.error); let body = json_body(response); let choice = &body["choices"][0]; assert_eq!(choice["message"]["content"], Value::Null); @@ -247,7 +247,8 @@ fn json_tool_arguments_and_refusal_do_not_become_assistant_text() { #[test] fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() { for include_usage in [false, true] { - let fixture = Fixture::new(Session::new(vec![ + let terminal = completed(json!([message("你好 🌍")])); + let events = [ created(), wire( "response.output_text.delta", @@ -265,11 +266,16 @@ fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() { "response.output_item.done", json!({"output_index":0,"item":message("你好 🌍")}), ), - completed(json!([message("你好 🌍")])), - ])); - let mut body = chat_request(true); - body["stream_options"] = json!({"include_usage":include_usage}); - let (_, chunks) = sse_body(fixture.post(body)); + terminal.clone(), + ]; + let identity = chat_identity(); + let mut encoder = ChatStreamEncoder::new(identity.clone(), include_usage); + let mut chunks = Vec::new(); + for event in events { + chunks.extend(encoder.push_event(None, &event).unwrap()); + } + assert!(encoder.is_completed()); + assert!(encoder.finish().unwrap().is_empty()); assert_eq!(combined(&chunks, "content"), "你好 🌍"); assert_eq!( chunks @@ -287,9 +293,9 @@ fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() { ); for chunk in &chunks { assert_eq!(chunk["object"], "chat.completion.chunk"); - assert_eq!(chunk["id"], chunks[0]["id"]); - assert_eq!(chunk["created"], chunks[0]["created"]); - assert_eq!(chunk["model"], "model-a"); + assert_eq!(chunk["id"], identity.id); + assert_eq!(chunk["created"], identity.created); + assert_eq!(chunk["model"], identity.model); } let usage: Vec<_> = chunks .iter() @@ -298,6 +304,14 @@ fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() { assert_eq!(usage.len(), usize::from(include_usage)); if include_usage { assert_eq!(usage[0]["usage"]["total_tokens"], 18); + let mut accumulator = ChatAccumulator::default(); + for chunk in &chunks { + accumulator.push(chunk).unwrap(); + } + assert_eq!( + accumulator.finish().unwrap(), + project_response(&terminal["response"], &identity).unwrap() + ); } } } @@ -439,7 +453,6 @@ fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() { "stop" ); } else { - assert!(response.error.is_none(), "{:?}", response.error); let body = json_body(response); assert_eq!(body["choices"][0]["message"]["content"], "preserved"); assert_eq!(body["choices"][0]["finish_reason"], "stop"); @@ -471,7 +484,6 @@ fn incomplete_projects_only_supported_finish_reasons() { expected ); } else { - assert!(response.error.is_none(), "{:?}", response.error); assert_eq!(json_body(response)["choices"][0]["finish_reason"], expected); } } @@ -529,7 +541,6 @@ fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_projected() .clone(); (body, combined(&chunks, "content"), usage) } else { - assert!(response.error.is_none(), "{:?}", response.error); let body = json_body(response); ( body.to_string(), @@ -762,6 +773,24 @@ fn conflicting_text_snapshot_fails_instead_of_appending_replacement_content() { fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_streams() { let custom = json!({"id":"ct_1","type":"custom_tool_call","call_id":"call_custom","name":"patch","input":"first\nsecond"}); let function = json!({"id":"fc_1","type":"function_call","call_id":"call_function","name":"lookup","arguments":"{}"}); + let output = json!([ + custom, function, + {"type":"reasoning","id":"reason","summary":[{"type":"summary_text","text":"thought"}],"encrypted_content":"PRIVATE_REASONING"}, + {"type":"message","id":"refusal","role":"assistant","status":"completed","content":[{"type":"refusal","refusal":"no"}]} + ]); + let direct = + project_response(&completed(output.clone())["response"], &chat_identity()).unwrap(); + let projected = &direct["choices"][0]["message"]; + assert_eq!(projected["refusal"], "no"); + assert_eq!(projected["reasoning_content"], "thought"); + assert_eq!( + projected["tool_calls"], + json!([ + {"id":"call_custom","type":"custom","custom":{"name":"patch","input":"first\nsecond"}}, + {"id":"call_function","type":"function","function":{"name":"lookup","arguments":"{}"}} + ]) + ); + assert!(!direct.to_string().contains("PRIVATE_REASONING")); for streaming in [false, true] { let mut initial_custom = custom.clone(); initial_custom["input"] = json!(""); @@ -789,12 +818,14 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream "response.custom_tool_call_input.done", json!({"output_index":0,"item_id":"ct_1","input":"first\nsecond"}), ), - completed(json!([custom, function])), + completed(output.clone()), ])); let response = fixture.post(chat_request(streaming)); - assert!(response.error.is_none(), "{:?}", response.error); if streaming { - let (_, chunks) = sse_body(response); + let (body, chunks) = sse_body(response); + assert_eq!(combined(&chunks, "refusal"), "no"); + assert_eq!(combined(&chunks, "reasoning_content"), "thought"); + assert!(!body.contains("PRIVATE_REASONING")); let calls = chunks .iter() .filter_map(|chunk| chunk["choices"][0]["delta"]["tool_calls"].as_array()) @@ -831,13 +862,7 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream ); } else { let body = json_body(response); - assert_eq!( - body["choices"][0]["message"]["tool_calls"], - json!([ - {"id":"call_custom","type":"custom","custom":{"name":"patch","input":"first\nsecond"}}, - {"id":"call_function","type":"function","function":{"name":"lookup","arguments":"{}"}} - ]) - ); + assert_eq!(body, direct); } } } @@ -859,7 +884,6 @@ fn image_previews_and_final_images_are_projected_once_per_distinct_snapshot() { completed(json!([image, message("created")])), ])); let response = fixture.post(chat_request(streaming)); - assert!(response.error.is_none(), "{:?}", response.error); if streaming { let (_, chunks) = sse_body(response); let images = chunks @@ -903,7 +927,6 @@ fn output_logprobs_survive_json_projection_and_stream_snapshot_deduplication() { completed(json!([output])), ])); let response = fixture.post(chat_request(streaming)); - assert!(response.error.is_none(), "{:?}", response.error); if streaming { let (_, chunks) = sse_body(response); let values = chunks @@ -960,64 +983,3 @@ fn streaming_citation_offsets_follow_delivered_text_when_messages_interleave() { assert_eq!(annotations[0]["url_citation"]["start_index"], 4); assert_eq!(annotations[0]["url_citation"]["end_index"], 6); } - -fn codec_message(text: &str) -> Value { - json!({"type":"message","id":"msg","role":"assistant","status":"completed","content":[{"type":"output_text","text":text,"annotations":[]}]}) -} -fn codec_completed(output: Value) -> Value { - json!({"type":"response.completed","response":{"id":"native","status":"completed","output":output,"usage":{"input_tokens":3,"output_tokens":5,"total_tokens":8}}}) -} - -#[test] -fn deduplicates_snapshots_and_preserves_usage_and_identity() { - let mut encoder = ChatStreamEncoder::new(super::super::identity(), true); - let mut accumulator = ChatAccumulator::default(); - let terminal = codec_completed(json!([codec_message("你好 🌍")])); - for event in [ - json!({"type":"response.created","response":{"id":"native"}}), - json!({"type":"response.output_text.delta","output_index":0,"content_index":0,"item_id":"msg","delta":"你好 "}), - json!({"type":"response.output_text.done","output_index":0,"content_index":0,"item_id":"msg","text":"你好 🌍"}), - terminal.clone(), - ] { - for chunk in encoder.push_event(None, &event).unwrap() { - accumulator.push(&chunk).unwrap(); - } - } - assert!(encoder.is_completed()); - assert!(encoder.finish().unwrap().is_empty()); - let result = accumulator.finish().unwrap(); - assert_eq!(result["choices"][0]["message"]["content"], "你好 🌍"); - assert_eq!(result["usage"]["total_tokens"], 8); - assert_eq!(result["id"], "chatcmpl-test"); - assert_eq!( - result, - project_response(&terminal["response"], &super::super::identity()).unwrap() - ); -} - -#[test] -fn custom_function_reasoning_and_refusal_keep_separate_shapes() { - let response = codec_completed( - json!([{"type":"custom_tool_call","id":"custom","call_id":"a","name":"shell","input":"pwd","status":"completed"},{"type":"function_call","id":"function","call_id":"b","name":"read","arguments":"{}","status":"completed"},{"type":"reasoning","id":"reason","summary":[{"type":"summary_text","text":"thought"}],"encrypted_content":"secret"},{"type":"message","id":"refusal","role":"assistant","status":"completed","content":[{"type":"refusal","refusal":"no"}]}]), - ); - let result = project_response(&response["response"], &super::super::identity()).unwrap(); - let message = &result["choices"][0]["message"]; - assert_eq!(message["refusal"], "no"); - assert_eq!(message["reasoning_content"], "thought"); - assert_eq!(message["tool_calls"][0]["custom"]["input"], "pwd"); - assert_eq!(message["tool_calls"][1]["function"]["arguments"], "{}"); - assert!(!result.to_string().contains("secret")); -} - -#[test] -fn conflicting_snapshots_and_eof_fail_without_synthesizing_success() { - let mut encoder = ChatStreamEncoder::new(super::super::identity(), false); - encoder.push_event(None,&json!({"type":"response.output_text.delta","output_index":0,"content_index":0,"item_id":"msg","delta":"sent"})).unwrap(); - assert_eq!(encoder.finish().unwrap_err(), ChatError::IncompleteStream); - assert_eq!( - encoder - .push_event(None, &codec_completed(json!([codec_message("different")]))) - .unwrap_err(), - ChatError::InvalidResponse - ); -} diff --git a/backend/crates/gateway-protocol/tests/genai/tokens.rs b/backend/crates/gateway-protocol/tests/genai/tokens.rs index 954be621c..fb29f2b92 100644 --- a/backend/crates/gateway-protocol/tests/genai/tokens.rs +++ b/backend/crates/gateway-protocol/tests/genai/tokens.rs @@ -1,4 +1,4 @@ -//! 原生完整请求优先级和 Messages 计数投影合同 +//! 原生完整计数请求的优先级与字段保留 use gateway_protocol::genai::count_tokens_request; use serde_json::json; diff --git a/backend/crates/providers/antigravity/tests/provider/execution.rs b/backend/crates/providers/antigravity/tests/provider/execution.rs index 1f6d6339c..ba7d515e2 100644 --- a/backend/crates/providers/antigravity/tests/provider/execution.rs +++ b/backend/crates/providers/antigravity/tests/provider/execution.rs @@ -617,38 +617,42 @@ async fn other_native_harnesses_are_rejected_without_synthetic_prewarm_or_accoun }; let upstream = MockServer::start().await; let fixture = Fixture::new(&upstream.uri()); - for protocol in ["openai", "anthropic"] { - for body in [ + for (protocol, body) in [ + ( + "openai", json!({"model":"fixture-model","generate":false,"input":[]}), + ), + ( + "openai", json!({"model":"fixture-model","previous_response_id":"foreign","input":[]}), + ), + ( + "anthropic", json!({"model":"fixture-model","messages":[{"role":"user","content":"hello"}]}), - ] { - let operation = Operation::Generate(GenerateRequest::from_protocol_payload( - ProtocolPayload::json_object(protocol, body.as_object().unwrap().clone()).unwrap(), - )); - assert!( - fixture - .provider - .local_websocket_prewarm( - &operation, - &ModelRequestId::new("req_foreign").unwrap() - ) - .is_none() - ); - let error = fixture + ), + ] { + let operation = Operation::Generate(GenerateRequest::from_protocol_payload( + ProtocolPayload::json_object(protocol, body.as_object().unwrap().clone()).unwrap(), + )); + assert!( + fixture .provider - .clone() - .execute( - ProviderRequest::new(operation, request(false).candidate().clone()), - context(frozen_profile(), CancellationToken::new()), - ) - .await - .err() - .expect("foreign native harness cannot be translated"); - assert_eq!(error.kind(), ProviderErrorKind::Unsupported); - assert_eq!(error.send_state(), UpstreamSendState::NotSent); - assert!(error.continuation_recovery_disposition().is_none()); - } + .local_websocket_prewarm(&operation, &ModelRequestId::new("req_foreign").unwrap()) + .is_none() + ); + let error = fixture + .provider + .clone() + .execute( + ProviderRequest::new(operation, request(false).candidate().clone()), + context(frozen_profile(), CancellationToken::new()), + ) + .await + .err() + .expect("foreign native harness cannot be translated"); + assert_eq!(error.kind(), ProviderErrorKind::Unsupported); + assert_eq!(error.send_state(), UpstreamSendState::NotSent); + assert!(error.continuation_recovery_disposition().is_none()); } assert!(upstream.received_requests().await.unwrap().is_empty()); assert_eq!(fixture.store.scheduling_reads.load(Ordering::SeqCst), 0); @@ -775,7 +779,7 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease() } #[tokio::test] -async fn chat_function_choice_preserves_functions_and_unspecified_output_limit() { +async fn chat_preserves_functions_without_inventing_generation_limits() { use gateway_core::{ engine::provider::ProviderRequest, operation::{GenerateRequest, Operation, ProtocolPayload}, @@ -787,18 +791,13 @@ async fn chat_function_choice_preserves_functions_and_unspecified_output_limit() "data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"ok\"}]},\"finishReason\":\"STOP\"}]}}\n\n", "text/event-stream", )) - .expect(4).mount(&upstream).await; + .expect(2).mount(&upstream).await; let function = json!({"type":"function","function":{"name":"pwd","parameters":{"type":"object"}}}); - for choice in [ - json!(null), - json!("auto"), - json!("required"), - json!({"type":"allowed_tools","allowed_tools":{"mode":"required","tools":[function]}}), - ] { + for explicit_null_limit in [false, true] { let fixture = Fixture::new(&upstream.uri()); - let mut body = json!({"model":"fixture-model","stream":true,"messages":[{"role":"user","content":"hello"}],"tools":[function],"tool_choice":choice}); - if choice == "required" { + let mut body = json!({"model":"fixture-model","stream":true,"messages":[{"role":"user","content":"hello"}],"tools":[function]}); + if explicit_null_limit { body["max_completion_tokens"] = json!(null); } let operation = Operation::Generate(GenerateRequest::from_protocol_payload( diff --git a/backend/crates/providers/openai/tests/provider/contract/mod.rs b/backend/crates/providers/openai/tests/provider/contract/mod.rs index 6ca16ea2e..b71d13f8f 100644 --- a/backend/crates/providers/openai/tests/provider/contract/mod.rs +++ b/backend/crates/providers/openai/tests/provider/contract/mod.rs @@ -222,38 +222,6 @@ async fn native_openai_rejects_foreign_harness_before_middleware_rewriting() { assert!(server.received_requests().await.unwrap().is_empty()); } -#[tokio::test] -async fn native_openai_rejects_unknown_protocol_before_send() { - let store = Arc::new(MemoryAccountStore::default()); - create_account(&store, "acct_provider_contract").await; - let server = MockServer::start().await; - let source = Operation::Generate(GenerateRequest::from_protocol_payload( - ProtocolPayload::json_object( - "example-source", - Map::from_iter([("opaque".to_owned(), json!("source-only"))]), - ) - .unwrap() - .with_context(Map::from_iter([("use_websocket".to_owned(), json!(false))])), - )); - let error = match provider_with_base_url(&store, server.uri()) - .execute( - planned_request("openai", source), - context_with_middleware( - "req_native_translate_missing", - Arc::new(PassThroughMiddleware), - FastMode::Default, - ), - ) - .await - { - Ok(_) => panic!("unknown source cannot use native Responses"), - Err(error) => error, - }; - assert_eq!(error.kind(), ProviderErrorKind::NoEligibleAccount); - assert_eq!(error.send_state(), UpstreamSendState::NotSent); - assert!(server.received_requests().await.unwrap().is_empty()); -} - #[tokio::test] async fn native_openai_rejects_capability_expanding_rewrite_before_send() { let store = Arc::new(MemoryAccountStore::default()); @@ -1630,20 +1598,6 @@ impl MiddlewarePlan for RequestRewriteMiddleware { } } -#[derive(Debug)] -struct PassThroughMiddleware; - -impl MiddlewarePlan for PassThroughMiddleware { - fn handle( - &self, - _: MiddlewareContext, - request: MiddlewareRequest, - next: MiddlewareNext, - ) -> BoxFuture<'static, Result> { - next.run(request) - } -} - #[derive(Debug)] struct RecordingMiddleware { observed: Arc>>>, diff --git a/backend/crates/providers/xai/tests/transport/canonical.rs b/backend/crates/providers/xai/tests/transport/canonical.rs index cc3b0bb1c..490012cea 100644 --- a/backend/crates/providers/xai/tests/transport/canonical.rs +++ b/backend/crates/providers/xai/tests/transport/canonical.rs @@ -741,36 +741,6 @@ fn decoder_should_preserve_image_and_hosted_tool_items_without_inventing_facts() ); } -#[test] -fn decoder_should_preserve_an_internal_search_name_declared_by_the_client() { - let request = tool_request(serde_json::json!({ - "model": "client", - "prompt_cache_key": "cache-session", - "input": "hello", - "tools": [{ - "type": "function", - "name": "x_user_search", - "parameters": {"type": "object"} - }] - })); - let body = concat!( - "event: response.created\n", - "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_declared\"}}\n\n", - "event: response.output_item.added\n", - "data: {\"type\":\"response.output_item.added\",\"output_index\":0,\"item\":{\"type\":\"function_call\",\"id\":\"item_client\",\"call_id\":\"call_client\",\"name\":\"x_user_search\",\"arguments\":\"{}\"}}\n\n", - "event: response.completed\n", - "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_declared\",\"status\":\"completed\"}}\n\n", - ); - - let events = GrokCanonicalDecoder::for_request("grok-4.5", &request) - .push(body.as_bytes()) - .expect("client-declared search function"); - - assert!(wire_events(&events).iter().any(|event| { - event.data().pointer("/item/name") == Some(&serde_json::json!("x_user_search")) - })); -} - #[test] fn decoder_should_tolerate_mismatched_event_identity_and_preserve_the_wire_event() { let body = concat!( diff --git a/backend/crates/providers/xai/tests/transport/request/mod.rs b/backend/crates/providers/xai/tests/transport/request/mod.rs index a592a2cff..2ef83e05b 100644 --- a/backend/crates/providers/xai/tests/transport/request/mod.rs +++ b/backend/crates/providers/xai/tests/transport/request/mod.rs @@ -123,20 +123,6 @@ fn explicit_session_should_be_tenant_isolated_and_stable_across_turns() { ); } -#[test] -fn soft_session_should_not_enable_the_native_cache_route() { - let request = raw_request(json!({ - "model": "client", - "instructions": "stable system", - "input": [{"role": "user", "content": "first prompt"}] - })); - - let encoded = - GrokResponsesRequest::encode(&request, "grok-4.5", &client_key()).expect("request"); - - assert!(!encoded.body().contains_key("tools")); -} - #[test] fn soft_session_should_follow_the_first_user_anchor() { let first = raw_request(json!({ @@ -203,26 +189,4 @@ fn native_business_fields_and_harness_items_are_not_rewritten() { assert_eq!(encoded.body().get(key), Some(value), "{key}"); } assert!(!encoded.body().contains_key("store")); - assert_eq!(encoded.body()["include"], json!(["native.future"])); -} - -#[test] -fn cache_routing_does_not_inject_tools_or_change_tool_choice() { - for tools in [ - None, - Some(json!([])), - Some(json!([{"type":"function","name":"web_search","parameters":{"type":"object"}}])), - ] { - let mut body = - json!({"input":"hello","prompt_cache_key":"session","tool_choice":"required"}); - if let Some(tools) = tools { - body["tools"] = tools; - } - let encoded = - GrokResponsesRequest::encode(&raw_request(body.clone()), "grok-4.7", &client_key()) - .unwrap(); - assert_eq!(encoded.body().get("tools"), body.get("tools")); - assert_eq!(encoded.body()["tool_choice"], "required"); - assert!(encoded.session_id().is_some()); - } }