Skip to main content

adk_graph/functional/
schema.rs

1//! State schema validation for the functional API.
2//!
3//! Provides validation of workflow state against a declared schema at
4//! workflow start and before applying task output reducers. Wraps the
5//! existing [`StateSchema`] from `adk-graph` and adds type-level
6//! validation capabilities specific to the functional API.
7//!
8//! # Example
9//!
10//! ```rust,ignore
11//! use adk_graph::functional::StateSchemaValidator;
12//! use adk_graph::state::StateSchema;
13//! use serde_json::json;
14//! use std::collections::HashMap;
15//!
16//! let schema = StateSchema::builder()
17//!     .channel("counter")
18//!     .list_channel("messages")
19//!     .build();
20//!
21//! let validator = StateSchemaValidator::new(schema)
22//!     .expect_type("counter", ExpectedType::Number)
23//!     .expect_type("messages", ExpectedType::Array);
24//!
25//! let mut state = HashMap::new();
26//! state.insert("counter".to_string(), json!(42));
27//! state.insert("messages".to_string(), json!([]));
28//!
29//! // Passes validation
30//! validator.validate_state(&state).unwrap();
31//! ```
32
33use serde_json::Value;
34use std::collections::HashMap;
35
36use crate::state::{State, StateSchema};
37
38use super::error::FunctionalError;
39
40/// Expected JSON value type for a state field.
41///
42/// Used by [`StateSchemaValidator`] to check that state values conform
43/// to the declared type expectations.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum ExpectedType {
46    /// JSON null value.
47    Null,
48    /// JSON boolean value.
49    Boolean,
50    /// JSON numeric value (integer or float).
51    Number,
52    /// JSON string value.
53    String,
54    /// JSON array value.
55    Array,
56    /// JSON object value.
57    Object,
58}
59
60impl ExpectedType {
61    /// Check if a JSON value matches this expected type.
62    pub fn matches(&self, value: &Value) -> bool {
63        match self {
64            ExpectedType::Null => value.is_null(),
65            ExpectedType::Boolean => value.is_boolean(),
66            ExpectedType::Number => value.is_number(),
67            ExpectedType::String => value.is_string(),
68            ExpectedType::Array => value.is_array(),
69            ExpectedType::Object => value.is_object(),
70        }
71    }
72
73    /// Return a human-readable name for this type.
74    pub fn type_name(&self) -> &'static str {
75        match self {
76            ExpectedType::Null => "null",
77            ExpectedType::Boolean => "boolean",
78            ExpectedType::Number => "number",
79            ExpectedType::String => "string",
80            ExpectedType::Array => "array",
81            ExpectedType::Object => "object",
82        }
83    }
84}
85
86impl std::fmt::Display for ExpectedType {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        write!(f, "{}", self.type_name())
89    }
90}
91
92/// Get a human-readable type name for a JSON value.
93fn value_type_name(value: &Value) -> &'static str {
94    match value {
95        Value::Null => "null",
96        Value::Bool(_) => "boolean",
97        Value::Number(_) => "number",
98        Value::String(_) => "string",
99        Value::Array(_) => "array",
100        Value::Object(_) => "object",
101    }
102}
103
104/// Validates workflow state against a declared schema.
105///
106/// Wraps the existing [`StateSchema`] and adds field-level type validation
107/// capabilities for the functional API. Used at workflow start to validate
108/// initial state, and before applying reducers to validate task output.
109///
110/// # Example
111///
112/// ```rust,ignore
113/// use adk_graph::functional::StateSchemaValidator;
114/// use adk_graph::state::StateSchema;
115///
116/// let schema = StateSchema::builder()
117///     .channel("status")
118///     .counter_channel("count")
119///     .build();
120///
121/// let validator = StateSchemaValidator::new(schema)
122///     .expect_type("status", ExpectedType::String)
123///     .expect_type("count", ExpectedType::Number);
124/// ```
125#[derive(Clone)]
126pub struct StateSchemaValidator {
127    /// The underlying state schema with channels and reducers.
128    schema: StateSchema,
129    /// Expected types for each field.
130    type_expectations: HashMap<String, ExpectedType>,
131    /// Fields that are required (must be present in state).
132    required_fields: Vec<String>,
133}
134
135impl std::fmt::Debug for StateSchemaValidator {
136    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137        f.debug_struct("StateSchemaValidator")
138            .field("type_expectations", &self.type_expectations)
139            .field("required_fields", &self.required_fields)
140            .finish_non_exhaustive()
141    }
142}
143
144impl StateSchemaValidator {
145    /// Create a new validator wrapping an existing [`StateSchema`].
146    pub fn new(schema: StateSchema) -> Self {
147        Self { schema, type_expectations: HashMap::new(), required_fields: Vec::new() }
148    }
149
150    /// Declare the expected type for a state field.
151    ///
152    /// Fields with type expectations will be validated when present.
153    /// Use [`Self::require_field`] to also require the field's presence.
154    pub fn expect_type(mut self, field: &str, expected: ExpectedType) -> Self {
155        self.type_expectations.insert(field.to_string(), expected);
156        self
157    }
158
159    /// Mark a field as required (must be present in state).
160    ///
161    /// Required fields that are missing from state will cause validation
162    /// to fail with a descriptive error.
163    pub fn require_field(mut self, field: &str) -> Self {
164        if !self.required_fields.contains(&field.to_string()) {
165            self.required_fields.push(field.to_string());
166        }
167        self
168    }
169
170    /// Get the underlying [`StateSchema`].
171    pub fn schema(&self) -> &StateSchema {
172        &self.schema
173    }
174
175    /// Validate that all required fields exist with correct types in state.
176    ///
177    /// Called at workflow start to validate the initial state.
178    ///
179    /// # Errors
180    ///
181    /// Returns [`FunctionalError::SchemaValidation`] if:
182    /// - A required field is missing from state
183    /// - A field value does not match its declared expected type
184    pub fn validate_state(&self, state: &State) -> Result<(), FunctionalError> {
185        // Check required fields are present.
186        for field in &self.required_fields {
187            if !state.contains_key(field) {
188                return Err(FunctionalError::SchemaValidation {
189                    field: field.clone(),
190                    expected: "present".to_string(),
191                    actual: "missing".to_string(),
192                });
193            }
194        }
195
196        // Check type expectations for present fields.
197        for (field, expected_type) in &self.type_expectations {
198            if let Some(value) = state.get(field)
199                && !expected_type.matches(value)
200            {
201                return Err(FunctionalError::SchemaValidation {
202                    field: field.clone(),
203                    expected: expected_type.type_name().to_string(),
204                    actual: value_type_name(value).to_string(),
205                });
206            }
207        }
208
209        Ok(())
210    }
211
212    /// Validate task output before applying reducers.
213    ///
214    /// Checks that output fields match their declared types. This is
215    /// called after a task produces output but before the output is
216    /// merged into the workflow state via reducers.
217    ///
218    /// # Arguments
219    ///
220    /// * `output` - A map of field names to values produced by the task.
221    ///
222    /// # Errors
223    ///
224    /// Returns [`FunctionalError::SchemaValidation`] if any output field
225    /// has a value that does not match its declared expected type.
226    pub fn validate_task_output(&self, output: &State) -> Result<(), FunctionalError> {
227        for (field, value) in output {
228            if let Some(expected_type) = self.type_expectations.get(field)
229                && !expected_type.matches(value)
230            {
231                return Err(FunctionalError::SchemaValidation {
232                    field: field.clone(),
233                    expected: expected_type.type_name().to_string(),
234                    actual: value_type_name(value).to_string(),
235                });
236            }
237        }
238
239        Ok(())
240    }
241
242    /// Apply an update to state using the underlying schema's reducer.
243    ///
244    /// Delegates to [`StateSchema::apply_update`].
245    pub fn apply_update(&self, state: &mut State, key: &str, value: Value) {
246        self.schema.apply_update(state, key, value);
247    }
248}
249
250impl Default for StateSchemaValidator {
251    fn default() -> Self {
252        Self::new(StateSchema::default())
253    }
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259    use serde_json::json;
260
261    #[test]
262    fn test_validate_state_passes_with_correct_types() {
263        let schema = StateSchema::builder().channel("name").counter_channel("count").build();
264
265        let validator = StateSchemaValidator::new(schema)
266            .expect_type("name", ExpectedType::String)
267            .expect_type("count", ExpectedType::Number)
268            .require_field("name");
269
270        let mut state = State::new();
271        state.insert("name".to_string(), json!("workflow_1"));
272        state.insert("count".to_string(), json!(0));
273
274        assert!(validator.validate_state(&state).is_ok());
275    }
276
277    #[test]
278    fn test_validate_state_fails_on_missing_required_field() {
279        let validator =
280            StateSchemaValidator::new(StateSchema::default()).require_field("required_field");
281
282        let state = State::new();
283
284        let err = validator.validate_state(&state).unwrap_err();
285        match err {
286            FunctionalError::SchemaValidation { field, expected, actual } => {
287                assert_eq!(field, "required_field");
288                assert_eq!(expected, "present");
289                assert_eq!(actual, "missing");
290            }
291            _ => panic!("unexpected error variant"),
292        }
293    }
294
295    #[test]
296    fn test_validate_state_fails_on_type_mismatch() {
297        let validator = StateSchemaValidator::new(StateSchema::default())
298            .expect_type("count", ExpectedType::Number);
299
300        let mut state = State::new();
301        state.insert("count".to_string(), json!("not_a_number"));
302
303        let err = validator.validate_state(&state).unwrap_err();
304        match err {
305            FunctionalError::SchemaValidation { field, expected, actual } => {
306                assert_eq!(field, "count");
307                assert_eq!(expected, "number");
308                assert_eq!(actual, "string");
309            }
310            _ => panic!("unexpected error variant"),
311        }
312    }
313
314    #[test]
315    fn test_validate_task_output_passes_with_correct_types() {
316        let validator = StateSchemaValidator::new(StateSchema::default())
317            .expect_type("result", ExpectedType::Object)
318            .expect_type("score", ExpectedType::Number);
319
320        let mut output = State::new();
321        output.insert("result".to_string(), json!({"key": "value"}));
322        output.insert("score".to_string(), json!(95));
323
324        assert!(validator.validate_task_output(&output).is_ok());
325    }
326
327    #[test]
328    fn test_validate_task_output_fails_on_type_mismatch() {
329        let validator = StateSchemaValidator::new(StateSchema::default())
330            .expect_type("items", ExpectedType::Array);
331
332        let mut output = State::new();
333        output.insert("items".to_string(), json!("not_an_array"));
334
335        let err = validator.validate_task_output(&output).unwrap_err();
336        match err {
337            FunctionalError::SchemaValidation { field, expected, actual } => {
338                assert_eq!(field, "items");
339                assert_eq!(expected, "array");
340                assert_eq!(actual, "string");
341            }
342            _ => panic!("unexpected error variant"),
343        }
344    }
345
346    #[test]
347    fn test_validate_state_skips_absent_optional_fields() {
348        let validator = StateSchemaValidator::new(StateSchema::default())
349            .expect_type("optional_field", ExpectedType::String);
350
351        // Field not present — should pass since it's not required.
352        let state = State::new();
353        assert!(validator.validate_state(&state).is_ok());
354    }
355
356    #[test]
357    fn test_validate_task_output_ignores_unknown_fields() {
358        let validator = StateSchemaValidator::new(StateSchema::default())
359            .expect_type("known", ExpectedType::Number);
360
361        let mut output = State::new();
362        output.insert("known".to_string(), json!(42));
363        output.insert("unknown".to_string(), json!("anything"));
364
365        // "unknown" has no type expectation, so validation passes.
366        assert!(validator.validate_task_output(&output).is_ok());
367    }
368
369    #[test]
370    fn test_expected_type_matches() {
371        assert!(ExpectedType::Null.matches(&json!(null)));
372        assert!(ExpectedType::Boolean.matches(&json!(true)));
373        assert!(ExpectedType::Number.matches(&json!(42)));
374        assert!(ExpectedType::Number.matches(&json!(1.5)));
375        assert!(ExpectedType::String.matches(&json!("hello")));
376        assert!(ExpectedType::Array.matches(&json!([1, 2, 3])));
377        assert!(ExpectedType::Object.matches(&json!({"key": "value"})));
378
379        assert!(!ExpectedType::Number.matches(&json!("42")));
380        assert!(!ExpectedType::String.matches(&json!(42)));
381        assert!(!ExpectedType::Array.matches(&json!({})));
382    }
383}