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

146 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-03-14 23:20 -0500

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- Numeric fields in valid ranges (max_iterations > 0, backoff >= 0, timeout > 0) 

13""" 

14 

15from __future__ import annotations 

16 

17import logging 

18from collections import deque 

19from dataclasses import dataclass 

20from enum import Enum 

21from pathlib import Path 

22from typing import Any 

23 

24import yaml 

25 

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

27 

28logger = logging.getLogger(__name__) 

29 

30 

31class ValidationSeverity(Enum): 

32 """Severity level for validation issues.""" 

33 

34 ERROR = "error" 

35 WARNING = "warning" 

36 

37 

38@dataclass 

39class ValidationError: 

40 """Structured validation error. 

41 

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

47 

48 message: str 

49 path: str | None = None 

50 severity: ValidationSeverity = ValidationSeverity.ERROR 

51 

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

58 

59 

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} 

71 

72# Valid comparison operators 

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

74 

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

88 "llm", 

89 "on_handoff", 

90 "input_key", 

91 } 

92) 

93 

94 

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

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

97 

98 Args: 

99 state_name: Name of the state containing this evaluator 

100 evaluate: The evaluator configuration to validate 

101 

102 Returns: 

103 List of validation errors found 

104 """ 

105 errors: list[ValidationError] = [] 

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

107 

108 # Check required fields for evaluator type 

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

110 for field_name in required: 

111 value = getattr(evaluate, field_name, None) 

112 if value is None: 

113 errors.append( 

114 ValidationError( 

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

116 path=path, 

117 ) 

118 ) 

119 

120 # Validate operator if present 

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

122 errors.append( 

123 ValidationError( 

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

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

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

127 ) 

128 ) 

129 

130 # Validate convergence-specific fields 

131 if evaluate.type == "convergence": 

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

133 errors.append( 

134 ValidationError( 

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

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

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

138 ) 

139 ) 

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

141 if ( 

142 evaluate.tolerance is not None 

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

144 and evaluate.tolerance < 0 

145 ): 

146 errors.append( 

147 ValidationError( 

148 message="Tolerance cannot be negative", 

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

150 ) 

151 ) 

152 

153 # Validate llm_structured-specific fields 

154 if evaluate.type == "llm_structured": 

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

156 errors.append( 

157 ValidationError( 

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

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

160 ) 

161 ) 

162 

163 # Validate diff_stall-specific fields 

164 if evaluate.type == "diff_stall": 

165 if evaluate.max_stall < 1: 

166 errors.append( 

167 ValidationError( 

168 message="max_stall must be >= 1", 

169 path=f"{path}.max_stall", 

170 ) 

171 ) 

172 

173 return errors 

174 

175 

176def _validate_state_action(state_name: str, state: StateConfig) -> list[ValidationError]: 

177 """Validate state action configuration. 

178 

179 Args: 

180 state_name: Name of the state to validate 

181 state: The state configuration to validate 

182 

183 Returns: 

184 List of validation errors found 

185 """ 

186 errors: list[ValidationError] = [] 

187 path = f"states.{state_name}" 

188 

189 # params field is only valid for mcp_tool states 

190 if state.params and state.action_type != "mcp_tool": 

191 errors.append( 

192 ValidationError( 

193 message="'params' field is only valid when action_type is 'mcp_tool'", 

194 path=f"{path}.params", 

195 ) 

196 ) 

197 

198 return errors 

199 

200 

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

202 """Validate state routing configuration. 

203 

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

205 

206 Args: 

207 state_name: Name of the state to validate 

208 state: The state configuration to validate 

209 

210 Returns: 

211 List of validation errors/warnings found 

212 """ 

213 errors: list[ValidationError] = [] 

214 path = f"states.{state_name}" 

215 

216 has_shorthand = ( 

217 state.on_yes is not None 

218 or state.on_no is not None 

219 or state.on_error is not None 

220 or state.on_partial is not None 

221 ) 

222 has_route = state.route is not None 

223 

224 # Warn about conflicting definitions 

225 if has_shorthand and has_route: 

226 errors.append( 

227 ValidationError( 

228 message="Both shorthand routing (on_yes/on_no/on_error) " 

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

230 path=path, 

231 severity=ValidationSeverity.WARNING, 

232 ) 

233 ) 

234 

235 # Check for no valid transition definition 

236 has_next = state.next is not None 

237 has_terminal = state.terminal 

238 

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

240 errors.append( 

241 ValidationError( 

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

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

244 path=path, 

245 ) 

246 ) 

247 

248 # Validate retry field pairing: max_retries requires on_retry_exhausted and vice versa 

249 if state.max_retries is not None and state.on_retry_exhausted is None: 

250 errors.append( 

251 ValidationError( 

252 message="'max_retries' requires 'on_retry_exhausted' to also be set", 

253 path=path, 

254 ) 

255 ) 

256 if state.on_retry_exhausted is not None and state.max_retries is None: 

257 errors.append( 

258 ValidationError( 

259 message="'on_retry_exhausted' requires 'max_retries' to also be set", 

260 path=path, 

261 ) 

262 ) 

263 if state.max_retries is not None and state.max_retries < 1: 

264 errors.append( 

265 ValidationError( 

266 message=f"'max_retries' must be >= 1, got {state.max_retries}", 

267 path=path, 

268 ) 

269 ) 

270 

271 return errors 

272 

273 

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

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

276 

277 Performs comprehensive validation: 

278 - Initial state exists 

279 - All referenced states exist 

280 - At least one terminal state 

281 - Evaluator configurations are valid 

282 - Routing configurations are valid 

283 - Numeric fields are in valid ranges (max_iterations > 0, backoff >= 0, timeout > 0) 

284 

285 Args: 

286 fsm: The FSM loop to validate 

287 

288 Returns: 

289 List of validation errors (empty if valid) 

290 """ 

