Skip to main content

graphrt_llm/nodes/
schema.rs

1//! Lightweight structural check of model output against a JSON Schema.
2//!
3//! Supports the subset that matters for structured output: `type` (single or
4//! list), `required`, `properties`, `items`, `enum` and `const`, applied
5//! recursively. Keywords outside that subset are ignored rather than rejected,
6//! so the check never fails valid output; it catches the common failure modes
7//! (wrong top-level type, missing required fields, wrong field types).
8
9use serde_json::Value as Json;
10
11/// Maximum nesting depth checked.
12const MAX_DEPTH: usize = 32;
13
14/// Validate `value` against `schema`. Returns the first problem found, with a
15/// JSON-pointer-like path.
16pub fn validate(value: &Json, schema: &Json) -> Result<(), String> {
17    check(value, schema, "$", 0)
18}
19
20/// Whether `value` matches the schema's top-level `type` (true when no type is given).
21pub fn matches_top_level_type(value: &Json, schema: &Json) -> bool {
22    match schema.get("type") {
23        None => true,
24        Some(t) => type_matches(value, t),
25    }
26}
27
28fn check(value: &Json, schema: &Json, path: &str, depth: usize) -> Result<(), String> {
29    if depth > MAX_DEPTH || !schema.is_object() {
30        return Ok(());
31    }
32    if let Some(t) = schema.get("type") {
33        if !type_matches(value, t) {
34            return Err(format!("{path}: expected {}, got {}", type_label(t), kind(value)));
35        }
36    }
37    if let Some(Json::Array(options)) = schema.get("enum") {
38        if !options.contains(value) {
39            return Err(format!("{path}: value {value} is not one of the allowed values"));
40        }
41    }
42    if let Some(expected) = schema.get("const") {
43        if expected != value {
44            return Err(format!("{path}: expected constant {expected}"));
45        }
46    }
47    match value {
48        Json::Object(map) => {
49            if let Some(Json::Array(required)) = schema.get("required") {
50                for name in required.iter().filter_map(Json::as_str) {
51                    if !map.contains_key(name) {
52                        return Err(format!("{path}: missing required property `{name}`"));
53                    }
54                }
55            }
56            if let Some(Json::Object(properties)) = schema.get("properties") {
57                for (name, sub) in properties {
58                    if let Some(v) = map.get(name) {
59                        check(v, sub, &format!("{path}.{name}"), depth + 1)?;
60                    }
61                }
62            }
63        }
64        Json::Array(items) => {
65            if let Some(item_schema) = schema.get("items").filter(|s| s.is_object()) {
66                for (i, item) in items.iter().enumerate() {
67                    check(item, item_schema, &format!("{path}[{i}]"), depth + 1)?;
68                }
69            }
70        }
71        _ => {}
72    }
73    Ok(())
74}
75
76fn type_matches(value: &Json, ty: &Json) -> bool {
77    match ty {
78        Json::String(name) => single_type_matches(value, name),
79        Json::Array(names) => names.iter().filter_map(Json::as_str).any(|n| single_type_matches(value, n)),
80        _ => true,
81    }
82}
83
84fn single_type_matches(value: &Json, name: &str) -> bool {
85    match name {
86        "object" => value.is_object(),
87        "array" => value.is_array(),
88        "string" => value.is_string(),
89        "boolean" => value.is_boolean(),
90        "null" => value.is_null(),
91        "number" => value.is_number(),
92        "integer" => {
93            value.as_i64().is_some() || value.as_u64().is_some() || value.as_f64().is_some_and(|f| f.fract() == 0.0)
94        }
95        _ => true, // unknown type names are not enforced
96    }
97}
98
99fn type_label(ty: &Json) -> String {
100    match ty {
101        Json::String(s) => s.clone(),
102        Json::Array(items) => items.iter().filter_map(Json::as_str).collect::<Vec<_>>().join(" or "),
103        other => other.to_string(),
104    }
105}
106
107fn kind(value: &Json) -> &'static str {
108    match value {
109        Json::Null => "null",
110        Json::Bool(_) => "boolean",
111        Json::Number(_) => "number",
112        Json::String(_) => "string",
113        Json::Array(_) => "array",
114        Json::Object(_) => "object",
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121    use serde_json::json;
122
123    fn schema() -> Json {
124        json!({
125            "type": "object",
126            "required": ["name", "tags"],
127            "properties": {
128                "name": {"type": "string"},
129                "age": {"type": "integer"},
130                "tags": {"type": "array", "items": {"type": "string"}},
131                "kind": {"enum": ["a", "b"]},
132                "maybe": {"type": ["string", "null"]}
133            }
134        })
135    }
136
137    #[test]
138    fn accepts_valid_values() {
139        assert!(
140            validate(&json!({"name": "x", "tags": ["a"], "age": 3, "kind": "a", "maybe": null}), &schema()).is_ok()
141        );
142        assert!(validate(&json!({"name": "x", "tags": [], "extra": 1}), &schema()).is_ok());
143    }
144
145    #[test]
146    fn reports_mismatches() {
147        let err = validate(&json!([1]), &schema()).unwrap_err();
148        assert!(err.contains("expected object"), "{err}");
149        let err = validate(&json!({"name": "x"}), &schema()).unwrap_err();
150        assert!(err.contains("`tags`"), "{err}");
151        let err = validate(&json!({"name": "x", "tags": [1]}), &schema()).unwrap_err();
152        assert!(err.contains("$.tags[0]"), "{err}");
153        let err = validate(&json!({"name": "x", "tags": [], "age": 1.5}), &schema()).unwrap_err();
154        assert!(err.contains("$.age"), "{err}");
155        assert!(validate(&json!({"name": "x", "tags": [], "kind": "z"}), &schema()).is_err());
156    }
157
158    #[test]
159    fn top_level_type() {
160        assert!(matches_top_level_type(&json!({}), &schema()));
161        assert!(!matches_top_level_type(&json!([1]), &schema()));
162        assert!(matches_top_level_type(&json!([1]), &json!({})));
163    }
164}