Coverage for little_loops / fsm / validation.py: 72%
149 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-04-02 13:03 -0500
« prev ^ index » next coverage.py v7.12.0, created at 2026-04-02 13:03 -0500
1"""FSM loop validation logic.
3This module provides validation for FSM loop definitions, ensuring
4structural correctness and catching common configuration errors.
6Validation checks:
7- Initial state exists in states dict
8- All referenced states exist
9- At least one terminal state
10- Evaluator configs have required fields for their type
11- No conflicting routing (shorthand vs full route)
12- Numeric fields in valid ranges (max_iterations > 0, backoff >= 0, timeout > 0)
13"""
15from __future__ import annotations
17import logging
18from collections import deque
19from dataclasses import dataclass
20from enum import Enum
21from pathlib import Path
22from typing import Any
24import yaml
26from little_loops.fsm.schema import EvaluateConfig, FSMLoop, StateConfig
28logger = logging.getLogger(__name__)
31class ValidationSeverity(Enum):
32 """Severity level for validation issues."""
34 ERROR = "error"
35 WARNING = "warning"
38@dataclass
39class ValidationError:
40 """Structured validation error.
42 Attributes:
43 message: Human-readable error description
44 path: Path to the problematic element (e.g., "states.check.route")
45 severity: Error severity (error or warning)
46 """
48 message: str
49 path: str | None = None
50 severity: ValidationSeverity = ValidationSeverity.ERROR
52 def __str__(self) -> str:
53 """Format error for display."""
54 prefix = f"[{self.severity.value.upper()}]"
55 if self.path:
56 return f"{prefix} {self.path}: {self.message}"
57 return f"{prefix} {self.message}"
60# Evaluator type to required fields mapping
61EVALUATOR_REQUIRED_FIELDS: dict[str, list[str]] = {
62 "exit_code": [],
63 "output_numeric": ["operator", "target"],
64 "output_json": ["path", "operator", "target"],
65 "output_contains": ["pattern"],
66 "convergence": ["target"],
67 "diff_stall": [],
68 "llm_structured": [],
69 "mcp_result": [],
70}
72# Valid comparison operators
73VALID_OPERATORS = {"eq", "ne", "lt", "le", "gt", "ge"}
75# All top-level keys recognized by FSMLoop.from_dict()
76KNOWN_TOP_LEVEL_KEYS: frozenset[str] = frozenset(
77 {
78 "name",
79 "description",
80 "initial",
81 "states",
82 "context",
83 "scope",
84 "max_iterations",
85 "backoff",
86 "timeout",
87 "default_timeout",
88 "maintain",
89 "llm",
90 "on_handoff",
91 "input_key",
92 "config",
93 }
94)
97def _validate_evaluator(state_name: str, evaluate: EvaluateConfig) -> list[ValidationError]:
98 """Validate evaluator configuration for type-specific requirements.
100 Args:
101 state_name: Name of the state containing this evaluator
102 evaluate: The evaluator configuration to validate
104 Returns:
105 List of validation errors found
106 """
107 errors: list[ValidationError] = []
108 path = f"states.{state_name}.evaluate"
110 # Check required fields for evaluator type
111 required = EVALUATOR_REQUIRED_FIELDS.get(evaluate.type, [])
112 for field_name in required:
113 value = getattr(evaluate, field_name, None)
114 if value is None:
115 errors.append(
116 ValidationError(
117 message=f"Evaluator type '{evaluate.type}' requires '{field_name}' field",
118 path=path,
119 )
120 )
122 # Validate operator if present
123 if evaluate.operator is not None and evaluate.operator not in VALID_OPERATORS:
124 errors.append(
125 ValidationError(
126 message=f"Invalid operator '{evaluate.operator}'. "
127 f"Must be one of: {', '.join(sorted(VALID_OPERATORS))}",
128 path=f"{path}.operator",
129 )
130 )
132 # Validate convergence-specific fields
133 if evaluate.type == "convergence":
134 if evaluate.direction not in ("minimize", "maximize"):
135 errors.append(
136 ValidationError(
137 message=f"Invalid direction '{evaluate.direction}'. "
138 "Must be 'minimize' or 'maximize'",
139 path=f"{path}.direction",
140 )
141 )
142 # Only validate tolerance if it's a numeric value (not an interpolation string)
143 if (
144 evaluate.tolerance is not None
145 and isinstance(evaluate.tolerance, (int, float))
146 and evaluate.tolerance < 0
147 ):
148 errors.append(
149 ValidationError(
150 message="Tolerance cannot be negative",
151 path=f"{path}.tolerance",
152 )
153 )
155 # Validate llm_structured-specific fields
156 if evaluate.type == "llm_structured":
157 if evaluate.min_confidence < 0 or evaluate.min_confidence > 1:
158 errors.append(
159 ValidationError(
160 message="min_confidence must be between 0 and 1",
161 path=f"{path}.min_confidence",
162 )
163 )
165 # Validate diff_stall-specific fields
166 if evaluate.type == "diff_stall":
167 if evaluate.max_stall < 1:
168 errors.append(
169 ValidationError(
170 message="max_stall must be >= 1",
171 path=f"{path}.max_stall",
172 )
173 )
175 return errors
178def _validate_state_action(state_name: str, state: StateConfig) -> list[ValidationError]:
179 """Validate state action configuration.
181 Args:
182 state_name: Name of the state to validate
183 state: The state configuration to validate
185 Returns:
186 List of validation errors found
187 """
188 errors: list[ValidationError] = []
189 path = f"states.{state_name}"
191 # params field is only valid for mcp_tool states
192 if state.params and state.action_type != "mcp_tool":
193 errors.append(
194 ValidationError(
195 message="'params' field is only valid when action_type is 'mcp_tool'",
196 path=f"{path}.params",
197 )
198 )
200 # loop and action are mutually exclusive
201 if state.loop is not None and state.action is not None:
202 errors.append(
203 ValidationError(
204 message="'loop' and 'action' are mutually exclusive — "
205 "a sub-loop state cannot also have an action",
206 path=f"{path}",
207 )
208 )
210 return errors
213def _validate_state_routing(state_name: str, state: StateConfig) -> list[ValidationError]:
214 """Validate state routing configuration.
216 Checks for conflicting routing definitions (shorthand vs full route).
218 Args:
219 state_name: Name of the state to validate
220 state: The state configuration to validate
222 Returns:
223 List of validation errors/warnings found
224 """
225 errors: list[ValidationError] = []
226 path = f"states.{state_name}"
228 has_shorthand = (
229 state.on_yes is not None
230 or state.on_no is not None
231 or state.on_error is not None
232 or state.on_partial is not None
233 )
234 has_route = state.route is not None
236 # Warn about conflicting definitions
237 if has_shorthand and has_route:
238 errors.append(
239 ValidationError(
240 message="Both shorthand routing (on_yes/on_no/on_error) "
241 "and full route table defined. Route table will take precedence.",
242 path=path,
243 severity=ValidationSeverity.WARNING,
244 )
245 )
247 # Check for no valid transition definition
248 has_next = state.next is not None
249 has_terminal = state.terminal
250 has_loop = state.loop is not None
252 if not has_shorthand and not has_route and not has_next and not has_terminal and not has_loop:
253 errors.append(
254 ValidationError(
255 message="State has no transition defined. Add routing, 'next', "
256 "or mark as 'terminal: true'",
257 path=path,
258 )
259 )
261 # Validate retry field pairing: max_retries requires on_retry_exhausted and vice versa
262 if state.max_retries is not None and state.on_retry_exhausted is None:
263 errors.append(
264 ValidationError(
265 message="'max_retries' requires 'on_retry_exhausted' to also be set",
266 path=path,
267 )
268 )
269 if state.on_retry_exhausted is not None and state.max_retries is None:
270 errors.append(
271 ValidationError(
272 message="'on_retry_exhausted' requires 'max_retries' to also be set",
273 path=path,
274 )
275 )
276 if state.max_retries is not None and state.max_retries < 1:
277 errors.append(
278 ValidationError(
279 message=f"'max_retries' must be >= 1, got {state.max_retries}",
280 path=path,
281 )
282 )
284 return errors
287def validate_fsm(fsm: FSMLoop) -> list[ValidationError]:
288 """Validate FSM structure and return list of errors.
290 Performs comprehensive validation:
291 - Initial state exists
292 - All referenced states exist
293 - At least one terminal state
294 - Evaluator configurations are valid
295 - Routing configurations are valid
296 - Numeric fields are in valid ranges (max_iterations > 0, backoff >= 0, timeout > 0)
298 Args:
299 fsm: The FSM loop to validate
301 Returns:
302 List of validation errors (empty if valid)
303 """
304 errors: list[ValidationError] = []
305 defined_states = fsm.get_all_state_names()
307 # Check initial state exists
308 if fsm.initial not in defined_states:
309 errors.append(
310 ValidationError(
311 message=f"Initial state '{fsm.initial}' not found in states",
312 path="initial",
313 )
314 )
316 # Check at least one terminal state
317 terminal_states = fsm.get_terminal_states()
318 if not terminal_states:
319 errors.append(
320 ValidationError(
321 message="No terminal state defined. At least one state must have 'terminal: true'",
322 path="states",
323 )
324 )
326 # Validate each state
327 for state_name, state in fsm.states.items():
328 # Check all referenced states exist
329 refs = state.get_referenced_states()
330 for ref in refs:
331 # $current is a special token for retry
332 if ref != "$current" and ref not in defined_states:
333 errors.append(
334 ValidationError(
335 message=f"References unknown state '{ref}'",
336 path=f"states.{state_name}",
337 )
338 )
340 # Validate action configuration
341 errors.extend(_validate_state_action(state_name, state))
343 # Validate evaluator if present
344 if state.evaluate is not None:
345 errors.extend(_validate_evaluator(state_name, state.evaluate))
347 # Validate routing configuration
348 errors.extend(_validate_state_routing(state_name, state))
350 # Check numeric field ranges
351 if fsm.max_iterations <= 0:
352 errors.append(
353 ValidationError(
354 message=f"max_iterations must be > 0, got {fsm.max_iterations}",
355 path="max_iterations",
356 )
357 )
358 if fsm.backoff is not None and fsm.backoff < 0:
359 errors.append(
360 ValidationError(
361 message=f"backoff must be >= 0, got {fsm.backoff}",
362 path="backoff",
363 )
364 )
365 if fsm.timeout is not None and fsm.timeout <= 0:
366 errors.append(
367 ValidationError(
368 message=f"timeout must be > 0, got {fsm.timeout}",
369 path="timeout",
370 )
371 )
372 if fsm.llm.max_tokens <= 0:
373 errors.append(
374 ValidationError(
375 message=f"llm.max_tokens must be > 0, got {fsm.llm.max_tokens}",
376 path="llm.max_tokens",
377 )
378 )
379 if fsm.llm.timeout <= 0:
380 errors.append(
381 ValidationError(
382 message=f"llm.timeout must be > 0, got {fsm.llm.timeout}",
383 path="llm.timeout",
384 )
385 )
387 # Check for unreachable states (warning only)
388 reachable = _find_reachable_states(fsm)
389 unreachable = defined_states - reachable
390 for state_name in unreachable:
391 errors.append(
392 ValidationError(
393 message="State is not reachable from initial state",
394 path=f"states.{state_name}",
395 severity=ValidationSeverity.WARNING,
396 )
397 )
399 return errors
402def _find_reachable_states(fsm: FSMLoop) -> set[str]:
403 """Find all states reachable from the initial state.
405 Uses breadth-first search to find all reachable states.
407 Args:
408 fsm: The FSM loop to analyze
410 Returns:
411 Set of reachable state names
412 """
413 reachable: set[str] = set()
414 to_visit: deque[str] = deque([fsm.initial])
416 while to_visit:
417 current = to_visit.popleft()
418 if current in reachable or current not in fsm.states:
419 continue
421 reachable.add(current)
422 state = fsm.states[current]
423 refs = state.get_referenced_states()
425 for ref in refs:
426 if ref != "$current" and ref not in reachable:
427 to_visit.append(ref)
429 return reachable
432def load_and_validate(path: Path) -> tuple[FSMLoop, list[ValidationError]]:
433 """Load YAML file and validate FSM structure.
435 Args:
436 path: Path to the YAML file to load
438 Returns:
439 Tuple of (validated FSMLoop instance, list of WARNING-severity ValidationErrors)
441 Raises:
442 FileNotFoundError: If the file doesn't exist
443 yaml.YAMLError: If the file is not valid YAML
444 ValueError: If validation fails (contains error details)
445 """
446 if not path.exists():
447 raise FileNotFoundError(f"FSM file not found: {path}")
449 with open(path) as f:
450 data: dict[str, Any] = yaml.safe_load(f)
452 if not isinstance(data, dict):
453 raise ValueError(f"FSM file must contain a YAML mapping, got {type(data)}")
455 # Check required fields before parsing
456 missing = []
457 for field in ["name", "initial", "states"]:
458 if field not in data:
459 missing.append(field)
461 if missing:
462 raise ValueError(f"FSM file missing required fields: {', '.join(missing)}")
464 # Check for unknown top-level keys before parsing
465 unknown_key_warnings: list[ValidationError] = []
466 unknown = set(data.keys()) - KNOWN_TOP_LEVEL_KEYS
467 if unknown:
468 unknown_key_warnings.append(
469 ValidationError(
470 path="<root>",
471 message=f"Unknown top-level keys: {', '.join(sorted(unknown))}",
472 severity=ValidationSeverity.WARNING,
473 )
474 )
476 # Parse into dataclass
477 fsm = FSMLoop.from_dict(data)
479 # Validate
480 errors = validate_fsm(fsm)
482 # Filter to errors only (not warnings) for raising
483 error_list = [e for e in errors if e.severity == ValidationSeverity.ERROR]
485 if error_list:
486 error_messages = "\n ".join(str(e) for e in error_list)
487 raise ValueError(f"FSM validation failed:\n {error_messages}")
489 # Collect all warnings (unknown-key warnings + structural warnings)
490 struct_warnings = [e for e in errors if e.severity == ValidationSeverity.WARNING]
491 all_warnings = unknown_key_warnings + struct_warnings
492 for warning in all_warnings:
493 logger.warning(str(warning))
495 return fsm, all_warnings