291 errors: list[ValidationError] = [] 

292 defined_states = fsm.get_all_state_names() 

293 

294 # Check initial state exists 

295 if fsm.initial not in defined_states: 

296 errors.append( 

297 ValidationError( 

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

299 path="initial", 

300 ) 

301 ) 

302 

303 # Check at least one terminal state 

304 terminal_states = fsm.get_terminal_states() 

305 if not terminal_states: 

306 errors.append( 

307 ValidationError( 

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

309 path="states", 

310 ) 

311 ) 

312 

313 # Validate each state 

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

315 # Check all referenced states exist 

316 refs = state.get_referenced_states() 

317 for ref in refs: 

318 # $current is a special token for retry 

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

320 errors.append( 

321 ValidationError( 

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

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

324 ) 

325 ) 

326 

327 # Validate action configuration 

328 errors.extend(_validate_state_action(state_name, state)) 

329 

330 # Validate evaluator if present 

331 if state.evaluate is not None: 

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

333 

334 # Validate routing configuration 

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

336 

337 # Check numeric field ranges 

338 if fsm.max_iterations <= 0: 

339 errors.append( 

340 ValidationError( 

341 message=f"max_iterations must be > 0, got {fsm.max_iterations}", 

342 path="max_iterations", 

343 ) 

344 ) 

345 if fsm.backoff is not None and fsm.backoff < 0: 

346 errors.append( 

347 ValidationError( 

348 message=f"backoff must be >= 0, got {fsm.backoff}", 

349 path="backoff", 

350 ) 

351 ) 

352 if fsm.timeout is not None and fsm.timeout <= 0: 

353 errors.append( 

354 ValidationError( 

355 message=f"timeout must be > 0, got {fsm.timeout}", 

356 path="timeout", 

357 ) 

358 ) 

359 if fsm.llm.max_tokens <= 0: 

360 errors.append( 

361 ValidationError( 

362 message=f"llm.max_tokens must be > 0, got {fsm.llm.max_tokens}", 

363 path="llm.max_tokens", 

364 ) 

365 ) 

366 if fsm.llm.timeout <= 0: 

367 errors.append( 

368 ValidationError( 

369 message=f"llm.timeout must be > 0, got {fsm.llm.timeout}", 

370 path="llm.timeout", 

371 ) 

372 ) 

373 

374 # Check for unreachable states (warning only) 

375 reachable = _find_reachable_states(fsm) 

376 unreachable = defined_states - reachable 

377 for state_name in unreachable: 

378 errors.append( 

379 ValidationError( 

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

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

382 severity=ValidationSeverity.WARNING, 

383 ) 

384 ) 

385 

386 return errors 

387 

388 

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

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

391 

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

393 

394 Args: 

395 fsm: The FSM loop to analyze 

396 

397 Returns: 

398 Set of reachable state names 

399 """ 

400 reachable: set[str] = set() 

401 to_visit: deque[str] = deque([fsm.initial]) 

402 

403 while to_visit: 

404 current = to_visit.popleft() 

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

406 continue 

407 

408 reachable.add(current) 

409 state = fsm.states[current] 

410 refs = state.get_referenced_states() 

411 

412 for ref in refs: 

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

414 to_visit.append(ref) 

415 

416 return reachable 

417 

418 

419def load_and_validate(path: Path) -> tuple[FSMLoop, list[ValidationError]]: 

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

421 

422 Args: 

423 path: Path to the YAML file to load 

424 

425 Returns: 

426 Tuple of (validated FSMLoop instance, list of WARNING-severity ValidationErrors) 

427 

428 Raises: 

429 FileNotFoundError: If the file doesn't exist 

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

431 ValueError: If validation fails (contains error details) 

432 """ 

433 if not path.exists(): 

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

435 

436 with open(path) as f: 

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

438 

439 if not isinstance(data, dict): 

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

441 

442 # Check required fields before parsing 

443 missing = [] 

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

445 if field not in data: 

446 missing.append(field) 

447 

448 if missing: 

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

450 

451 # Check for unknown top-level keys before parsing 

452 unknown_key_warnings: list[ValidationError] = [] 

453 unknown = set(data.keys()) - KNOWN_TOP_LEVEL_KEYS 

454 if unknown: 

455 unknown_key_warnings.append( 

456 ValidationError( 

457 path="<root>", 

458 message=f"Unknown top-level keys: {', '.join(sorted(unknown))}", 

459 severity=ValidationSeverity.WARNING, 

460 ) 

461 ) 

462 

463 # Parse into dataclass 

464 fsm = FSMLoop.from_dict(data) 

465 

466 # Validate 

467 errors = validate_fsm(fsm) 

468 

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

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

471 

472 if error_list: 

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

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

475 

476 # Collect all warnings (unknown-key warnings + structural warnings) 

477 struct_warnings = [e for e in errors if e.severity == ValidationSeverity.WARNING] 

478 all_warnings = unknown_key_warnings + struct_warnings 

479 for warning in all_warnings: 

480 logger.warning(str(warning)) 

481 

482 return fsm, all_warnings