Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

fix(gateway): check tool parameter schemas as sent, without $ref expansion (#1000)

Jan Kadleca1b629790bfd
diff --git a/conformance/anthropic_messages/request_vectors.json b/conformance/anthropic_messages/request_vectors.json
index 6e64d3f83..6a748e68f 100644
--- a/conformance/anthropic_messages/request_vectors.json
+++ b/conformance/anthropic_messages/request_vectors.json
@@ -451,7 +451,10 @@
{"name": "tool name over 64 characters", "body": {"model": "m", "max_tokens": 1, "tools": [{"name": "mcp__a_very_long_server_name__and_an_equally_long_tool_name_beyond", "input_schema": {"type": "object"}}], "messages": [{"role": "user", "content": "x"}]}, "message": "tools.0.name: tool names longer than 64 characters are not supported"},
{"name": "tool name pattern", "body": {"model": "m", "max_tokens": 1, "tools": [{"name": "math.add", "input_schema": {"type": "object"}}], "messages": [{"role": "user", "content": "x"}]}, "message": "tools.0.name: String should match pattern '^[a-zA-Z0-9_-]{1,64}$'"},
{"name": "tool without input_schema", "body": {"model": "m", "max_tokens": 1, "tools": [{"name": "t"}], "messages": [{"role": "user", "content": "x"}]}, "message": "tools.0.input_schema: Field required"},
- {"name": "unsupported schema keyword", "body": {"model": "m", "max_tokens": 1, "tools": [{"name": "t", "input_schema": {"type": "object", "if": {"properties": {"a": {"const": 1}}}, "then": {"required": ["b"]}}}], "messages": [{"role": "user", "content": "x"}]}, "message": "tools.0.input_schema: the schema uses an unsupported JSON Schema keyword (if, then, else, $dynamicRef, unevaluatedProperties, dependentSchemas) or exceeds the size or depth limits"},
+ {"name": "unsupported schema keyword", "body": {"model": "m", "max_tokens": 1, "tools": [{"name": "t", "input_schema": {"type": "object", "if": {"properties": {"a": {"const": 1}}}, "then": {"required": ["b"]}}}], "messages": [{"role": "user", "content": "x"}]}, "message": "tools.0.input_schema.if: JSON Schema keyword 'if' is not supported"},
+ {"name": "several unsupported schema keywords", "body": {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": "x"}], "tools": [{"name": "t", "input_schema": {"type": "object", "else": {}, "if": {}, "then": {}}}]}, "message": "tools.0.input_schema.if: JSON Schema keyword 'if' is not supported"},
+ {"name": "unresolved schema ref", "body": {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": "x"}], "tools": [{"name": "t", "input_schema": {"type": "object", "properties": {"a": {"$ref": "#/$defs/Missing"}}}}]}, "message": "tools.0.input_schema.properties.a.$ref: unresolved internal '$ref' \"#/$defs/Missing\""},
+ {"name": "zero-padded schema ref index", "body": {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": "x"}], "tools": [{"name": "t", "input_schema": {"type": "object", "$defs": {"variants": [{"type": "string"}, {"type": "integer"}]}, "properties": {"a": {"$ref": "#/$defs/variants/01"}}}}]}, "message": "tools.0.input_schema.properties.a.$ref: unresolved internal '$ref' \"#/$defs/variants/01\""},
{"name": "undeclared named tool", "body": {"model": "m", "max_tokens": 1, "tools": [{"name": "a", "input_schema": {"type": "object"}}], "tool_choice": {"type": "tool", "name": "b"}, "messages": [{"role": "user", "content": "x"}]}, "message": "tool_choice.tool.name: tool 'b' is not declared in tools"},
{"name": "tool_choice any without tools", "body": {"model": "m", "max_tokens": 1, "tool_choice": {"type": "any"}, "messages": [{"role": "user", "content": "x"}]}, "message": "tool_choice.any: tool_choice requires tools"},
{"name": "thinking budget below minimum", "body": {"model": "m", "max_tokens": 4096, "thinking": {"type": "enabled", "budget_tokens": 512}, "messages": [{"role": "user", "content": "x"}]}, "message": "thinking.enabled.budget_tokens: Input should be greater than or equal to 1024"},
diff --git a/packages/sie_gateway/src/handlers/grammar.rs b/packages/sie_gateway/src/handlers/grammar.rs
index 33bbf8ad6..561fcecea 100644
--- a/packages/sie_gateway/src/handlers/grammar.rs
+++ b/packages/sie_gateway/src/handlers/grammar.rs
@@ -24,6 +24,10 @@
//! ``$ref`` support is deliberately bounded to internal JSON pointers
//! (``#/...``). External documents, unresolved pointers, and recursive
//! reference cycles are rejected before the worker sees the schema.
+//!
+//! Tool parameter schemas go through :func:`validate_tool_parameters`
+//! instead. They are never compiled into a grammar, so they are checked as
+//! sent, without ``$ref`` expansion.
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
@@ -85,6 +89,11 @@ pub fn check_capability(
/// while keeping the worker compile budget bounded.
pub const MAX_GRAMMAR_BYTES: usize = 64 * 1024;
+/// Maximum size of a tool's parameter schema as sent, in bytes. The same
+/// budget as a grammar, but measured without ``$ref`` expansion; see
+/// :func:`validate_tool_parameters`.
+pub const MAX_TOOL_SCHEMA_BYTES: usize = MAX_GRAMMAR_BYTES;
+
/// Maximum JSON Schema nesting depth. Counted by recursive walks over
/// ``properties`` / ``items`` / ``oneOf`` / ``anyOf`` / ``allOf`` /
/// ``additionalProperties``. Pathological schemas (think
@@ -153,6 +162,29 @@ fn bad_request(message: String, param: &str, code: &'static str) -> Response {
.into_response()
}
+/// Why a JSON Schema was refused: the 400's ``message``, the ``param``
+/// path it names, and its error ``code``.
+#[derive(Debug)]
+pub struct SchemaRejection {
+ pub message: String,
+ pub param: String,
+ pub code: &'static str,
+}
+
+impl SchemaRejection {
+ fn new(message: String, param: &str, code: &'static str) -> Self {
+ Self {
+ message,
+ param: param.to_string(),
+ code,
+ }
+ }
+
+ pub fn into_response(self) -> Response {
+ bad_request(self.message, &self.param, self.code)
+ }
+}
+
/// Parse the ``grammar`` object as it appears under
/// ``/v1/generate/{model}`` request bodies. Caller is responsible for
/// the capability gate (model config ``tasks.generate.capabilities.grammar``
@@ -230,7 +262,7 @@ pub fn parse_grammar(v: &Value) -> GrammarParseResult {
let schema = obj.get("json_schema").expect("checked above");
let resolved_schema = match dereference_schema_refs(schema, "grammar.json_schema") {
Ok(schema) => schema,
- Err(resp) => return GrammarParseResult::Err(resp),
+ Err(rejection) => return GrammarParseResult::Err(rejection.into_response()),
};
let serialized_len =
json_schema_grammar_len(&resolved_schema, label.as_deref(), strict).unwrap_or(0);
@@ -243,8 +275,8 @@ pub fn parse_grammar(v: &Value) -> GrammarParseResult {
oai_code::INVALID_REQUEST,
));
}
- if let Err(resp) = walk_schema(&resolved_schema, "grammar.json_schema", 0) {
- return GrammarParseResult::Err(resp);
+ if let Err(rejection) = walk_schema(&resolved_schema, "grammar.json_schema", None) {
+ return GrammarParseResult::Err(rejection.into_response());
}
GrammarParseResult::Ok(GrammarSpec::JsonSchema {
value: resolved_schema,
@@ -326,8 +358,71 @@ fn json_schema_grammar_len(
serde_json::to_vec(&Value::Object(obj)).map(|b| b.len())
}
-#[allow(clippy::result_large_err)]
-fn dereference_schema_refs(schema: &Value, path: &str) -> Result<Value, Response> {
+/// Check a tool's ``parameters`` (or ``input_schema``) before the request
+/// is forwarded. ``path`` is the field's request path, used in ``param``.
+///
+/// The worker renders tool schemas into the prompt and reads them to parse
+/// the model's calls; it never compiles them into a grammar (a forced
+/// ``tool_choice`` constrains only the tool name), and it follows ``$ref``
+/// lazily with its own bound. So the schema is checked as sent, without
+/// ``$ref`` expansion: its serialized size, depth and node count, the
+/// unsupported keywords, and that every ``$ref`` names a definition inside
+/// it. A schema that reuses definitions is measured as written, and a
+/// recursive definition is allowed.
+pub fn validate_tool_parameters(schema: &Value, path: &str) -> Result<(), SchemaRejection> {
+ let serialized_len = serde_json::to_vec(schema).map(|b| b.len()).unwrap_or(0);
+ if serialized_len > MAX_TOOL_SCHEMA_BYTES {
+ return Err(SchemaRejection::new(
+ format!(
+ "JSON Schema {serialized_len} bytes exceeds limit ({MAX_TOOL_SCHEMA_BYTES} bytes)"
+ ),
+ path,
+ oai_code::INVALID_REQUEST,
+ ));
+ }
+ walk_schema(schema, path, Some(schema))
+}
+
+/// Resolve an internal ``$ref`` against ``root``, returning the ref
+/// string (``#`` plus its JSON pointer) and its target. ``ref_param`` is
+/// the ``param`` path of the ``$ref`` key itself.
+fn resolve_internal_ref<'r, 'v>(
+ root: &'r Value,
+ ref_value: &'v Value,
+ ref_param: &str,
+) -> Result<(&'v str, &'r Value), SchemaRejection> {
+ let Some(ref_str) = ref_value.as_str() else {
+ return Err(SchemaRejection::new(
+ "'$ref' must be a string".to_string(),
+ ref_param,
+ oai_code::INVALID_REQUEST,
+ ));
+ };
+ let Some(pointer) = ref_str.strip_prefix('#') else {
+ return Err(SchemaRejection::new(
+ "external '$ref' is not supported".to_string(),
+ ref_param,
+ oai_code::UNSUPPORTED_FIELD,
+ ));
+ };
+ if !pointer.is_empty() && !pointer.starts_with('/') {
+ return Err(SchemaRejection::new(
+ "only internal JSON-pointer '$ref' values are supported".to_string(),
+ ref_param,
+ oai_code::UNSUPPORTED_FIELD,
+ ));
+ }
+ let Some(target) = root.pointer(pointer) else {
+ return Err(SchemaRejection::new(
+ format!("unresolved internal '$ref' {ref_str:?}"),
+ ref_param,
+ oai_code::INVALID_REQUEST,
+ ));
+ };
+ Ok((ref_str, target))
+}
+
+fn dereference_schema_refs(schema: &Value, path: &str) -> Result<Value, SchemaRejection> {
let mut visited: usize = 0;
let mut stack: Vec<String> = Vec::new();
dereference_schema_refs_inner(
@@ -349,7 +444,6 @@ enum SchemaContext {
Other,
}
-#[allow(clippy::result_large_err)]
fn dereference_schema_refs_inner(
root: &Value,
v: &Value,
@@ -358,17 +452,17 @@ fn dereference_schema_refs_inner(
stack: &mut Vec<String>,
context: SchemaContext,
traversal_depth: usize,
-) -> Result<Value, Response> {
+) -> Result<Value, SchemaRejection> {
*visited = visited.saturating_add(1);
if *visited > MAX_SCHEMA_NODES {
- return Err(bad_request(
+ return Err(SchemaRejection::new(
format!("JSON Schema node count exceeds limit ({MAX_SCHEMA_NODES})"),
path,
oai_code::INVALID_REQUEST,
));
}
if traversal_depth > MAX_SCHEMA_TRAVERSAL_DEPTH {
- return Err(bad_request(
+ return Err(SchemaRejection::new(
format!("JSON Schema traversal depth exceeds limit ({MAX_SCHEMA_TRAVERSAL_DEPTH})"),
path,
oai_code::INVALID_REQUEST,
@@ -378,45 +472,23 @@ fn dereference_schema_refs_inner(
match v {
Value::Object(map) => {
if context == SchemaContext::Schema && map.contains_key("$ref") {
- let ref_value = map.get("$ref").expect("checked above");
let ref_param = format!("{path}.$ref");
- let Some(ref_str) = ref_value.as_str() else {
- return Err(bad_request(
- "'$ref' must be a string".to_string(),
- &ref_param,
- oai_code::INVALID_REQUEST,
- ));
- };
- let Some(pointer) = ref_str.strip_prefix('#') else {
- return Err(bad_request(
- "external '$ref' is not supported".to_string(),
- &ref_param,
- oai_code::UNSUPPORTED_FIELD,
- ));
- };
- if !pointer.is_empty() && !pointer.starts_with('/') {
- return Err(bad_request(
- "only internal JSON-pointer '$ref' values are supported".to_string(),
- &ref_param,
- oai_code::UNSUPPORTED_FIELD,
- ));
- }
- if stack.iter().any(|p| p == pointer) {
- return Err(bad_request(
+ let (ref_str, target) = resolve_internal_ref(
+ root,
+ map.get("$ref").expect("checked above"),
+ &ref_param,
+ )?;
+ // A ref on the stack resolved when it was pushed, so
+ // checking the cycle after resolution reports the same error.
+ if stack.iter().any(|r| r == ref_str) {
+ return Err(SchemaRejection::new(
format!("recursive '$ref' cycle detected at {ref_str:?}"),
&ref_param,
oai_code::INVALID_REQUEST,
));
}
- let Some(target) = root.pointer(pointer) else {
- return Err(bad_request(
- format!("unresolved internal '$ref' {ref_str:?}"),
- &ref_param,
- oai_code::INVALID_REQUEST,
- ));
- };
- stack.push(pointer.to_string());
+ stack.push(ref_str.to_string());
let resolved = dereference_schema_refs_inner(
root,
target,
@@ -537,13 +609,22 @@ fn schema_child_context(parent: SchemaContext, key: &str) -> SchemaContext {
/// ``path`` is the dotted accessor for whatever produced 400s name in
/// ``param``. Array elements append ``[N]``; object members append
/// ``.<key>``.
-#[allow(clippy::result_large_err)]
-fn walk_schema(v: &Value, path: &str, depth: usize) -> Result<(), Response> {
+///
+/// With ``refs_root``, every ``$ref`` must resolve inside it (see
+/// :func:`resolve_internal_ref`); refs are checked, not followed.
+fn walk_schema(v: &Value, path: &str, refs_root: Option<&Value>) -> Result<(), SchemaRejection> {
let mut visited: usize = 0;
- walk_schema_inner(v, path, depth, &mut visited, SchemaContext::Schema, 0)
+ walk_schema_inner(
+ v,
+ path,
+ 0,
+ &mut visited,
+ SchemaContext::Schema,
+ 0,
+ refs_root,
+ )
}
-#[allow(clippy::result_large_err)]
fn walk_schema_inner(
v: &Value,
path: &str,
@@ -551,24 +632,25 @@ fn walk_schema_inner(
visited: &mut usize,
context: SchemaContext,
traversal_depth: usize,
-) -> Result<(), Response> {
+ refs_root: Option<&Value>,
+) -> Result<(), SchemaRejection> {
*visited = visited.saturating_add(1);
if *visited > MAX_SCHEMA_NODES {
- return Err(bad_request(
+ return Err(SchemaRejection::new(
format!("JSON Schema node count exceeds limit ({MAX_SCHEMA_NODES})"),
path,
oai_code::INVALID_REQUEST,
));
}
if traversal_depth > MAX_SCHEMA_TRAVERSAL_DEPTH {
- return Err(bad_request(
+ return Err(SchemaRejection::new(
format!("JSON Schema traversal depth exceeds limit ({MAX_SCHEMA_TRAVERSAL_DEPTH})"),
path,
oai_code::INVALID_REQUEST,
));
}
if depth > MAX_SCHEMA_DEPTH {
- return Err(bad_request(
+ return Err(SchemaRejection::new(
format!("JSON Schema depth exceeds limit ({MAX_SCHEMA_DEPTH})"),
path,
oai_code::INVALID_REQUEST,
@@ -586,9 +668,16 @@ fn walk_schema_inner(
if map.contains_key(kw) {
let param = format!("{path}.{kw}");
let message = format!("JSON Schema keyword '{kw}' is not supported");
- return Err(bad_request(message, &param, oai_code::UNSUPPORTED_FIELD));
+ return Err(SchemaRejection::new(
+ message,
+ &param,
+ oai_code::UNSUPPORTED_FIELD,
+ ));
}
}
+ if let (Some(root), Some(ref_value)) = (refs_root, map.get("$ref")) {
+ resolve_internal_ref(root, ref_value, &format!("{path}.$ref"))?;
+ }
}
for (k, child) in map {
let child_path = format!("{path}.{k}");
@@ -605,6 +694,7 @@ fn walk_schema_inner(
visited,
child_context,
traversal_depth + 1,
+ refs_root,
)?;
}
}
@@ -624,6 +714,7 @@ fn walk_schema_inner(
visited,
child_context,
traversal_depth + 1,
+ refs_root,
)?;
}
}
@@ -662,6 +753,7 @@ fn is_schema_nesting_key(key: &str) -> bool {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::handlers::test_support::schema_with_shared_definition;
use axum::body::to_bytes;
use serde_json::json;
@@ -830,9 +922,9 @@ mod tests {
#[tokio::test]
async fn test_dereference_schema_refs_rejects_raw_traversal_depth() {
let schema = deeply_nested_unknown_value(MAX_SCHEMA_TRAVERSAL_DEPTH + 1);
- let response = dereference_schema_refs(&schema, "grammar.json_schema")
+ let rejection = dereference_schema_refs(&schema, "grammar.json_schema")
.expect_err("raw traversal depth should reject during dereference");
- let body = err_body(response).await;
+ let body = err_body(rejection.into_response()).await;
assert_eq!(body["error"]["code"], "invalid_request");
assert!(body["error"]["message"]
@@ -843,9 +935,9 @@ mod tests {
#[tokio::test]
async fn test_walk_schema_rejects_raw_traversal_depth() {
let schema = deeply_nested_unknown_value(MAX_SCHEMA_TRAVERSAL_DEPTH + 1);
- let response = walk_schema(&schema, "grammar.json_schema", 0)
+ let rejection = walk_schema(&schema, "grammar.json_schema", None)
.expect_err("raw traversal depth should reject during validation");
- let body = err_body(response).await;
+ let body = err_body(rejection.into_response()).await;
assert_eq!(body["error"]["code"], "invalid_request");
assert!(body["error"]["message"]
@@ -1311,4 +1403,146 @@ mod tests {
});
let _ = ok_or_panic(parse_grammar(&v));
}
+
+ const TOOL_PATH: &str = "tools[0].function.parameters";
+
+ fn tool_rejection(schema: &Value) -> SchemaRejection {
+ validate_tool_parameters(schema, TOOL_PATH)
+ .expect_err("expected the tool schema to be refused")
+ }
+
+ #[tokio::test]
+ async fn test_tool_parameters_accept_refs_that_expand_past_the_node_cap() {
+ let schema = schema_with_shared_definition(150, 40, 1);
+ assert!(serde_json::to_vec(&schema).unwrap().len() < MAX_GRAMMAR_BYTES);
+
+ validate_tool_parameters(&schema, TOOL_PATH).expect("tool schema should be accepted");
+
+ let body = err_or_panic(parse_grammar(&json!({"json_schema": schema}))).await;
+ assert_eq!(
+ body["error"]["message"],
+ format!("JSON Schema node count exceeds limit ({MAX_SCHEMA_NODES})")
+ );
+ }
+
+ #[tokio::test]
+ async fn test_tool_parameters_accept_refs_that_expand_past_the_byte_cap() {
+ let schema = schema_with_shared_definition(40, 2, 2000);
+ assert!(serde_json::to_vec(&schema).unwrap().len() < MAX_GRAMMAR_BYTES);
+
+ validate_tool_parameters(&schema, TOOL_PATH).expect("tool schema should be accepted");
+
+ let body = err_or_panic(parse_grammar(&json!({"json_schema": schema}))).await;
+ let message = body["error"]["message"].as_str().unwrap_or("");
+ assert!(
+ message.starts_with("grammar payload ")
+ && message.ends_with(&format!("exceeds limit ({MAX_GRAMMAR_BYTES} bytes)")),
+ "message: {message}"
+ );
+ }
+
+ #[tokio::test]
+ async fn test_tool_parameters_accept_a_recursive_definition() {
+ let schema = json!({
+ "type": "object",
+ "$defs": {
+ "Node": {
+ "type": "object",
+ "properties": {"children": {"type": "array", "items": {"$ref": "#/$defs/Node"}}},
+ }
+ },
+ "properties": {"root": {"$ref": "#/$defs/Node"}},
+ });
+
+ validate_tool_parameters(&schema, TOOL_PATH).expect("tool schema should be accepted");
+
+ let body = err_or_panic(parse_grammar(&json!({"json_schema": schema}))).await;
+ assert!(body["error"]["message"]
+ .as_str()
+ .is_some_and(|message| message.starts_with("recursive '$ref' cycle detected")));
+ }
+
+ #[test]
+ fn test_tool_parameters_reject_an_unresolved_ref() {
+ let rejection = tool_rejection(&json!({
+ "type": "object",
+ "properties": {"a": {"$ref": "#/$defs/Missing"}},
+ }));
+ assert_eq!(
+ rejection.message,
+ "unresolved internal '$ref' \"#/$defs/Missing\""
+ );
+ assert_eq!(rejection.param, format!("{TOOL_PATH}.properties.a.$ref"));
+ assert_eq!(rejection.code, oai_code::INVALID_REQUEST);
+ }
+
+ #[test]
+ fn test_tool_parameters_reject_an_external_ref() {
+ let rejection = tool_rejection(&json!({
+ "type": "object",
+ "properties": {"a": {"$ref": "https://example.com/schema.json"}},
+ }));
+ assert_eq!(rejection.message, "external '$ref' is not supported");
+ assert_eq!(rejection.param, format!("{TOOL_PATH}.properties.a.$ref"));
+ assert_eq!(rejection.code, oai_code::UNSUPPORTED_FIELD);
+ }
+
+ #[test]
+ fn test_tool_parameters_reject_an_unsupported_keyword_inside_a_definition() {
+ let rejection = tool_rejection(&json!({
+ "type": "object",
+ "$defs": {"Shared": {"type": "object", "if": {"required": ["a"]}}},
+ "properties": {"a": {"$ref": "#/$defs/Shared"}},
+ }));
+ assert_eq!(
+ rejection.message,
+ "JSON Schema keyword 'if' is not supported"
+ );
+ assert_eq!(rejection.param, format!("{TOOL_PATH}.$defs.Shared.if"));
+ assert_eq!(rejection.code, oai_code::UNSUPPORTED_FIELD);
+ }
+
+ #[test]
+ fn test_tool_parameters_reject_an_oversized_schema() {
+ let schema = json!({"type": "object", "description": "d".repeat(MAX_GRAMMAR_BYTES)});
+ let size = serde_json::to_vec(&schema).unwrap().len();
+
+ let rejection = tool_rejection(&schema);
+ assert_eq!(
+ rejection.message,
+ format!("JSON Schema {size} bytes exceeds limit ({MAX_GRAMMAR_BYTES} bytes)")
+ );
+ assert_eq!(rejection.param, TOOL_PATH);
+ }
+
+ #[test]
+ fn test_tool_parameters_reject_a_deep_schema() {
+ let mut schema = json!({"type": "string"});
+ for _ in 0..=MAX_SCHEMA_DEPTH {
+ schema = json!({"type": "object", "properties": {"x": schema}});
+ }
+
+ let rejection = tool_rejection(&schema);
+ assert_eq!(
+ rejection.message,
+ format!("JSON Schema depth exceeds limit ({MAX_SCHEMA_DEPTH})")
+ );
+ assert!(
+ rejection.param.starts_with(TOOL_PATH),
+ "param: {}",
+ rejection.param
+ );
+ }
+
+ #[test]
+ fn test_tool_parameters_reject_too_many_nodes() {
+ let schema = json!({"type": "integer", "enum": vec![0; MAX_SCHEMA_NODES]});
+ assert!(serde_json::to_vec(&schema).unwrap().len() < MAX_GRAMMAR_BYTES);
+
+ let rejection = tool_rejection(&schema);
+ assert_eq!(
+ rejection.message,
+ format!("JSON Schema node count exceeds limit ({MAX_SCHEMA_NODES})")
+ );
+ }
}
diff --git a/packages/sie_gateway/src/handlers/messages/request.rs b/packages/sie_gateway/src/handlers/messages/request.rs
index 1aa39a8a2..eddad96cf 100644
--- a/packages/sie_gateway/src/handlers/messages/request.rs
+++ b/packages/sie_gateway/src/handlers/messages/request.rs
@@ -10,7 +10,7 @@
use serde_json::{json, Map, Value};
use super::error::MessagesError;
-use crate::handlers::grammar::{parse_grammar, GrammarParseResult};
+use crate::handlers::grammar::validate_tool_parameters;
pub(crate) const SUPPORTED_ANTHROPIC_VERSION: &str = "2023-06-01";
pub(crate) const MAX_TOOLS: usize = 64;
@@ -571,9 +571,11 @@ fn tools(body: &Map<String, Value>) -> Result<(Option<Vec<Value>>, Vec<String>),
)))
}
};
- if let GrammarParseResult::Err(_) = parse_grammar(&json!({"json_schema": schema})) {
+ let schema_path = format!("{path}.input_schema");
+ if let Err(rejection) = validate_tool_parameters(schema, &schema_path) {
return Err(invalid(format!(
- "{path}.input_schema: the schema uses an unsupported JSON Schema keyword (if, then, else, $dynamicRef, unevaluatedProperties, dependentSchemas) or exceeds the size or depth limits"
+ "{}: {}",
+ rejection.param, rejection.message
)));
}
function.insert("parameters".into(), schema.clone());
diff --git a/packages/sie_gateway/src/handlers/messages/tests.rs b/packages/sie_gateway/src/handlers/messages/tests.rs
index 470c0e25a..026497fa9 100644
--- a/packages/sie_gateway/src/handlers/messages/tests.rs
+++ b/packages/sie_gateway/src/handlers/messages/tests.rs
@@ -205,6 +205,20 @@ fn tool_count_over_the_limit_is_refused() {
);
}
+#[test]
+fn a_tool_schema_is_not_expanded_against_the_grammar_caps() {
+ let schema = crate::handlers::test_support::schema_with_shared_definition(150, 40, 1);
+ let translation = messages_to_chat(
+ &json!({"model": "m", "max_tokens": 1, "tools": [{"name": "t", "input_schema": schema}], "messages": [{"role": "user", "content": "x"}]}),
+ None,
+ )
+ .unwrap();
+ assert_eq!(
+ translation.chat["tools"][0]["function"]["parameters"],
+ schema
+ );
+}
+
#[test]
fn response_vectors_translate_the_chat_completion() {
let vectors = vectors("response_vectors.json");
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 39162c86a..7565f3b61 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -6573,7 +6573,7 @@ struct ChatRequestParams {
/// request omitted the field. Each entry is
/// ``{type: "function", function: {name, description?, parameters?}}``
/// with the ``function.parameters`` (when present) already
- /// run through the JSON-Schema safety walker.
+ /// checked by :func:`grammar::validate_tool_parameters`.
tools: Option<Vec<serde_json::Value>>,
/// OpenAI ``tool_choice``: one of the literal strings ``"auto"`` /
/// ``"none"`` / ``"required"`` or
@@ -6822,8 +6822,9 @@ fn decode_video_data_uri(value: &serde_json::Value) -> Result<(String, String),
/// ``json_object`` (loose JSON) translates to a built-in generic
/// schema (``{"type": "object", ...}``).
/// * ``tools`` / ``tool_choice`` / ``parallel_tool_calls`` — validated and
-/// forwarded; ``function.parameters`` is run through the JSON-Schema
-/// safety walker (see the `ChatRequestParams` field docs above).
+/// forwarded; ``function.parameters`` is checked by
+/// :func:`grammar::validate_tool_parameters` (see the `ChatRequestParams`
+/// field docs above).
/// * ``logprobs`` / ``top_logprobs`` — validated and forwarded; the worker
/// emits per-token log-probabilities via SGLang ``return_logprob`` and
/// the gateway plumbs them onto each chunk / the aggregate body.
@@ -8113,10 +8114,11 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {
/// description?: string, parameters?: object}}``.
/// * ``function.name`` must match the OpenAI pattern
/// ``^[a-zA-Z0-9_-]{1,64}$``.
-/// * ``function.parameters`` (when present) is run through the shared
-/// JSON-Schema safety walker so the same depth / size / unsupported-
-/// keyword caps that apply to ``response_format.json_schema`` also
-/// apply here.
+/// * ``function.parameters`` (when present) is checked as sent by
+/// :func:`grammar::validate_tool_parameters`: the same size, depth,
+/// node and unsupported-keyword caps as ``response_format.json_schema``,
+/// but without ``$ref`` expansion, since tool schemas are never
+/// compiled into a grammar.
///
/// Returns the original `Vec<Value>` (one entry per tool) on success
/// so the caller can plumb it verbatim through the wire envelope —
@@ -8219,22 +8221,13 @@ fn validate_chat_tools(v: &serde_json::Value) -> Result<Vec<serde_json::Value>,
}
if let Some(params) = func.get("parameters") {
if !params.is_null() {
- // Re-use the same JSON-Schema safety walker that
- // ``response_format.json_schema`` runs. We wrap the
- // schema in the ``{json_schema: <schema>}`` envelope
- // ``parse_grammar`` expects.
- let wrapped = serde_json::json!({"json_schema": params});
- match super::grammar::parse_grammar(&wrapped) {
- super::grammar::GrammarParseResult::Ok(_) => {}
- super::grammar::GrammarParseResult::Err(_) => {
- return Err(bad(
- format!(
- "tools[{i}].function.parameters failed JSON-Schema safety caps"
- ),
- &format!("tools[{i}].function.parameters"),
- oai_code::INVALID_REQUEST,
- ));
- }
+ let path = format!("tools[{i}].function.parameters");
+ if let Err(rejection) = super::grammar::validate_tool_parameters(params, &path) {
+ return Err(bad(
+ format!("{path}: {}", rejection.message),
+ &rejection.param,
+ rejection.code,
+ ));
}
}
}
@@ -27304,8 +27297,8 @@ mod tests {
}
/// ``tools[].function.parameters`` runs through the JSON-Schema
- /// safety walker — a schema with ``$ref`` is rejected with a 400
- /// keyed on the offending tool index.
+ /// safety walker — an unresolved ``$ref`` is rejected with a 400
+ /// that names the reason and the offending path.
#[tokio::test]
async fn test_chat_params_from_json_rejects_invalid_tool_schema() {
let mut body = _chat_body_min("m");
@@ -27321,10 +27314,31 @@ mod tests {
}]);
let v = _expect_chat_err(body).await;
assert_eq!(v["error"]["code"], "invalid_request");
- let param = v["error"]["param"].as_str().unwrap_or("");
- assert!(
- param.starts_with("tools[0].function.parameters"),
- "expected param path under tools[0].function.parameters, got {param}"
+ assert_eq!(
+ v["error"]["message"],
+ "tools[0].function.parameters: unresolved internal '$ref' \"#/$defs/Foo\""
+ );
+ assert_eq!(
+ v["error"]["param"],
+ "tools[0].function.parameters.properties.x.$ref"
+ );
+ }
+
+ /// Tool parameters are not compiled into a grammar, so a schema whose
+ /// ``$ref`` expansion would exceed the grammar caps is accepted as long
+ /// as the schema as sent is within them.
+ #[test]
+ fn test_chat_params_from_json_accepts_tool_schema_with_large_ref_expansion() {
+ let parameters = crate::handlers::test_support::schema_with_shared_definition(150, 40, 1);
+ let mut body = _chat_body_min("m");
+ body["tools"] = serde_json::json!([{
+ "type": "function",
+ "function": {"name": "f", "parameters": parameters},
+ }]);
+ let p = _expect_chat_ok(body);
+ assert_eq!(
+ p.tools.as_ref().unwrap()[0]["function"]["parameters"],
+ parameters
);
}
@@ -27753,7 +27767,7 @@ mod tests {
assert_eq!(v["error"]["param"], "response_format.type");
}
- /// The shared safety walker applies to the chat translator too, after
+ /// The grammar safety walker applies to the chat translator too, after
/// internal ``$ref`` entries inside ``json_schema.schema`` are inlined.
#[test]
fn test_chat_params_from_json_response_format_dereferences_dollar_ref() {
diff --git a/packages/sie_gateway/src/handlers/test_support.rs b/packages/sie_gateway/src/handlers/test_support.rs
index 022e1a33a..235e9b663 100644
--- a/packages/sie_gateway/src/handlers/test_support.rs
+++ b/packages/sie_gateway/src/handlers/test_support.rs
@@ -1252,6 +1252,39 @@ impl ThresholdBroker {
}
}
+/// An object schema whose ``properties`` each ``$ref`` one shared
+/// definition of ``fields`` string fields, each with a
+/// ``description_len``-byte description. Expanding the refs copies the
+/// definition once per property.
+pub(crate) fn schema_with_shared_definition(
+ properties: usize,
+ fields: usize,
+ description_len: usize,
+) -> serde_json::Value {
+ let description = "d".repeat(description_len);
+ let shared_fields: serde_json::Map<String, serde_json::Value> = (0..fields)
+ .map(|i| {
+ (
+ format!("f{i}"),
+ serde_json::json!({"type": "string", "description": description}),
+ )
+ })
+ .collect();
+ let refs: serde_json::Map<String, serde_json::Value> = (0..properties)
+ .map(|i| {
+ (
+ format!("p{i}"),
+ serde_json::json!({"$ref": "#/$defs/Shared"}),
+ )
+ })
+ .collect();
+ serde_json::json!({
+ "type": "object",
+ "$defs": {"Shared": {"type": "object", "properties": shared_fields}},
+ "properties": refs,
+ })
+}
+
#[cfg(test)]
mod threshold_broker_tests {
use super::ThresholdBroker;
diff --git a/packages/sie_server/src/sie_server/api/anthropic_translation.py b/packages/sie_server/src/sie_server/api/anthropic_translation.py
index f68069612..0ee69a52a 100644
--- a/packages/sie_server/src/sie_server/api/anthropic_translation.py
+++ b/packages/sie_server/src/sie_server/api/anthropic_translation.py
@@ -25,9 +25,7 @@ from dataclasses import dataclass
from http import HTTPStatus
from typing import Any
-from fastapi import HTTPException
-
-from sie_server.api.generate import _parse_native_grammar
+from sie_server.api.generate import _tool_parameters_rejection
SUPPORTED_ANTHROPIC_VERSION = "2023-06-01"
MAX_TOOLS = 64
@@ -589,13 +587,9 @@ def _tools(body: dict[str, Any]) -> tuple[list[dict[str, Any]] | None, list[str]
raise _required(f"{path}.input_schema")
if not isinstance(schema, dict):
raise _invalid(f"{path}.input_schema: Input should be a valid dictionary")
- try:
- _parse_native_grammar({"json_schema": schema})
- except HTTPException:
- raise _invalid(
- f"{path}.input_schema: the schema uses an unsupported JSON Schema keyword (if, then, else, "
- "$dynamicRef, unevaluatedProperties, dependentSchemas) or exceeds the size or depth limits"
- ) from None
+ reason = _tool_parameters_rejection(schema, f"{path}.input_schema")
+ if reason is not None:
+ raise _invalid(reason)
function["parameters"] = schema
tools.append({"type": "function", "function": function})
names.append(name)
diff --git a/packages/sie_server/src/sie_server/api/generate.py b/packages/sie_server/src/sie_server/api/generate.py
index 9cabe2e4b..1d7540b4e 100644
--- a/packages/sie_server/src/sie_server/api/generate.py
+++ b/packages/sie_server/src/sie_server/api/generate.py
@@ -169,20 +169,21 @@ _MAX_GENERATE_IMAGE_BYTES = 16 * 1024 * 1024
_MAX_GENERATE_IMAGE_BASE64_CHARS = 4 * ((_MAX_GENERATE_IMAGE_BYTES + 2) // 3)
_MAX_GENERATE_IMAGE_FORMAT_LENGTH = 32
_MAX_GRAMMAR_BYTES = 64 * 1024
+# A tool schema's budget, measured as sent rather than with ``$ref`` expanded.
+_MAX_TOOL_SCHEMA_BYTES = _MAX_GRAMMAR_BYTES
_MAX_SCHEMA_DEPTH = 16
_MAX_SCHEMA_TRAVERSAL_DEPTH = 128
_MAX_SCHEMA_NODES = 16 * 1024
_MAX_REGEX_LENGTH = 4 * 1024
_MAX_EBNF_LENGTH = 8 * 1024
-_UNSUPPORTED_SCHEMA_KEYWORDS = frozenset(
- {
- "$dynamicRef",
- "if",
- "then",
- "else",
- "unevaluatedProperties",
- "dependentSchemas",
- }
+# In the gateway's ``UNSUPPORTED_KEYWORDS`` order: the first one present is the one reported.
+_UNSUPPORTED_SCHEMA_KEYWORDS = (
+ "$dynamicRef",
+ "if",
+ "then",
+ "else",
+ "unevaluatedProperties",
+ "dependentSchemas",
)
_NATIVE_TOKENIZER_CACHE_SIZE = 16
_NATIVE_TOKENIZER_LOAD_LOCK = threading.Lock()
@@ -392,7 +393,13 @@ def _json_pointer(root: Any, pointer: str) -> Any:
token = raw_token.replace("~1", "/").replace("~0", "~")
if isinstance(current, dict) and token in current:
current = current[token]
- elif isinstance(current, list) and token.isascii() and token.isdecimal():
+ elif (
+ isinstance(current, list)
+ and token.isascii()
+ and token.isdecimal()
+ # RFC 6901: an array index is "0" or has no leading zero, as the gateway's lookup requires.
+ and (len(token) == 1 or not token.startswith("0"))
+ ):
try:
index = int(token)
except ValueError as exc:
@@ -405,6 +412,30 @@ def _json_pointer(root: Any, pointer: str) -> Any:
return current
+def _quoted(text: str) -> str:
+ """Quote a schema value in an error message as the gateway does."""
+ return json.dumps(text, ensure_ascii=False)
+
+
+def _resolve_internal_ref(root: Any, ref: Any, ref_path: str) -> tuple[str, Any]:
+ """Resolve an internal ``$ref`` against ``root``, returning its JSON pointer and target."""
+ if not isinstance(ref, str):
+ raise _bad_request("'$ref' must be a string", param=ref_path)
+ if not ref.startswith("#"):
+ raise _bad_request("external '$ref' is not supported", param=ref_path, code="unsupported_field")
+ pointer = ref[1:]
+ if pointer and not pointer.startswith("/"):
+ raise _bad_request(
+ "only internal JSON-pointer '$ref' values are supported",
+ param=ref_path,
+ code="unsupported_field",
+ )
+ try:
+ return pointer, _json_pointer(root, pointer)
+ except KeyError as exc:
+ raise _bad_request(f"unresolved internal '$ref' {_quoted(ref)}", param=ref_path) from exc
+
+
def _dereference_schema_refs(schema: dict[str, Any]) -> dict[str, Any]:
visited = 0
stack: list[str] = []
@@ -426,23 +457,11 @@ def _dereference_schema_refs(schema: dict[str, Any]) -> dict[str, Any]:
if context == "schema" and "$ref" in value:
ref = value["$ref"]
ref_path = f"{path}.$ref"
- if not isinstance(ref, str):
- raise _bad_request("'$ref' must be a string", param=ref_path)
- if not ref.startswith("#"):
- raise _bad_request("external '$ref' is not supported", param=ref_path, code="unsupported_field")
- pointer = ref[1:]
- if pointer and not pointer.startswith("/"):
- raise _bad_request(
- "only internal JSON-pointer '$ref' values are supported",
- param=ref_path,
- code="unsupported_field",
- )
+ pointer, target = _resolve_internal_ref(schema, ref, ref_path)
+ # A pointer on the stack resolved when it was pushed, so
+ # checking the cycle after resolution reports the same error.
if pointer in stack:
- raise _bad_request(f"recursive '$ref' cycle detected at {ref!r}", param=ref_path)
- try:
- target = _json_pointer(schema, pointer)
- except KeyError as exc:
- raise _bad_request(f"unresolved internal '$ref' {ref!r}", param=ref_path) from exc
+ raise _bad_request(f"recursive '$ref' cycle detected at {_quoted(ref)}", param=ref_path)
stack.append(pointer)
resolved = resolve(target, path, "schema", traversal_depth + 1)
stack.pop()
@@ -480,7 +499,11 @@ def _dereference_schema_refs(schema: dict[str, Any]) -> dict[str, Any]:
return cast("dict[str, Any]", resolved)
-def _validate_schema_shape(schema: Any) -> None:
+def _validate_schema_shape(schema: Any, *, path: str = "grammar.json_schema", refs_root: Any = None) -> None:
+ """Enforce the schema caps and keyword reject-list on ``schema`` as given; ``path`` prefixes each ``param``.
+
+ With ``refs_root``, every ``$ref`` must resolve inside it; refs are checked, not followed.
+ """
visited = 0
nesting_keys = {
"properties",
@@ -519,14 +542,16 @@ def _validate_schema_shape(schema: Any) -> None:
if depth > _MAX_SCHEMA_DEPTH:
raise _bad_request(f"JSON Schema depth exceeds limit ({_MAX_SCHEMA_DEPTH})", param=path)
if isinstance(value, dict):
- unsupported = _UNSUPPORTED_SCHEMA_KEYWORDS.intersection(value) if context == "schema" else set()
- if unsupported:
- keyword = sorted(unsupported)[0]
- raise _bad_request(
- f"JSON Schema keyword '{keyword}' is not supported",
- param=f"{path}.{keyword}",
- code="unsupported_field",
- )
+ if context == "schema":
+ keyword = next((kw for kw in _UNSUPPORTED_SCHEMA_KEYWORDS if kw in value), None)
+ if keyword is not None:
+ raise _bad_request(
+ f"JSON Schema keyword '{keyword}' is not supported",
+ param=f"{path}.{keyword}",
+ code="unsupported_field",
+ )
+ if refs_root is not None and "$ref" in value:
+ _resolve_internal_ref(refs_root, value["$ref"], f"{path}.$ref")
for key, child in value.items():
child_context = _schema_child_context(context, key)
child_depth = depth + 1 if context == "schema" and key in nesting_keys else depth
@@ -542,7 +567,36 @@ def _validate_schema_shape(schema: Any) -> None:
for index, child in enumerate(value):
walk(child, f"{path}[{index}]", depth, child_context, traversal_depth + 1)
- walk(schema, "grammar.json_schema", 0, "schema", 0)
+ walk(schema, path, 0, "schema", 0)
+
+
+def _validate_tool_parameters(schema: dict[str, Any], path: str) -> None:
+ """Check a tool's parameter schema as sent, without ``$ref`` expansion.
+
+ Mirrors ``validate_tool_parameters`` in the gateway's ``handlers/grammar.rs``.
+ Tool schemas are rendered into the prompt and read to parse calls, never
+ compiled into a grammar, so a schema that reuses definitions is measured as
+ written and a recursive definition is allowed.
+ """
+ # ``surrogatepass``: a decoded JSON string may hold a lone surrogate, which strict UTF-8 cannot encode.
+ encoded = json.dumps(schema, separators=(",", ":"), ensure_ascii=False).encode("utf-8", "surrogatepass")
+ encoded_size = len(encoded)
+ if encoded_size > _MAX_TOOL_SCHEMA_BYTES:
+ raise _bad_request(
+ f"JSON Schema {encoded_size} bytes exceeds limit ({_MAX_TOOL_SCHEMA_BYTES} bytes)",
+ param=path,
+ )
+ _validate_schema_shape(schema, path=path, refs_root=schema)
+
+
+def _tool_parameters_rejection(schema: dict[str, Any], path: str) -> str | None:
+ """Why :func:`_validate_tool_parameters` refuses ``schema`` as ``"<param>: <message>"``, or ``None``."""
+ try:
+ _validate_tool_parameters(schema, path)
+ except HTTPException as exc:
+ detail = cast("dict[str, Any]", exc.detail)
+ return f"{detail['param']}: {detail['message']}"
+ return None
def _parse_native_grammar(value: Any) -> GrammarSpec | None:
diff --git a/packages/sie_server/src/sie_server/processors/tool_call_parser.py b/packages/sie_server/src/sie_server/processors/tool_call_parser.py
index 7091393c2..81d104ec5 100644
--- a/packages/sie_server/src/sie_server/processors/tool_call_parser.py
+++ b/packages/sie_server/src/sie_server/processors/tool_call_parser.py
@@ -196,11 +196,28 @@ def _enum_type(values: list[object]) -> str:
return kinds.pop() if len(kinds) == 1 else "string"
-def _schema_type(schema: Any, root: Mapping[str, Any], depth: int = 0) -> str | None:
- """Infer one conversion type from a parameter schema, as SGLang's ``infer_type_from_json_schema`` does."""
+def _schema_type(
+ schema: Any, root: Mapping[str, Any], depth: int = 0, seen: dict[tuple[int, int], str | None] | None = None
+) -> str | None:
+ """Infer one conversion type from a parameter schema, as SGLang's ``infer_type_from_json_schema`` does.
+
+ ``seen`` holds each resolved schema's result at each depth for one inference. A ``$ref`` lets many
+ variants name one definition, so without it a chain of combinators over shared definitions is walked
+ once per path, exponentially in its depth; with it each schema is inferred at most once per depth.
+ """
+ seen = {} if seen is None else seen
schema = _resolve_ref(schema, root)
if not isinstance(schema, Mapping) or depth > _MAX_SCHEMA_DEPTH:
return None
+ key = (id(schema), depth)
+ if key not in seen:
+ seen[key] = _infer_schema_type(schema, root, depth, seen)
+ return seen[key]
+
+
+def _infer_schema_type(
+ schema: Mapping[str, Any], root: Mapping[str, Any], depth: int, seen: dict[tuple[int, int], str | None]
+) -> str | None:
declared = schema.get("type")
if isinstance(declared, str):
return declared.strip().lower()
@@ -209,7 +226,7 @@ def _schema_type(schema: Any, root: Mapping[str, Any], depth: int = 0) -> str |
return non_null[0].strip().lower() if non_null else "string"
variants = schema.get("anyOf") or schema.get("oneOf")
if isinstance(variants, list):
- kinds = [kind for kind in (_schema_type(variant, root, depth + 1) for variant in variants) if kind]
+ kinds = [kind for kind in (_schema_type(variant, root, depth + 1, seen) for variant in variants) if kind]
if kinds:
distinct = set(kinds)
if len(distinct) == 1:
@@ -223,7 +240,7 @@ def _schema_type(schema: Any, root: Mapping[str, Any], depth: int = 0) -> str |
all_of = schema.get("allOf")
if isinstance(all_of, list):
for variant in all_of:
- kind = _schema_type(variant, root, depth + 1)
+ kind = _schema_type(variant, root, depth + 1, seen)
if kind and kind != "string":
return kind
return "string"
@@ -234,10 +251,23 @@ def _schema_type(schema: Any, root: Mapping[str, Any], depth: int = 0) -> str |
return None
-def _schema_allows_null(schema: Any, root: Mapping[str, Any], depth: int = 0) -> bool:
+def _schema_allows_null(
+ schema: Any, root: Mapping[str, Any], depth: int = 0, seen: dict[tuple[int, int], bool] | None = None
+) -> bool:
+ """Whether a parameter schema admits ``null``; ``seen`` memoizes as in :func:`_schema_type`."""
+ seen = {} if seen is None else seen
schema = _resolve_ref(schema, root)
if not isinstance(schema, Mapping) or depth > _MAX_SCHEMA_DEPTH:
return False
+ key = (id(schema), depth)
+ if key not in seen:
+ seen[key] = _schema_admits_null(schema, root, depth, seen)
+ return seen[key]
+
+
+def _schema_admits_null(
+ schema: Mapping[str, Any], root: Mapping[str, Any], depth: int, seen: dict[tuple[int, int], bool]
+) -> bool:
declared = schema.get("type")
if schema.get("nullable") is True or declared == "null" or (isinstance(declared, list) and "null" in declared):
return True
@@ -245,7 +275,7 @@ def _schema_allows_null(schema: Any, root: Mapping[str, Any], depth: int = 0) ->
if isinstance(enum, list) and None in enum:
return True
return any(
- isinstance(variants, list) and any(_schema_allows_null(variant, root, depth + 1) for variant in variants)
+ isinstance(variants, list) and any(_schema_allows_null(variant, root, depth + 1, seen) for variant in variants)
for variants in (schema.get("anyOf"), schema.get("oneOf"))
)
diff --git a/packages/sie_server/tests/api/test_anthropic_translation.py b/packages/sie_server/tests/api/test_anthropic_translation.py
index 42df96df1..ccef1b0a7 100644
--- a/packages/sie_server/tests/api/test_anthropic_translation.py
+++ b/packages/sie_server/tests/api/test_anthropic_translation.py
@@ -9,6 +9,7 @@ chat validation, as the gateway checks it against its chat seam.
from __future__ import annotations
import asyncio
+import copy
import json
from collections.abc import AsyncIterator
from pathlib import Path
@@ -92,6 +93,33 @@ def test_a_rejected_request_vector_is_refused_with_its_wording(case: dict[str, A
assert refused.value.message == case["message"]
+def _shared_definition_schema() -> dict[str, Any]:
+ """150 properties that ``$ref`` one 40-field definition: small as sent, past the node cap once expanded."""
+ fields = {f"f{index}": {"type": "string", "description": "d"} for index in range(40)}
+ return {
+ "type": "object",
+ "$defs": {"Shared": {"type": "object", "properties": fields}},
+ "properties": {f"p{index}": {"$ref": "#/$defs/Shared"} for index in range(150)},
+ }
+
+
+def test_a_tool_schema_is_not_expanded_against_the_grammar_caps() -> None:
+ schema = _shared_definition_schema()
+ expected = copy.deepcopy(schema)
+ body = {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": "x"}]}
+
+ translation = messages_to_chat({**body, "tools": [{"name": "t", "input_schema": schema}]}, None)
+ assert translation.chat["tools"][0]["function"]["parameters"] == expected
+
+
+def test_a_tool_schema_with_a_lone_surrogate_is_measured_not_refused() -> None:
+ schema = json.loads('{"type": "object", "description": "\\ud800"}')
+ body = {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": "x"}]}
+
+ translation = messages_to_chat({**body, "tools": [{"name": "t", "input_schema": schema}]}, None)
+ assert translation.chat["tools"][0]["function"]["parameters"] == schema
+
+
@pytest.mark.parametrize("case", _vectors("claude_code_requests.json")["cases"], ids=lambda case: case["name"])
def test_a_captured_claude_code_request_translates_or_fails_with_the_recovery_wording(case: dict[str, Any]) -> None:
expect = case["expect"]
diff --git a/packages/sie_server/tests/api/test_generate.py b/packages/sie_server/tests/api/test_generate.py
index c8376a7e0..fa8167b25 100644
--- a/packages/sie_server/tests/api/test_generate.py
+++ b/packages/sie_server/tests/api/test_generate.py
@@ -1069,8 +1069,8 @@ class TestGenerateEndpoint:
@pytest.mark.parametrize(
"list_index",
- ["²", "9" * 5000],
- ids=["non-ascii", "overlong-ascii"],
+ ["²", "9" * 5000, "01"],
+ ids=["non-ascii", "overlong-ascii", "leading-zero"],
)
def test_native_grammar_rejects_invalid_json_pointer_list_index(self, list_index: str) -> None:
pointer = f"/{list_index}"
diff --git a/packages/sie_server/tests/processors/test_tool_call_parser.py b/packages/sie_server/tests/processors/test_tool_call_parser.py
index f312dc84f..6da1101a7 100644
--- a/packages/sie_server/tests/processors/test_tool_call_parser.py
+++ b/packages/sie_server/tests/processors/test_tool_call_parser.py
@@ -991,6 +991,33 @@ def test_self_referencing_schema_does_not_loop() -> None:
assert _parse_xml_tool_call("<function=f><parameter=v>\n1\n</parameter></function>", schemas) == ("f", {"v": "1"})
[email protected]("combinator", ["anyOf", "allOf"])
+def test_shared_definitions_under_combinators_are_inferred_once(combinator: str) -> None:
+ """Each definition names the next twice, so a walk without memoization visits 2**25 paths."""
+ definitions = {f"D{i}": {combinator: [{"$ref": f"#/$defs/D{i + 1}"}] * 2} for i in range(25)}
+ definitions["D25"] = {"type": "integer"}
+ schemas = {"f": {"$defs": definitions, "properties": {"v": {"$ref": "#/$defs/D0"}}}}
+
+ call = "<function=f><parameter=v>\n7\n</parameter></function>"
+ assert tool_call_parser._parse_xml_tool_call(call, schemas) == ("f", {"v": 7})
+
+
[email protected]("combinator", ["anyOf", "allOf"])
+def test_a_definition_first_reached_at_the_depth_limit_is_inferred_again_nearer_the_root(combinator: str) -> None:
+ """The long chain reaches ``Shared`` at the depth limit, where its variants are cut off; the short path does not."""
+ depth = tool_call_parser._MAX_SCHEMA_DEPTH
+ definitions: dict[str, object] = {f"C{i}": {combinator: [{"$ref": f"#/$defs/C{i + 1}"}]} for i in range(depth - 2)}
+ definitions[f"C{depth - 2}"] = {combinator: [{"$ref": "#/$defs/Shared"}]}
+ definitions["Shared"] = {"anyOf": [{"$ref": "#/$defs/Leaf"}]}
+ root = {"$defs": definitions}
+ parameter = {combinator: [{"$ref": "#/$defs/C0"}, {"$ref": "#/$defs/Shared"}]}
+
+ definitions["Leaf"] = {"type": "integer"}
+ assert tool_call_parser._schema_type(parameter, root) == "integer"
+ definitions["Leaf"] = {"type": "null"}
+ assert tool_call_parser._schema_allows_null({"anyOf": parameter[combinator]}, root)
+
+
@pytest.mark.asyncio
async def test_non_streaming_candidates_keep_a_malformed_block_as_text() -> None:
import json