diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index b0f19737..28607c60 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -4157,6 +4157,141 @@ mod tests { fs::remove_dir_all(root).unwrap(); } + #[tokio::test] + async fn nullable_tool_arguments_agree_across_json_and_live_sse() { + for stream in [false, true] { + for thinking in [false, true] { + for valid in [false, true] { + let (tokenizer, root) = test_tokenizer(); + let (commands, mut received) = mpsc::channel::(1); + let mut state = AppState::default(); + state.worker.write().await.state = WorkerState::Ready; + state.tokenizer = Some(tokenizer.clone()); + state.generation = Some(commands); + let output = format!( + "{}123null\"123\"2", + if thinking { "Think.\n\n" } else { "" } + ); + let mut payload = json!({ + "model":"strata-local", "input":"Lookup", "stream":stream, + "reasoning":{"effort":if thinking { "low" } else { "none" }}, + "tools":[{"type":"function","name":"lookup","parameters":{ + "type":"object","properties":{ + "id":{"type":["string","null"],"enum":[if valid { "123" } else { "456" },null]}, + "empty":{"type":["string","null"]}, + "quoted":{"type":["string","null"]}, + "days":{"type":"integer"} + },"required":["id","empty","quoted","days"],"additionalProperties":false + }}],"store":false + }); + // Streaming is transport only; neither mode rewrites the schema/prompt. + payload["stream"] = json!(false); + let expected_prompt = + render_request_prompt(&serde_json::from_value(payload.clone()).unwrap()) + .unwrap(); + payload["stream"] = json!(stream); + let worker = tokio::spawn(async move { + let command = received.recv().await.unwrap(); + assert_eq!( + tokenizer.decode(&command.request.token_ids).unwrap(), + expected_prompt + ); + let ids = tokenizer.encode(&output, false).unwrap(); + let generated = ids.len() as u64; + let mut events = ids.into_iter().map(Event::Token).collect::>(); + events.push(Event::Done(Done { + generated, + prompt_tokens: command.request.token_ids.len() as u64, + prompt_ms: 1.0, + decode_ms: 2.0, + finish: Finish::Stop, + drafts_accepted: None, + drafts_offered: None, + reused: None, + expert_hits: None, + expert_lookups: None, + })); + match command.result { + GenerationResult::Buffered(sender) => { + sender.send(Ok(events)).unwrap(); + } + GenerationResult::Streaming(sender) => { + for event in events { + // Early validation failure may close the generation receiver. + if sender.send(Ok(event)).await.is_err() { + break; + } + } + } + GenerationResult::Finished => panic!("unexpected finished command"), + } + }); + let response = create(State(state), Ok(Json(payload))).await; + let expected_args = r#"{"days":2,"empty":null,"id":"123","quoted":"\"123\""}"#; + let final_response = + if stream { + assert_eq!(response.status(), StatusCode::OK); + let mut body = response.into_body(); + let mut events = Vec::new(); + while let Some(frame) = body.frame().await { + events.push(parse_sse(&frame.unwrap().into_data().unwrap())); + } + for (n, event) in events.iter().enumerate() { + assert_eq!(event["sequence_number"], n); + } + let terminal = if valid { + "response.completed" + } else { + "response.failed" + }; + assert_eq!(events.last().unwrap()["type"], terminal); + assert_eq!(events.iter().filter(|e| e["type"] == terminal).count(), 1); + let calls = events + .iter() + .filter(|e| e["type"] == "response.function_call_arguments.done") + .collect::>(); + if valid { + assert_eq!(calls.len(), 1); + assert_eq!(calls[0]["arguments"], expected_args); + } else { + assert!(calls.is_empty()); + assert!(!events.iter().any(|e| e["type"] + == "response.function_call_arguments.delta" + || (e["type"] == "response.output_item.added" + && e["item"]["type"] == "function_call"))); + } + events.last().unwrap()["response"].clone() + } else { + assert_eq!( + response.status(), + if valid { + StatusCode::OK + } else { + StatusCode::BAD_GATEWAY + } + ); + serde_json::from_slice::( + &to_bytes(response.into_body(), usize::MAX).await.unwrap(), + ) + .unwrap() + }; + if valid { + let calls = final_response["output"] + .as_array() + .unwrap() + .iter() + .filter(|i| i["type"] == "function_call") + .collect::>(); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0]["arguments"], expected_args); + } + worker.await.unwrap(); + fs::remove_dir_all(root).unwrap(); + } + } + } + } + #[tokio::test] async fn streaming_endpoint_sends_text_before_done_and_finishes_in_order() { let (tokenizer, root) = test_tokenizer(); diff --git a/control-plane/src/tool_output.rs b/control-plane/src/tool_output.rs index dd1a8737..b1ed49d1 100644 --- a/control-plane/src/tool_output.rs +++ b/control-plane/src/tool_output.rs @@ -175,13 +175,8 @@ fn parse_call(text: &str, tools: &[Value]) -> Result<(Segment, usize), String> { .get("parameters") .and_then(|value| value.get("properties")) .and_then(|value| value.get(parameter)) - .and_then(|value| value.get("type")) - .and_then(Value::as_str); - let parsed = if declared == Some("string") { - Value::String(value.to_owned()) - } else { - serde_json::from_str(value).unwrap_or_else(|_| Value::String(value.to_owned())) - }; + .and_then(|value| value.get("type")); + let parsed = parameter_value(value, declared); if arguments.insert(parameter.to_owned(), parsed).is_some() { return Err(format!("duplicate tool parameter: {parameter}")); } @@ -189,6 +184,34 @@ fn parse_call(text: &str, tools: &[Value]) -> Result<(Segment, usize), String> { } } +fn parameter_value(raw: &str, declared: Option<&Value>) -> Value { + let text = || Value::String(raw.to_owned()); + if declared.is_some_and(|kind| kind == "string") { + return text(); + } + let parsed = serde_json::from_str(raw).unwrap_or_else(|_| text()); + if let Some(types) = declared.and_then(Value::as_array) + && types.iter().any(|kind| kind == "string") + { + // Qwen's string parameters are raw text, not JSON string literals. + // A union may opt into another JSON type, but must not turn a nullable + // string such as 123 into an undeclared number (or strip its quotes). + let declared_non_string = types.iter().any(|kind| match kind.as_str() { + Some("null") => parsed.is_null(), + Some("boolean") => parsed.is_boolean(), + Some("number") => parsed.is_number(), + Some("integer") => parsed.as_f64().is_some_and(|n| n.fract() == 0.0), + Some("object") => parsed.is_object(), + Some("array") => parsed.is_array(), + _ => false, + }); + if !declared_non_string { + return text(); + } + } + parsed +} + fn find_parameter_end(text: &str) -> Option { let mut search = 0; while let Some(relative) = text[search..].find("") { @@ -244,6 +267,52 @@ mod tests { ); } + #[test] + fn string_type_unions_preserve_raw_text_and_decode_declared_json_types() { + for (types, raw, expected) in [ + (json!(["string", "null"]), "123", json!("123")), + (json!(["null", "string"]), "false", json!("false")), + (json!(["string", "null"]), "{}", json!("{}")), + (json!(["string", "null"]), "[]", json!("[]")), + (json!(["string", "null"]), "null", Value::Null), + (json!(["string", "null"]), "\"123\"", json!("\"123\"")), + (json!(["string", "null"]), " 123 ", json!(" 123 ")), + (json!(["string", "integer"]), "12", json!(12)), + (json!(["string", "integer"]), "1.5", json!("1.5")), + (json!(["string", "integer"]), "1.0", json!(1.0)), + (json!(["string", "number"]), "1.5", json!(1.5)), + (json!(["string", "boolean"]), "false", json!(false)), + (json!(["string", "object"]), "{}", json!({})), + (json!(["string", "array"]), "[]", json!([])), + (json!(["string"]), "null", json!("null")), + (json!("string"), "null", json!("null")), + (json!("string"), "\"x\"", json!("\"x\"")), + (json!(["integer", "null"]), "12", json!(12)), + ] { + let tools = + [json!({"name":"lookup","parameters":{"properties":{"value":{"type":types}}}})]; + let text = format!( + "{raw}" + ); + let expected = vec![Segment::Call { + name: "lookup".into(), + arguments: json!({"value":expected}), + }]; + assert_eq!( + parse_complete(&text, &tools).unwrap(), + expected, + "{types}: {raw}" + ); + let mut parser = Incremental::new(&tools); + let mut streamed = Vec::new(); + for ch in text.chars() { + streamed.extend(parser.feed(&ch.to_string()).unwrap()); + } + streamed.extend(parser.finish().unwrap()); + assert_eq!(streamed, expected, "stream {types}: {raw}"); + } + } + #[test] fn incomplete_or_undeclared_calls_are_never_published() { let tools = [json!({"name":"write","parameters":{"properties":{}}})]; diff --git a/docs/api-contract.md b/docs/api-contract.md index d7b27442..0954d604 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -229,6 +229,19 @@ The Rust control plane has a `POST /v1/responses` route and a reusable response The offline trace builder accepts text fragments, function-call argument fragments, and token usage. It assembles a non-streaming response or an ordered SSE stream ending in `response.completed`. Tool arguments must form a JSON object. `text.format` supports `text`, `json_object`, and `json_schema` validation in both live serving and the offline builder. External schema references are rejected. The synthetic fixture at `benchmarks/fixtures/responses/structured-tool.json` demonstrates text plus a tool call; it is not evidence of live Codex compatibility. +For native Qwen tool parameters, a direct property `type: "string"` preserves +raw text, including quotes. A direct type array containing `"string"` now does +the same unless the text parses as a declared **non-string** JSON type. Thus +`["string", "null"]` preserves `123`, `false`, `{}` and quoted text as strings, +while the literal `null` selects null. `["string", "integer"]` selects an integer +for `123` and a string for `1.5`. This is a deterministic interpretation of an +ambiguous raw-text format, not a search for any schema-valid coercion. Full-schema +validation still runs before publishing a callable item; enum/range violations +are not retried as strings. Scalar declarations and untyped handling retain +their previous behavior. Type inference through `$ref`, `anyOf` or `oneOf` is +not added by this rule. JSON and both live SSE paths use the same decoder; +CPU fixtures verify argument equality, not real-model tool-call quality. + `control-plane/src/wire.rs` encodes the upstream `GEN` request line and parses the current `T`, `PP`, `DONE`, and `ERR` output lines. The supervisor accepts an internal token-ID generation command, checks its context budget, and sends it to a resident worker. It can return a buffered result or stream bounded token events. Dropping the SSE receiver cancels generation. Native Qwen prompt assembly matches pinned text-only and one representative tool golden case byte-for-byte. The live Qwen parser holds split call markers and rejects incomplete calls; it validates full argument objects before publishing function-call events. Current request parsing supports `model`, string or array `input`, `stream`, `instructions`, `max_output_tokens`, `previous_response_id`, `parallel_tool_calls`, `reasoning`, `text`, named function `tools`, `tool_choice`, `temperature`, `top_p`, `truncation`, `metadata`, and `store`. Unknown fields are rejected. Terminal responses are stored by default; `store: false` disables this. `previous_response_id` replays a stored response with the new input, including function calls and matching results. By default the store is process-local and bounded to 64 responses or 128 MiB, whichever is reached first; old IDs become unavailable after eviction or restart. Multimodal input remains unsupported. The body limit is 16 MiB.