diff --git a/crates/symphony/src/grammar/schema.rs b/crates/symphony/src/grammar/schema.rs index b8819aa94d..03dff15d0a 100644 --- a/crates/symphony/src/grammar/schema.rs +++ b/crates/symphony/src/grammar/schema.rs @@ -5,6 +5,8 @@ //! over a tool's properties the syntaxes share: one argument per property, in the schema's order, //! optional unless the schema requires it. +use std::collections::HashSet; + use serde_json::{json, Value}; use super::Grammar; @@ -53,11 +55,12 @@ pub(super) fn arguments( /// points at nothing (a grammar with such a pointer would not compile, and the whole call with /// it). A `$ref` lends its target's keywords, and the property's own win, as in JSON Schema /// 2020-12. -pub(super) fn shape( - schema: &Value, - definitions: Definitions<'_>, +pub(super) fn shape<'a>( + schema: &'a Value, + definitions: Definitions<'a>, text: impl FnOnce() -> Grammar, ) -> Option<(&'static str, Grammar)> { + let definitions = definitions.within(schema); if !definitions.pointers_resolve(schema) { return None; } @@ -92,34 +95,76 @@ pub(super) fn shape( } } -/// The definitions at the root of a tool's schema, `$defs` and `definitions`. Each property's -/// schema goes to the engine as a document of its own, and a `$ref` such as `#/$defs/Node` points -/// from the root of the document it stands in, so the definitions travel with the property's -/// schema. A pointer to the root itself, `#`, names the tool's schema in the tool and the property -/// in the property's document, so it resolves to nothing here, and the property takes any value. +/// The definitions a property's schema can point into: its own `$defs` and `definitions` first, +/// then the tool's root ones, which is the document the engine gets ([`Self::attached_to`]). Each +/// property's schema goes to the engine as a document of its own, and a `$ref` such as +/// `#/$defs/Node` points from the root of the document it stands in, so the definitions travel +/// with the property's schema. A pointer to the root itself, `#`, names the tool's schema in the +/// tool and the property in the property's document, so it resolves to nothing here, and the +/// property takes any value. #[derive(Clone, Copy)] pub(super) struct Definitions<'a> { + own: Blocks<'a>, + root: Blocks<'a>, +} + +/// A schema's two definition blocks. +#[derive(Clone, Copy)] +struct Blocks<'a> { defs: Option<&'a Value>, definitions: Option<&'a Value>, } +impl<'a> Blocks<'a> { + fn of(schema: &'a Value) -> Self { + Self { + defs: schema.get("$defs"), + definitions: schema.get("definitions"), + } + } + + fn named(self, block: &str) -> Option<&'a Value> { + match block { + "$defs" => self.defs, + "definitions" => self.definitions, + _ => None, + } + } +} + impl<'a> Definitions<'a> { pub(super) fn of(root: &'a Value) -> Self { Self { - defs: root.get("$defs"), - definitions: root.get("definitions"), + own: Blocks::of(root), + root: Blocks::of(root), + } + } + + /// The definitions as the property `schema` sees them: its own blocks first, then the root's. + fn within(self, schema: &'a Value) -> Self { + Self { + own: Blocks::of(schema), + root: self.root, } } - /// The schema a local pointer names: `#/$defs/Name` or `#/definitions/Name` an entry, with the - /// pointer's escapes (`~1` for `/`, `~0` for `~`) undone; `#` itself nothing, since it would - /// name the property's own document once the engine compiles it alone. + /// The schema a local pointer names: `#/$defs/Name` or `#/definitions/Name` an entry, the + /// property's own block before the root's, with the pointer's escapes (`~1` for `/`, `~0` for + /// `~`) undone; `#` itself nothing, since it would name the property's own document once the + /// engine compiles it alone. fn resolve(self, pointer: &str) -> Option<&'a Value> { let mut segments = pointer.strip_prefix("#/")?.split('/'); - let mut node = match segments.next()? { - "$defs" => self.defs?, - "definitions" => self.definitions?, - _ => return None, + let block = segments.next()?; + let name = segments.next()?.replace("~1", "/").replace("~0", "~"); + // A block the property has but that is no object (`"$defs": null`) stays as it is in the + // document the engine gets, with no entry to find, so nothing resolves through it. + let mut node = match self.own.named(block) { + Some(Value::Object(entries)) => match entries.get(&name) { + Some(entry) => entry, + None => self.root.named(block)?.get(&name)?, + }, + Some(_) => return None, + None => self.root.named(block)?.get(&name)?, }; for segment in segments { node = node.get(segment.replace("~1", "/").replace("~0", "~"))?; @@ -135,33 +180,37 @@ impl<'a> Definitions<'a> { /// Whether every local pointer in `schema` names something, and every pointer in what it /// names, as far as the pointers reach: the definitions travel with the property, so a pointer - /// at nothing inside one of them reaches the engine too. A definition that names itself is - /// followed once. - fn pointers_resolve(self, schema: &Value) -> bool { - self.pointers_resolve_from(schema, &mut Vec::new()) - } - - fn pointers_resolve_from(self, schema: &Value, followed: &mut Vec) -> bool { - match schema { - Value::Object(map) => map.iter().all(|(key, value)| { - let local = value - .as_str() - .filter(|pointer| is_reference(key) && pointer.starts_with('#')); - let named_resolves = local.is_none_or(|pointer| match self.resolve(pointer) { - None => false, - Some(_) if followed.iter().any(|seen| seen == pointer) => true, - Some(target) => { - followed.push(pointer.to_string()); - self.pointers_resolve_from(target, followed) + /// at nothing inside one of them reaches the engine too. Each distinct pointer is followed + /// once (`followed` remembers them, so a definition that names itself, or a wide schema, costs + /// one look per definition), and the schemas still to look at wait in a list of the walk's + /// own, not on the call stack: a chain of definitions costs its length and no stack, however + /// long a request makes it and however deep each definition nests before its pointer. + fn pointers_resolve(self, schema: &'a Value) -> bool { + let mut followed = HashSet::new(); + let mut pending = vec![schema]; + while let Some(schema) = pending.pop() { + match schema { + Value::Object(map) => { + for (key, value) in map { + let local = value + .as_str() + .filter(|pointer| is_reference(key) && pointer.starts_with('#')); + if let Some(pointer) = local { + let Some(target) = self.resolve(pointer) else { + return false; + }; + if followed.insert(pointer) { + pending.push(target); + } + } + pending.push(value); } - }); - named_resolves && self.pointers_resolve_from(value, followed) - }), - Value::Array(items) => items - .iter() - .all(|item| self.pointers_resolve_from(item, followed)), - _ => true, + } + Value::Array(items) => pending.extend(items), + _ => {} + } } + true } /// The property's schema with the root's definitions attached, so a local pointer in it still @@ -169,13 +218,14 @@ impl<'a> Definitions<'a> { /// stays; the root's fill in the names it lacks. A schema with no local pointer goes as it is. fn attached_to(self, schema: &Value) -> Value { let mut attached = schema.clone(); - if self.defs.is_none() && self.definitions.is_none() || !has_local_reference(schema) { + let root = self.root; + if root.defs.is_none() && root.definitions.is_none() || !has_local_reference(schema) { return attached; } let Some(object) = attached.as_object_mut() else { return attached; }; - for (name, block) in [("$defs", self.defs), ("definitions", self.definitions)] { + for (name, block) in [("$defs", root.defs), ("definitions", root.definitions)] { let Some(Value::Object(entries)) = block else { continue; }; diff --git a/crates/symphony/src/grammar/xtml.rs b/crates/symphony/src/grammar/xtml.rs index 095db9a915..4cd3ea0bd9 100644 --- a/crates/symphony/src/grammar/xtml.rs +++ b/crates/symphony/src/grammar/xtml.rs @@ -381,6 +381,170 @@ mod tests { } } + #[test] + fn a_propertys_own_definition_stands_before_the_roots() { + // The engine gets the property's schema with its own definitions kept and the root's + // filling in the rest, so the check reads the same: the property's `Inner` is whole and + // the root's `Inner`, which points at nothing, is not the one `Outer` reaches. + let call = first_call(&[tool( + "t", + value!({ + "type": "object", + "$defs": { + "Outer": {"type": "object", "properties": {"in": {"$ref": "#/$defs/Inner"}}}, + "Inner": {"$ref": "#/$defs/Gone"}, + }, + "properties": { + "own": { + "$ref": "#/$defs/Outer", + "$defs": {"Inner": {"type": "integer"}}, + }, + "root": {"$ref": "#/$defs/Outer"}, + }, + "required": ["own", "root"], + }), + )]); + let slots = call["elements"][3]["elements"] + .as_array() + .expect("two slots"); + assert_eq!( + slots[0]["elements"][0]["value"], + argument_open("own", "object") + ); + assert_eq!( + slots[0]["elements"][1]["json_schema"]["$defs"]["Inner"], + value!({"type": "integer"}), + "the property's own definition goes to the engine" + ); + assert_eq!( + slots[1]["elements"][0]["value"], "<|open|>argument key=\"root\" type=\"", + "through the root's Inner the pointer reaches nothing" + ); + } + + #[test] + fn a_chain_of_definitions_is_followed_to_its_end_however_long_and_deep() { + // Every link is a different pointer, so the memo of pointers followed does not shorten a + // chain, and the walk keeps the schemas still to look at in a list of its own: a request's + // chain costs its length and no stack, however many links it has and however deep each + // link nests before its pointer. The property carries a type of its own: a whole chain + // pins it, and a chain whose last link points at nothing does not, so the pin shows the + // walk reached the end rather than stopping partway. + let chain = |links: usize, nesting: usize, whole: bool| { + let mut defs = serde_json::Map::new(); + for i in 0..links { + let mut link = value!({"$ref": format!("#/$defs/D{}", i + 1)}); + for _ in 0..nesting { + link = value!({"properties": {"a": link}}); + } + defs.insert(format!("D{i}"), link); + } + if whole { + defs.insert(format!("D{links}"), value!({"type": "integer"})); + } + tool( + "t", + value!({ + "type": "object", + "$defs": defs, + "properties": {"p": {"type": "object", "$ref": "#/$defs/D0"}}, + "required": ["p"], + }), + ) + }; + let opener = |links: usize, nesting: usize, whole: bool| { + first_call(&[chain(links, nesting, whole)])["elements"][3]["elements"][0]["elements"][0] + ["value"] + .clone() + }; + let typeless = "<|open|>argument key=\"p\" type=\""; + assert_eq!(opener(10, 0, true), argument_open("p", "object")); + assert_eq!( + opener(5_000, 0, true), + argument_open("p", "object"), + "five thousand links" + ); + // Sixty-four links, each wrapped a hundred and twenty times in `properties` before its + // pointer, two objects a wrap: a walk with a frame per object would need some fifteen + // thousand of them. + assert_eq!( + opener(64, 120, true), + argument_open("p", "object"), + "sixty-four links nested deep" + ); + // The same chains with their last definition missing: only a walk that reaches the end + // finds the pointer at nothing. + assert_eq!( + opener(5_000, 0, false), + typeless, + "five thousand links to nothing" + ); + assert_eq!( + opener(64, 120, false), + typeless, + "sixty-four deep links to nothing" + ); + } + + #[test] + fn a_wide_schema_keeps_its_pins_however_many_definitions_it_names() { + // A property whose fields each name a different leaf definition is looked at once per + // definition and keeps its type, with every definition attached. + let mut defs = serde_json::Map::new(); + let mut fields = serde_json::Map::new(); + for i in 0..70 { + defs.insert(format!("L{i}"), value!({"type": "integer"})); + fields.insert(format!("f{i}"), value!({"$ref": format!("#/$defs/L{i}")})); + } + let call = first_call(&[tool( + "t", + value!({ + "type": "object", + "$defs": defs, + "properties": {"wide": {"type": "object", "properties": fields}}, + "required": ["wide"], + }), + )]); + let slot = &call["elements"][3]["elements"][0]; + assert_eq!( + slot["elements"][0]["value"], + argument_open("wide", "object") + ); + assert_eq!( + slot["elements"][1]["json_schema"]["$defs"]["L69"], + value!({"type": "integer"}) + ); + } + + #[test] + fn a_propertys_own_definitions_block_that_is_no_object_resolves_nothing() { + // `"$defs": null` (an SDK writing an empty map as null) stays as it is in the document the + // engine gets, with no entry at the pointer, so the property pins nothing rather than a + // schema the engine cannot compile. + let call = first_call(&[tool( + "t", + value!({ + "type": "object", + "$defs": {"Count": {"type": "integer"}}, + "properties": { + "null_block": {"$ref": "#/$defs/Count", "$defs": null}, + "list_block": {"$ref": "#/$defs/Count", "$defs": []}, + }, + "required": ["null_block", "list_block"], + }), + )]); + let slots = call["elements"][3]["elements"] + .as_array() + .expect("two slots"); + for (slot, key) in [(&slots[0], "null_block"), (&slots[1], "list_block")] { + assert_eq!( + slot["elements"][0]["value"], + format!("<|open|>argument key=\"{key}\" type=\""), + "{key} pins nothing" + ); + } + } + #[test] fn attribute_values_are_escaped_as_the_template_writes_them() { let parameters = value!({