declarations_are_bounded_unique_and_closed_before_render still asserted that
temperature 0.4 is rejected, which cce4333 made valid. Assert acceptance of an
in-range value and rejection of an out-of-range one (2.5).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
544 lines
20 KiB
Rust
544 lines
20 KiB
Rust
//! Independent synthetic protocol fixtures for the experimental native tool adapter.
|
|
//! No model, provider, device, external schema resolver or tool execution is used.
|
|
use serde_json::{Value, json};
|
|
use strata_desktop_core::{
|
|
runtime_rpc::proto::Usage,
|
|
runtime_tool_response::ToolResponse,
|
|
runtime_tools::{ValidatedSegment, prepare},
|
|
};
|
|
|
|
fn function(name: &str) -> Value {
|
|
json!({"type":"function","name":name,"parameters":{
|
|
"type":"object","properties":{"path":{"type":"string"}},
|
|
"required":["path"],"additionalProperties":false}})
|
|
}
|
|
|
|
fn request(tools: Vec<Value>) -> Value {
|
|
json!({"model":"native_fixture","input":"Read the synthetic fixture.",
|
|
"max_output_tokens":64,"tools":tools})
|
|
}
|
|
|
|
fn call(name: &str, parameters: &[(&str, &str)]) -> String {
|
|
let mut raw = format!("<tool_call><function={name}>");
|
|
for (key, value) in parameters {
|
|
raw.push_str(&format!("<parameter={key}>{value}</parameter>"));
|
|
}
|
|
raw.push_str("</function></tool_call>");
|
|
raw
|
|
}
|
|
|
|
fn usage() -> Usage {
|
|
Usage {
|
|
input_tokens: 17,
|
|
output_tokens: 9,
|
|
reused_input_tokens: 3,
|
|
}
|
|
}
|
|
|
|
fn events(bytes: &[axum::body::Bytes]) -> Vec<Value> {
|
|
bytes
|
|
.iter()
|
|
.map(|bytes| {
|
|
let text = std::str::from_utf8(bytes).unwrap();
|
|
let data = text
|
|
.lines()
|
|
.find_map(|line| line.strip_prefix("data: "))
|
|
.unwrap();
|
|
let value: Value = serde_json::from_str(data).unwrap();
|
|
assert!(text.starts_with(&format!("event: {}\n", value["type"].as_str().unwrap())));
|
|
value
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
#[test]
|
|
fn no_tool_prompt_retains_literal_template_bytes() {
|
|
let plan = prepare(&json!({"model":"native_fixture","input":" hello "})).unwrap();
|
|
assert_eq!(plan.max_output_tokens, 256);
|
|
assert_eq!(
|
|
plan.prompt,
|
|
"<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
|
|
);
|
|
assert!(
|
|
matches!(&plan.policy.parse_output("plain text").unwrap()[0], ValidatedSegment::Text(text) if text == "plain text")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn declarations_are_bounded_unique_and_closed_before_render() {
|
|
let valid = prepare(&request(vec![function("read")])).unwrap();
|
|
assert_eq!(valid.max_output_tokens, 64);
|
|
assert!(valid.prompt.contains("read"));
|
|
for tools in [
|
|
vec![function("read"), function("read")],
|
|
vec![json!({"type":"web_search"})],
|
|
vec![
|
|
json!({"type":"custom","name":"run","format":{"type":"grammar","syntax":"lark","definition":"start: WORD"}}),
|
|
],
|
|
vec![
|
|
json!({"type":"function","name":"read","parameters":{"type":"object"},"surprise":true}),
|
|
],
|
|
(0..129).map(|i| function(&format!("read_{i}"))).collect(),
|
|
] {
|
|
assert!(prepare(&request(tools)).is_err());
|
|
}
|
|
for (field, value) in [
|
|
("previous_response_id", json!("resp_old")),
|
|
("store", json!(true)),
|
|
// Sampling controls are forwarded since cce4333, but only inside the Original's ranges.
|
|
("temperature", json!(2.5)),
|
|
("unexpected_field", json!(true)),
|
|
] {
|
|
let mut invalid = request(vec![function("read")]);
|
|
invalid[field] = value;
|
|
assert!(prepare(&invalid).is_err(), "field {field}");
|
|
}
|
|
let mut sampled = request(vec![function("read")]);
|
|
sampled["temperature"] = json!(0.4);
|
|
assert!(
|
|
prepare(&sampled).is_ok(),
|
|
"an in-range temperature is accepted"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn choice_requires_declared_identity_and_controls_call_presence() {
|
|
let raw = call("read", &[("path", "fixture")]);
|
|
for choice in [
|
|
json!("auto"),
|
|
json!("required"),
|
|
json!({"type":"function","name":"read"}),
|
|
] {
|
|
let mut req = request(vec![function("read")]);
|
|
req["tool_choice"] = choice;
|
|
let plan = prepare(&req).unwrap();
|
|
assert!(plan.policy.parse_output(&raw).is_ok());
|
|
if req["tool_choice"] != "auto" {
|
|
assert!(plan.policy.parse_output("text alone").is_err());
|
|
}
|
|
}
|
|
let mut none = request(vec![function("read")]);
|
|
none["tool_choice"] = json!("none");
|
|
let plan = prepare(&none).unwrap();
|
|
assert!(plan.policy.parse_output("text alone").is_ok());
|
|
assert!(plan.policy.parse_output(&raw).is_err());
|
|
for choice in [
|
|
json!("unknown"),
|
|
json!({"type":"function","name":"absent"}),
|
|
json!({"type":"function","name":"read","extra":1}),
|
|
] {
|
|
let mut req = request(vec![function("read")]);
|
|
req["tool_choice"] = choice;
|
|
assert!(prepare(&req).is_err());
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn allowed_subset_and_parallel_false_are_enforced_after_whole_parse() {
|
|
let mut req = request(vec![function("read"), function("write")]);
|
|
req["tool_choice"] = json!({"type":"allowed_tools","mode":"required","tools":[{"type":"function","name":"read"}]});
|
|
let plan = prepare(&req).unwrap();
|
|
assert!(
|
|
plan.policy
|
|
.parse_output(&call("read", &[("path", "a")]))
|
|
.is_ok()
|
|
);
|
|
assert!(
|
|
plan.policy
|
|
.parse_output(&call("write", &[("path", "a")]))
|
|
.is_err()
|
|
);
|
|
assert!(plan.policy.parse_output("text alone").is_err());
|
|
req["tool_choice"]["tools"] = json!([{"type":"function","name":"absent"}]);
|
|
assert!(prepare(&req).is_err());
|
|
let mut req = request(vec![function("read")]);
|
|
req["parallel_tool_calls"] = json!(false);
|
|
let plan = prepare(&req).unwrap();
|
|
let one = call("read", &[("path", "a")]);
|
|
assert!(plan.policy.parse_output(&one).is_ok());
|
|
assert!(plan.policy.parse_output(&format!("{one}\n{one}")).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn schema_required_additional_and_nullable_values_are_independent() {
|
|
let tool = json!({"type":"function","name":"read","parameters":{
|
|
"type":"object","properties":{"path":{"type":["string","null"]}},
|
|
"required":["path"],"additionalProperties":false}});
|
|
let plan = prepare(&request(vec![tool])).unwrap();
|
|
for (raw, expected) in [("null", Value::Null), ("123", json!("123"))] {
|
|
let parsed = plan
|
|
.policy
|
|
.parse_output(&call("read", &[("path", raw)]))
|
|
.unwrap();
|
|
let ValidatedSegment::Call(item) = &parsed[0] else {
|
|
panic!("expected call");
|
|
};
|
|
let arguments: Value = serde_json::from_str(item["arguments"].as_str().unwrap()).unwrap();
|
|
assert_eq!(arguments, json!({"path":expected}));
|
|
assert_eq!(item["name"], "read");
|
|
assert_eq!(item["type"], "function_call");
|
|
assert!(item.get("id").is_none());
|
|
assert!(item.get("call_id").is_none());
|
|
assert!(item.get("status").is_none());
|
|
}
|
|
assert!(plan.policy.parse_output(&call("read", &[])).is_err());
|
|
assert!(
|
|
plan.policy
|
|
.parse_output(&call("read", &[("path", "a"), ("extra", "1")]))
|
|
.is_err()
|
|
);
|
|
let typed = prepare(&request(vec![json!({"type":"function","name":"count","parameters":{
|
|
"type":"object","properties":{"n":{"type":"integer","minimum":1}},"required":["n"],"additionalProperties":false}})])).unwrap();
|
|
for bad in ["0", "1.5", "null", "oops"] {
|
|
assert!(
|
|
typed
|
|
.policy
|
|
.parse_output(&call("count", &[("n", bad)]))
|
|
.is_err()
|
|
);
|
|
}
|
|
assert!(
|
|
typed
|
|
.policy
|
|
.parse_output(&call("count", &[("n", "2")]))
|
|
.is_ok()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn schema_local_refs_work_and_all_external_reference_forms_refuse() {
|
|
let schema = json!({"type":"object","$defs":{"path":{"type":"string"}},
|
|
"properties":{"path":{"$ref":"#/$defs/path"}},"required":["path"],"additionalProperties":false});
|
|
let plan = prepare(&request(vec![
|
|
json!({"type":"function","name":"read","parameters":schema}),
|
|
]))
|
|
.unwrap();
|
|
assert!(
|
|
plan.policy
|
|
.parse_output(&call("read", &[("path", "fixture")]))
|
|
.is_ok()
|
|
);
|
|
for key in ["$ref", "$dynamicRef", "$recursiveRef"] {
|
|
for reference in [
|
|
"https://example.invalid/schema",
|
|
"file:///etc/private",
|
|
"../schema.json",
|
|
] {
|
|
let mut schema = json!({"type":"object","properties":{"deep":{"allOf":[{}]}}});
|
|
schema["properties"]["deep"]["allOf"][0][key] = json!(reference);
|
|
assert!(
|
|
prepare(&request(vec![
|
|
json!({"type":"function","name":"read","parameters":schema})
|
|
]))
|
|
.is_err(),
|
|
"{key} {reference}"
|
|
);
|
|
}
|
|
}
|
|
let bad = request(vec![
|
|
json!({"type":"function","name":"read","parameters":{"type":"bogus"}}),
|
|
]);
|
|
assert!(prepare(&bad).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn namespaced_custom_regex_restores_exact_identity_and_input() {
|
|
// Independently frozen SHA256("ops/run")[0..24], not obtained from Catalog.
|
|
const ALIAS: &str = "ns_7d2bb0bfd31e620d6d5c9097";
|
|
let req = request(vec![json!({"type":"namespace","name":"ops","tools":[{
|
|
"type":"custom","name":"run","format":{"type":"grammar","syntax":"regex","definition":"[A-Z]+ [0-9]+"}}]})]);
|
|
let plan = prepare(&req).unwrap();
|
|
assert!(plan.prompt.contains(ALIAS));
|
|
let parsed = plan
|
|
.policy
|
|
.parse_output(&call(ALIAS, &[("input", "MOVE 12")]))
|
|
.unwrap();
|
|
let ValidatedSegment::Call(item) = &parsed[0] else {
|
|
panic!("expected custom call");
|
|
};
|
|
assert_eq!(
|
|
item,
|
|
&json!({"type":"custom_tool_call","name":"run","namespace":"ops","input":"MOVE 12"})
|
|
);
|
|
for raw in ["move 12", "MOVE 12 trailing", "", "MOVE\n12"] {
|
|
assert!(
|
|
plan.policy
|
|
.parse_output(&call(ALIAS, &[("input", raw)]))
|
|
.is_err()
|
|
);
|
|
}
|
|
assert!(
|
|
plan.policy
|
|
.parse_output(&call("run", &[("input", "MOVE 12")]))
|
|
.is_err()
|
|
);
|
|
|
|
let mut forced = req.clone();
|
|
forced["tool_choice"] = json!({"type":"custom","name":"run","namespace":"ops"});
|
|
let forced_plan = prepare(&forced).unwrap();
|
|
assert!(
|
|
forced_plan
|
|
.policy
|
|
.parse_output(&call(ALIAS, &[("input", "MOVE 12")]))
|
|
.is_ok()
|
|
);
|
|
forced["tool_choice"] = json!({"type":"custom","name":"run"});
|
|
assert!(prepare(&forced).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn exact_call_result_ids_type_and_order_gate_continuation() {
|
|
let mut req = request(vec![function("read")]);
|
|
let prior = json!({"type":"function_call","call_id":"call_fixture","name":"read","arguments":"{\"path\":\"fixture\"}"});
|
|
let result = json!({"type":"function_call_output","call_id":"call_fixture","output":"owned synthetic result"});
|
|
req["input"] =
|
|
json!([{"role":"user","content":"read"},prior,result,{"role":"user","content":"continue"}]);
|
|
let plan = prepare(&req).unwrap();
|
|
assert!(plan.prompt.contains("owned synthetic result"));
|
|
for input in [
|
|
json!([result]),
|
|
json!([result, prior]),
|
|
json!([prior, result, result]),
|
|
json!([prior, prior, result]),
|
|
json!([prior,{"type":"function_call_output","call_id":"call_other","output":"x"}]),
|
|
json!([prior,{"type":"custom_tool_call_output","call_id":"call_fixture","output":"x"}]),
|
|
json!([{"type":"function_call","call_id":"call_fixture","name":"absent","arguments":"{}"},result]),
|
|
] {
|
|
req["input"] = input;
|
|
assert!(prepare(&req).is_err());
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn parallel_history_resolves_ids_and_renders_results_in_call_order() {
|
|
let mut req = request(vec![function("read")]);
|
|
req["input"] = json!([
|
|
{"role":"user","content":"read twice"},
|
|
{"type":"function_call","call_id":"call_A","name":"read","arguments":"{\"path\":\"first\"}"},
|
|
{"type":"function_call","call_id":"call_B","name":"read","arguments":"{\"path\":\"second\"}"},
|
|
{"type":"function_call_output","call_id":"call_B","output":"RESULT_B_LITERAL"},
|
|
{"type":"function_call_output","call_id":"call_A","output":"RESULT_A_LITERAL"},
|
|
{"role":"user","content":"continue"}
|
|
]);
|
|
let prompt = prepare(&req).unwrap().prompt;
|
|
assert!(prompt.find("RESULT_A_LITERAL").unwrap() < prompt.find("RESULT_B_LITERAL").unwrap());
|
|
req["input"][4]["call_id"] = json!("call_B");
|
|
assert!(prepare(&req).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn unknown_incomplete_duplicate_or_late_invalid_call_refuses_entire_output() {
|
|
let plan = prepare(&request(vec![function("read")])).unwrap();
|
|
let valid = call("read", &[("path", "fixture")]);
|
|
for invalid in [
|
|
"<tool_call><function=read><parameter=path>half".to_owned(),
|
|
call("absent", &[]),
|
|
call("read", &[("path", "a"), ("path", "b")]),
|
|
call("read", &[]),
|
|
"</tool_call>".to_owned(),
|
|
"<function=read></function>".to_owned(),
|
|
"<tool_call".to_owned(),
|
|
] {
|
|
assert!(
|
|
plan.policy
|
|
.parse_output(&format!("visible-looking text\n{valid}\n{invalid}"))
|
|
.is_err()
|
|
);
|
|
}
|
|
}
|
|
|
|
fn function_item() -> ValidatedSegment {
|
|
ValidatedSegment::Call(
|
|
json!({"type":"function_call","name":"read","arguments":"{\"path\":\"fixture\"}"}),
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn publisher_indices_sequence_ids_and_deltas_have_one_terminal() {
|
|
let mut publisher = ToolResponse::new("resp_fixed".into(), "native_fixture".into());
|
|
let opening = publisher.beginning();
|
|
assert_eq!(opening.len(), 2);
|
|
for event in events(&opening) {
|
|
assert_eq!(event["response"]["output"], json!([]));
|
|
}
|
|
assert!(publisher.beginning().is_empty());
|
|
let long_text = format!("{}🦩", "x".repeat(8191));
|
|
let segments = vec![
|
|
ValidatedSegment::Text(String::new()),
|
|
ValidatedSegment::Text(long_text.clone()),
|
|
function_item(),
|
|
ValidatedSegment::Call(
|
|
json!({"type":"custom_tool_call","name":"run","namespace":"ops","input":"MOVE 12"}),
|
|
),
|
|
];
|
|
let (completion, response) = publisher.complete(segments, &usage(), "stop").unwrap();
|
|
let mut all = events(&opening);
|
|
all.extend(events(&completion));
|
|
for (index, event) in all.iter().enumerate() {
|
|
assert_eq!(event["sequence_number"], index);
|
|
assert_eq!(event["response_id"], "resp_fixed");
|
|
}
|
|
let output = response["output"].as_array().unwrap();
|
|
assert_eq!(output.len(), 3);
|
|
assert_eq!(
|
|
response["usage"],
|
|
json!({"input_tokens":17,"output_tokens":9,"total_tokens":26,"input_tokens_details":{"cached_tokens":3}})
|
|
);
|
|
let added: Vec<_> = all
|
|
.iter()
|
|
.filter(|e| e["type"] == "response.output_item.added")
|
|
.collect();
|
|
assert_eq!(
|
|
added
|
|
.iter()
|
|
.map(|e| e["output_index"].as_u64().unwrap())
|
|
.collect::<Vec<_>>(),
|
|
vec![0, 1, 2]
|
|
);
|
|
for index in 1..3 {
|
|
assert_eq!(added[index]["item"]["id"], output[index]["id"]);
|
|
assert_eq!(added[index]["item"]["call_id"], output[index]["call_id"]);
|
|
assert_eq!(output[index]["status"], "completed");
|
|
assert!(
|
|
output[index]["call_id"]
|
|
.as_str()
|
|
.unwrap()
|
|
.starts_with("call_")
|
|
);
|
|
}
|
|
assert_ne!(output[1]["call_id"], output[2]["call_id"]);
|
|
let reconstructed: String = all
|
|
.iter()
|
|
.filter(|e| e["type"] == "response.output_text.delta")
|
|
.map(|e| e["delta"].as_str().unwrap())
|
|
.collect();
|
|
assert_eq!(reconstructed, long_text);
|
|
assert_eq!(
|
|
all.iter()
|
|
.filter(|e| e["type"] == "response.completed")
|
|
.count(),
|
|
1
|
|
);
|
|
assert_eq!(all.last().unwrap()["response"], response);
|
|
assert!(publisher.complete(vec![], &usage(), "stop").is_err());
|
|
let (after, unchanged) = publisher.failed("invalid_tool_output");
|
|
assert!(after.is_empty());
|
|
assert_eq!(unchanged, response);
|
|
}
|
|
|
|
#[test]
|
|
fn publisher_invalid_late_item_reason_usage_and_bounds_are_atomic() {
|
|
let bad = ValidatedSegment::Call(
|
|
json!({"type":"function_call","name":"read","arguments":"{}","call_id":"injected"}),
|
|
);
|
|
let mut publisher = ToolResponse::new("resp_atomic".into(), "native_fixture".into());
|
|
assert!(
|
|
publisher
|
|
.complete(
|
|
vec![
|
|
ValidatedSegment::Text("early text".into()),
|
|
function_item(),
|
|
bad
|
|
],
|
|
&usage(),
|
|
"stop"
|
|
)
|
|
.is_err()
|
|
);
|
|
let opening = events(&publisher.beginning());
|
|
assert_eq!(opening[0]["sequence_number"], 0);
|
|
assert_eq!(opening[0]["response"]["output"], json!([]));
|
|
for reason in ["tool_calls", "unknown", ""] {
|
|
assert!(
|
|
publisher
|
|
.complete(vec![function_item()], &usage(), reason)
|
|
.is_err()
|
|
);
|
|
}
|
|
for bad in [
|
|
Usage {
|
|
input_tokens: u64::MAX,
|
|
output_tokens: 1,
|
|
reused_input_tokens: 0,
|
|
},
|
|
Usage {
|
|
input_tokens: 1,
|
|
output_tokens: 0,
|
|
reused_input_tokens: 2,
|
|
},
|
|
] {
|
|
assert!(
|
|
publisher
|
|
.complete(vec![function_item()], &bad, "stop")
|
|
.is_err()
|
|
);
|
|
}
|
|
for segments in [
|
|
vec![ValidatedSegment::Text("x".repeat(8 * 1024 * 1024 + 1))],
|
|
(0..129).map(|_| function_item()).collect(),
|
|
(0..1025)
|
|
.map(|_| ValidatedSegment::Text(String::new()))
|
|
.collect(),
|
|
] {
|
|
assert!(publisher.complete(segments, &usage(), "stop").is_err());
|
|
}
|
|
let (ending, response) = publisher
|
|
.complete(vec![function_item()], &usage(), "length")
|
|
.unwrap();
|
|
let ending = events(&ending);
|
|
assert_eq!(ending[0]["sequence_number"], 2);
|
|
assert_eq!(response["status"], "incomplete");
|
|
assert_eq!(
|
|
response["incomplete_details"]["reason"],
|
|
"max_output_tokens"
|
|
);
|
|
assert_eq!(ending.last().unwrap()["type"], "response.incomplete");
|
|
}
|
|
|
|
#[test]
|
|
fn publisher_failure_is_sanitized_and_never_creates_a_tool_item() {
|
|
let mut publisher = ToolResponse::new("resp_failed".into(), "native_fixture".into());
|
|
let (ending, response) = publisher.failed("private model text must not appear");
|
|
assert_eq!(response["error"]["code"], "runtime_generation_failed");
|
|
assert_eq!(response["output"], json!([]));
|
|
assert_eq!(
|
|
events(&ending)
|
|
.iter()
|
|
.filter(|e| e["type"] == "response.failed")
|
|
.count(),
|
|
1
|
|
);
|
|
let (repeat, same) = publisher.failed("runtime_cancelled");
|
|
assert!(repeat.is_empty());
|
|
assert_eq!(same, response);
|
|
}
|
|
|
|
#[test]
|
|
fn published_standard_output_replays_exact_call_identity_with_result() {
|
|
let mut publisher = ToolResponse::new("resp_replay".into(), "native_fixture".into());
|
|
let (_, body) = publisher
|
|
.complete(
|
|
vec![
|
|
ValidatedSegment::Text("I will read.".into()),
|
|
function_item(),
|
|
],
|
|
&usage(),
|
|
"stop",
|
|
)
|
|
.unwrap();
|
|
let mut input = vec![json!({"role":"user","content":"read"})];
|
|
input.extend(body["output"].as_array().unwrap().iter().cloned());
|
|
input.push(json!({"type":"function_call_output","call_id":body["output"][1]["call_id"],"output":"REPLAY_RESULT_LITERAL"}));
|
|
input.push(json!({"role":"user","content":"continue"}));
|
|
let mut req = request(vec![function("read")]);
|
|
req["input"] = json!(input);
|
|
let plan = prepare(&req).unwrap();
|
|
assert!(plan.prompt.contains("I will read."));
|
|
assert!(plan.prompt.contains("REPLAY_RESULT_LITERAL"));
|
|
req["input"][1]["status"] = json!("in_progress");
|
|
assert!(prepare(&req).is_err());
|
|
req["input"][1]["status"] = json!("completed");
|
|
req["input"][1]["content"][0]["annotations"] = json!([{"type":"unknown"}]);
|
|
assert!(prepare(&req).is_err());
|
|
}
|