Coverage for little_loops / fsm / validation.py: 100%

113 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-03-04 01:17 -0600

1"""FSM loop validation logic. 

2 

3This module provides validation for FSM loop definitions, ensuring 

4structural correctness and catching common configuration errors. 

5 

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""" 

13 

14from __future__ import annotations 

15 

16import logging 

17from dataclasses import dataclass 

18from enum import Enum 

19from pathlib import Path 

20from typing import Any 

21 

22import yaml 

23 

24from little_loops.fsm.schema import EvaluateConfig, FSMLoop, StateConfig 

25 

26logger = logging.getLogger(__name__) 

27 

28 

29class ValidationSeverity(Enum): 

30 """Severity level for validation issues.""" 

31 

32 ERROR = "error" 

33 WARNING = "warning" 

34 

35 

36@dataclass 

37class ValidationError: 

38 """Structured validation error. 

39 

40 Attributes: 

41 message: Human-readable error description 

42 path: Path to the problematic element (e.g., "states.check.route") 

43 severity: Error severity (error or warning) 

44 """ 

45 

46 message: str 

47 path: str | None = None 

48 severity: ValidationSeverity = ValidationSeverity.ERROR 

49 

50 def __str__(self) -> str: 

51 """Format error for display.""" 

52 prefix = f"[{self.severity.value.upper()}]" 

53 if self.path: 

54 return f"{prefix} {self.path}: {self.message}" 

55 return f"{prefix} {self.message}" 

56 

57 

58# Evaluator type to required fields mapping 

59EVALUATOR_REQUIRED_FIELDS: dict[str, list[str]] = { 

60 "exit_code": [], 

61 "output_numeric": ["operator", "target"], 

62 "output_json": ["path", "operator", "target"], 

63 "output_contains": ["pattern"], 

64 "convergence": ["target"], 

65 "llm_structured": [], 

66} 

67 

68# Valid comparison operators 

69VALID_OPERATORS = {"eq", "ne", "lt", "le", "gt", "ge"} 

70 

71 

72def _validate_evaluator(state_name: str, evaluate: EvaluateConfig) -> list[ValidationError]: 

73 """Validate evaluator configuration for type-specific requirements. 

74 

75 Args: 

76 state_name: Name of the state containing this evaluator 

77 evaluate: The evaluator configuration to validate 

78 

79 Returns: 

80 List of validation errors found 

81 """ 

82 errors: list[ValidationError] = [] 

83 path = f"states.{state_name}.evaluate" 

84 

85 # Check required fields for evaluator type 

86 required = EVALUATOR_REQUIRED_FIELDS.get(evaluate.type, []) 

87 for field_name in required: 

88 value = getattr(evaluate, field_name, None) 

89 if value is None: 

90 errors.append( 

91 ValidationError( 

92 message=f"Evaluator type '{evaluate.type}' requires '{field_name}' field", 

93 path=path, 

94 ) 

95 ) 

96 

97 # Validate operator if present 

98 if evaluate.operator is not None and evaluate.operator not in VALID_OPERATORS: 

99 errors.append( 

100 ValidationError( 

101 message=f"Invalid operator '{evaluate.operator}'. " 

102 f"Must be one of: {', '.join(sorted(VALID_OPERATORS))}", 

103 path=f"{path}.operator", 

104 ) 

105 ) 

106 

107 # Validate convergence-specific fields 

108 if evaluate.type == "convergence": 

109 if evaluate.direction not in ("minimize", "maximize"): 

110 errors.append( 

111 ValidationError( 

112 message=f"Invalid direction '{evaluate.direction}'. " 

113 "Must be 'minimize' or 'maximize'", 

114 path=f"{path}.direction", 

115 ) 

116 ) 

117 # Only validate tolerance if it's a numeric value (not an interpolation string) 

118 if ( 

119 evaluate.tolerance is not None 

120 and isinstance(evaluate.tolerance, (int, float)) 

121 and evaluate.tolerance < 0 

122 ): 

123 errors.append( 

124 ValidationError( 

125 message="Tolerance cannot be negative", 

126 path=f"{path}.tolerance", 

127 ) 

128 ) 

129 

130 # Validate llm_structured-specific fields 

131 if evaluate.type == "llm_structured": 

132 if evaluate.min_confidence < 0 or evaluate.min_confidence > 1: 

133 errors.append( 

134 ValidationError( 

135 message="min_confidence must be between 0 and 1", 

136 path=f"{path}.min_confidence", 

137 ) 

138 ) 

139 

140 return errors 

141 

142 

143def _validate_state_routing(state_name: str, state: StateConfig) -> list[ValidationError]: 

144 """Validate state routing configuration. 

145 

146 Checks for conflicting routing definitions (shorthand vs full route). 

147 

148 Args: 

149 state_name: Name of the state to validate 

150 state: The state configuration to validate 

151 

152 Returns: 

153 List of validation errors/warnings found 

154 """ 

155 errors: list[ValidationError] = [] 

156 path = f"states.{state_name}" 

157 

158 has_shorthand = ( 

159 state.on_success is not None or state.on_failure is not None or state.on_error is not None 

160 ) 

161 has_route = state.route is not None 

162 

163 # Warn about conflicting definitions 

164 if has_shorthand and has_route: 

165 errors.append( 

166 ValidationError( 

167 message="Both shorthand routing (on_success/on_failure/on_error) " 

168 "and full route table defined. Route table will take precedence.", 

169 path=path, 

170 severity=ValidationSeverity.WARNING, 

171 ) 

172 ) 

173 

174 # Check for no valid transition definition 

175 has_next = state.next is not None 

176 has_terminal = state.terminal 

177 

178 if not has_shorthand and not has_route and not has_next and not has_terminal: 

179 errors.append( 

180 ValidationError( 

181 message="State has no transition defined. Add routing, 'next', " 

182 "or mark as 'terminal: true'", 

183 path=path, 

184 ) 

185 ) 

186 

187 return errors 

188 

189 

190def validate_fsm(fsm: FSMLoop) -> list[ValidationError]: 

191 """Validate FSM structure and return list of errors. 

192 

193 Performs comprehensive validation: 

194 - Initial state exists 

195 - All referenced states exist 

196 - At least one terminal state 

197 - Evaluator configurations are valid 

198 - Routing configurations are valid 

199 

200 Args: 

201 fsm: The FSM loop to validate 

202 

203 Returns: 

204 List of validation errors (empty if valid) 

205 """ 

206 errors: list[ValidationError] = [] 

207 defined_states = fsm.get_all_state_names() 

208 

209 # Check initial state exists 

210 if fsm.initial not in defined_states: 

211 errors.append( 

212 ValidationError( 

213 message=f"Initial state '{fsm.initial}' not found in states", 

214 path="initial", 

215 ) 

216 ) 

217 

218 # Check at least one terminal state 

219 terminal_states = fsm.get_terminal_states() 

220 if not terminal_states: 

221 errors.append( 

222 ValidationError( 

223 message="No terminal state defined. At least one state must have 'terminal: true'", 

224 path="states", 

225 ) 

226 ) 

227 

228 # Validate each state 

229 for state_name, state in fsm.states.items(): 

230 # Check all referenced states exist 

231 refs = state.get_referenced_states() 

232 for ref in refs: 

233 # $current is a special token for retry 

234 if ref != "$current" and ref not in defined_states: 

235 errors.append( 

236 ValidationError( 

237 message=f"References unknown state '{ref}'", 

238 path=f"states.{state_name}", 

239 ) 

240 ) 

241 

242 # Validate evaluator if present 

243 if state.evaluate is not None: 

244 errors.extend(_validate_evaluator(state_name, state.evaluate)) 

245 

246 # Validate routing configuration 

247 errors.extend(_validate_state_routing(state_name, state)) 

248 

249 # Check for unreachable states (warning only) 

250 reachable = _find_reachable_states(fsm) 

251 unreachable = defined_states - reachable 

252 for state_name in unreachable: 

253 errors.append( 

254 ValidationError( 

255 message="State is not reachable from initial state", 

256 path=f"states.{state_name}", 

257 severity=ValidationSeverity.WARNING, 

258 ) 

259 ) 

260 

261 return errors 

262 

263 

264def _find_reachable_states(fsm: FSMLoop) -> set[str]: 

265 """Find all states reachable from the initial state. 

266 

267 Uses breadth-first search to find all reachable states. 

268 

269 Args: 

270 fsm: The FSM loop to analyze 

271 

272 Returns: 

273 Set of reachable state names 

274 """ 

275 reachable: set[str] = set() 

276 to_visit: list[str] = [fsm.initial] 

277 

278 while to_visit: 

279 current = to_visit.pop(0) 

280 if current in reachable or current not in fsm.states: 

281 continue 

282 

283 reachable.add(current) 

284 state = fsm.states[current] 

285 refs = state.get_referenced_states() 

286 

287 for ref in refs: 

288 if ref != "$current" and ref not in reachable: 

289 to_visit.append(ref) 

290 

291 return reachable 

292 

293 

294def load_and_validate(path: Path) -> FSMLoop: 

295 """Load YAML file and validate FSM structure. 

296 

297 Args: 

298 path: Path to the YAML file to load 

299 

300 Returns: 

301 Validated FSMLoop instance 

302 

303 Raises: 

304 FileNotFoundError: If the file doesn't exist 

305 yaml.YAMLError: If the file is not valid YAML 

306 ValueError: If validation fails (contains error details) 

307 """ 

308 if not path.exists(): 

309 raise FileNotFoundError(f"FSM file not found: {path}") 

310 

311 with open(path) as f: 

312 data: dict[str, Any] = yaml.safe_load(f) 

313 

314 if not isinstance(data, dict): 

315 raise ValueError(f"FSM file must contain a YAML mapping, got {type(data)}") 

316 

317 # Check required fields before parsing 

318 missing = [] 

319 for field in ["name", "initial", "states"]: 

320 if field not in data: 

321 missing.append(field) 

322 

323 if missing: 

324 raise ValueError(f"FSM file missing required fields: {', '.join(missing)}") 

325 

326 # Parse into dataclass 

327 fsm = FSMLoop.from_dict(data) 

328 

329 # Validate 

330 errors = validate_fsm(fsm) 

331 

332 # Filter to errors only (not warnings) for raising 

333 error_list = [e for e in errors if e.severity == ValidationSeverity.ERROR] 

334 

335 if error_list: 

336 error_messages = "\n ".join(str(e) for e in error_list) 

337 raise ValueError(f"FSM validation failed:\n {error_messages}") 

338 

339 # Log warnings 

340 warnings = [e for e in errors if e.severity == ValidationSeverity.WARNING] 

341 for warning in warnings: 

342 logger.warning(str(warning)) 

343 

344 return fsm