Coverage for little_loops / fsm / persistence.py: 25%

223 statements  

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

1"""State persistence and event streaming for FSM loops. 

2 

3This module provides persistence capabilities for FSM loop execution: 

4- LoopState: Dataclass representing loop execution state 

5- StatePersistence: File I/O for state and events 

6- PersistentExecutor: Wrapper that persists state during execution 

7- Utility functions for listing running loops and reading history 

8 

9File structure: 

10 .loops/ 

11 ├── fix-types.yaml # Loop definition 

12 ├── .running/ # Runtime state (auto-managed) 

13 │ ├── fix-types.state.json 

14 │ └── fix-types.events.jsonl 

15 └── .history/ # Archived run logs (auto-populated) 

16 └── fix-types/ 

17 └── 2024-01-15T103000/ 

18 ├── state.json 

19 └── events.jsonl 

20""" 

21 

22from __future__ import annotations 

23 

24import json 

25import logging 

26import shutil 

27import time 

28from dataclasses import dataclass, field 

29from datetime import UTC, datetime 

30from pathlib import Path 

31from typing import Any 

32 

33from little_loops.fsm.executor import EventCallback, ExecutionResult, FSMExecutor 

34from little_loops.fsm.schema import FSMLoop 

35 

36RUNNING_DIR = ".running" 

37HISTORY_DIR = ".history" 

38 

39logger = logging.getLogger(__name__) 

40 

41 

42def _iso_now() -> str: 

43 """Return current time as ISO 8601 string.""" 

44 return datetime.now(UTC).isoformat() 

45 

46 

47def _now_ms() -> int: 

48 """Return current time in milliseconds.""" 

49 return int(time.time() * 1000) 

50 

51 

52@dataclass 

53class LoopState: 

54 """Persistent state for an FSM loop execution. 

55 

56 This captures all runtime state needed to resume a loop: 

57 - Current state and iteration 

58 - Captured variables and previous result 

59 - Last evaluation result 

60 - Timestamps and status 

61 

62 Attributes: 

63 loop_name: Name of the loop 

64 current_state: Current FSM state name 

65 iteration: Current iteration count (1-based) 

66 captured: Captured action outputs by variable name 

67 prev_result: Previous state's result (output, exit_code, state) 

68 last_result: Last evaluation result (verdict, details) 

69 started_at: ISO timestamp when loop started 

70 updated_at: ISO timestamp when state was last saved 

71 status: Execution status (running, completed, failed, interrupted, awaiting_continuation, timed_out) 

72 continuation_prompt: Continuation context from handoff signal (if status is awaiting_continuation) 

73 accumulated_ms: Total milliseconds elapsed across all segments up to this save (used to restore 

74 elapsed time correctly after resume, so duration_ms and ${loop.elapsed_ms} reflect the 

75 full loop lifetime rather than only the most recent segment) 

76 """ 

77 

78 loop_name: str 

79 current_state: str 

80 iteration: int 

81 captured: dict[str, dict[str, Any]] 

82 prev_result: dict[str, Any] | None 

83 last_result: dict[str, Any] | None 

84 started_at: str 

85 updated_at: str 

86 status: ( 

87 str # "running", "completed", "failed", "interrupted", "awaiting_continuation", "timed_out" 

88 ) 

89 continuation_prompt: str | None = None 

90 accumulated_ms: int = 0 # total elapsed ms across all segments (for resume offset) 

91 retry_counts: dict[str, int] = field(default_factory=dict) # per-state retry tracking 

92 

93 def to_dict(self) -> dict[str, Any]: 

94 """Convert to dictionary for JSON serialization.""" 

95 result = { 

96 "loop_name": self.loop_name, 

97 "current_state": self.current_state, 

98 "iteration": self.iteration, 

99 "captured": self.captured, 

100 "prev_result": self.prev_result, 

101 "last_result": self.last_result, 

102 "started_at": self.started_at, 

103 "updated_at": self.updated_at, 

104 "status": self.status, 

105 "accumulated_ms": self.accumulated_ms, 

106 } 

107 if self.continuation_prompt is not None: 

108 result["continuation_prompt"] = self.continuation_prompt 

109 if self.retry_counts: 

110 result["retry_counts"] = self.retry_counts 

111 return result 

112 

113 @classmethod 

114 def from_dict(cls, data: dict[str, Any]) -> LoopState: 

115 """Create LoopState from dictionary. 

116 

117 Args: 

118 data: Dictionary with loop state fields 

119 

120 Returns: 

121 LoopState instance 

122 """ 

123 return cls( 

124 loop_name=data["loop_name"], 

125 current_state=data["current_state"], 

126 iteration=data["iteration"], 

127 captured=data.get("captured", {}), 

128 prev_result=data.get("prev_result"), 

129 last_result=data.get("last_result"), 

130 started_at=data["started_at"], 

131 updated_at=data.get("updated_at", ""), 

132 status=data["status"], 

133 continuation_prompt=data.get("continuation_prompt"), 

134 accumulated_ms=data.get("accumulated_ms", 0), 

135 retry_counts=data.get("retry_counts", {}), 

136 ) 

137 

138 

139class StatePersistence: 

140 """Manage loop state persistence and event streaming. 

141 

142 Handles file I/O for: 

143 - State file: JSON file with current execution state 

144 - Events file: JSONL file with execution events (append-only) 

145 

146 Files are stored in .loops/.running/<loop_name>.* 

147 """ 

148 

149 def __init__(self, loop_name: str, loops_dir: Path | None = None) -> None: 

150 """Initialize persistence for a loop. 

151 

152 Args: 

153 loop_name: Name of the loop 

154 loops_dir: Base directory for loops (default: .loops) 

155 """ 

156 self.loop_name = loop_name 

157 self.loops_dir = loops_dir or Path(".loops") 

158 self.running_dir = self.loops_dir / RUNNING_DIR 

159 self.state_file = self.running_dir / f"{loop_name}.state.json" 

160 self.events_file = self.running_dir / f"{loop_name}.events.jsonl" 

161 

162 def initialize(self) -> None: 

163 """Create running directory if needed.""" 

164 self.running_dir.mkdir(parents=True, exist_ok=True) 

165 

166 def save_state(self, state: LoopState) -> None: 

167 """Save current state to file. 

168 

169 Updates the updated_at timestamp before saving. 

170 

171 Args: 

172 state: LoopState to save 

173 """ 

174 state.updated_at = _iso_now() 

175 self.state_file.write_text(json.dumps(state.to_dict(), indent=2)) 

176 

177 def load_state(self) -> LoopState | None: 

178 """Load state from file, or None if not exists. 

179 

180 Returns: 

181 LoopState if file exists and is valid, None otherwise 

182 """ 

183 if not self.state_file.exists(): 

184 return None 

185 try: 

186 data = json.loads(self.state_file.read_text()) 

187 except json.JSONDecodeError: 

188 return None 

189 try: 

190 return LoopState.from_dict(data) 

191 except KeyError as e: 

192 logger.warning("Corrupted state file %s: missing key %s", self.state_file, e) 

193 return None 

194 

195 def clear_state(self) -> None: 

196 """Remove state file.""" 

197 if self.state_file.exists(): 

198 self.state_file.unlink() 

199 

200 def append_event(self, event: dict[str, Any]) -> None: 

201 """Append event to JSONL file. 

202 

203 Args: 

204 event: Event dictionary to append 

205 """ 

206 with open(self.events_file, "a", encoding="utf-8") as f: 

207 f.write(json.dumps(event) + "\n") 

208 

209 def read_events(self) -> list[dict[str, Any]]: 

210 """Read all events from file. 

211 

212 Returns: 

213 List of event dictionaries, empty if file doesn't exist 

214 """ 

215 if not self.events_file.exists(): 

216 return [] 

217 events: list[dict[str, Any]] = [] 

218 with open(self.events_file, encoding="utf-8") as f: 

219 for line in f: 

220 line = line.strip() 

221 if line: 

222 try: 

223 events.append(json.loads(line)) 

224 except json.JSONDecodeError: 

225 continue # Skip malformed lines 

226 return events 

227 

228 def clear_events(self) -> None: 

229 """Remove events file.""" 

230 if self.events_file.exists(): 

231 self.events_file.unlink() 

232 

233 def archive_run(self) -> Path | None: 

234 """Archive current run files to .history/ before clearing. 

235 

236 Reads the current state to derive the run timestamp, then copies 

237 both state.json and events.jsonl into: 

238 <loops_dir>/.history/<loop_name>/<run_id>/ 

239 

240 where run_id is a compact ISO timestamp derived from started_at 

241 (e.g. "2024-01-15T103000" from "2024-01-15T10:30:00.123456+00:00"). 

242 

243 Returns: 

244 Path to the archive directory if files were archived, None if 

245 there were no files to archive (fresh run). 

246 """ 

247 has_state = self.state_file.exists() 

248 has_events = self.events_file.exists() 

249 if not has_state and not has_events: 

250 return None 

251 

252 # Derive run ID from started_at in state file, or fall back to now 

253 state = self.load_state() 

254 if state is not None and state.started_at: 

255 # Compact ISO: strip colons, dots, plus signs; take first 19 chars 

256 # e.g. "2024-01-15T10:30:00.123+00:00" → "2024-01-15T103000" 

257 run_id = state.started_at.replace(":", "").replace(".", "").replace("+", "")[:17] 

258 else: 

259 run_id = datetime.now(UTC).strftime("%Y-%m-%dT%H%M%S") 

260 

261 archive_dir = self.loops_dir / HISTORY_DIR / self.loop_name / run_id 

262 archive_dir.mkdir(parents=True, exist_ok=True) 

263 

264 if has_state: 

265 shutil.copy2(self.state_file, archive_dir / "state.json") 

266 if has_events: 

267 shutil.copy2(self.events_file, archive_dir / "events.jsonl") 

268 

269 return archive_dir 

270 

271 def clear_all(self) -> None: 

272 """Archive current run files then clear state and events (for new run).""" 

273 self.archive_run() 

274 self.clear_state() 

275 self.clear_events() 

276 

277 

278class PersistentExecutor: 

279 """FSM Executor with state persistence and event streaming. 

280 

281 Wraps FSMExecutor to: 

282 - Save state after each state transition 

283 - Append events to JSONL file as they occur 

284 - Support resuming from saved state 

285 - Support graceful shutdown via signal handling 

286 """ 

287 

288 def __init__( 

289 self, 

290 fsm: FSMLoop, 

291 persistence: StatePersistence | None = None, 

292 loops_dir: Path | None = None, 

293 **executor_kwargs: Any, 

294 ) -> None: 

295 """Initialize persistent executor. 

296 

297 Args: 

298 fsm: FSM loop definition 

299 persistence: Optional pre-configured persistence (for testing) 

300 loops_dir: Base directory for loops (default: .loops) 

301 **executor_kwargs: Additional kwargs for FSMExecutor 

302 """ 

303 from little_loops.fsm.handoff_handler import HandoffBehavior, HandoffHandler 

304 from little_loops.fsm.signal_detector import SignalDetector 

305 

306 self.fsm = fsm 

307 self.persistence = persistence or StatePersistence(fsm.name, loops_dir or Path(".loops")) 

308 self.persistence.initialize() 

309 

310 # Create signal detector and handler based on FSM config 

311 signal_detector = SignalDetector() 

312 handoff_handler = HandoffHandler(HandoffBehavior(fsm.on_handoff)) 

313 

314 # Create base executor with event callback that persists 

315 self._executor = FSMExecutor( 

316 fsm, 

317 event_callback=self._handle_event, 

318 signal_detector=signal_detector, 

319 handoff_handler=handoff_handler, 

320 **executor_kwargs, 

321 ) 

322 self._last_result: dict[str, Any] | None = None 

323 self._continuation_prompt: str | None = None 

324 self._on_event: EventCallback | None = None 

325 

326 def request_shutdown(self) -> None: 

327 """Request graceful shutdown of the executor. 

328 

329 Delegates to the underlying FSMExecutor's request_shutdown method. 

330 The loop will exit cleanly after the current state completes, 

331 saving state as "interrupted" so it can be resumed later. 

332 """ 

333 self._executor.request_shutdown() 

334 

335 def _handle_event(self, event: dict[str, Any]) -> None: 

336 """Handle event: persist to file and save state. 

337 

338 Args: 

339 event: Event dictionary from executor 

340 """ 

341 self.persistence.append_event(event) 

342 

343 # Save state after state transitions 

344 event_type = event.get("event") 

345 if event_type in ("state_enter", "loop_complete"): 

346 self._save_state() 

347 

348 # Track evaluation results for state persistence 

349 if event_type == "evaluate": 

350 self._last_result = { 

351 "verdict": event.get("verdict"), 

352 "details": { 

353 k: v for k, v in event.items() if k not in ("event", "ts", "type", "verdict") 

354 }, 

355 } 

356 

357 # Track handoff events for continuation prompt 

358 if event_type == "handoff_detected": 

359 self._continuation_prompt = event.get("continuation") 

360 

361 # Delegate to secondary observer (e.g. progress display) 

362 if self._on_event is not None: 

363 self._on_event(event) 

364 

365 def _save_state(self) -> None: 

366 """Save current executor state to file.""" 

367 status = "running" 

368 if self._executor.current_state: 

369 state_config = self.fsm.states.get(self._executor.current_state) 

370 if state_config and state_config.terminal: 

371 status = "completed" 

372 

373 state = LoopState( 

374 loop_name=self.fsm.name, 

375 current_state=self._executor.current_state, 

376 iteration=self._executor.iteration, 

377 captured=self._executor.captured, 

378 prev_result=self._executor.prev_result, 

379 last_result=self._last_result, 

380 started_at=self._executor.started_at, 

381 updated_at="", # Will be set by save_state 

382 status=status, 

383 accumulated_ms=_now_ms() 

384 - self._executor.start_time_ms 

385 + self._executor.elapsed_offset_ms, 

386 retry_counts=dict(self._executor._retry_counts), 

387 ) 

388 self.persistence.save_state(state) 

389 

390 def run(self, clear_previous: bool = True) -> ExecutionResult: 

391 """Run the FSM with persistence. 

392 

393 Args: 

394 clear_previous: If True, clear previous state/events before running 

395 

396 Returns: 

397 ExecutionResult from the execution 

398 """ 

399 if clear_previous: 

400 self.persistence.clear_all() 

401 

402 result = self._executor.run() 

403 

404 # Update final state 

405 final_status = "completed" if result.terminated_by == "terminal" else "failed" 

406 if result.terminated_by in ("max_iterations", "signal"): 

407 final_status = "interrupted" 

408 if result.terminated_by == "handoff": 

409 final_status = "awaiting_continuation" 

410 if result.terminated_by == "timeout": 

411 final_status = "timed_out" 

412 

413 final_state = LoopState( 

414 loop_name=self.fsm.name, 

415 current_state=result.final_state, 

416 iteration=result.iterations, 

417 captured=result.captured, 

418 prev_result=self._executor.prev_result, 

419 last_result=self._last_result, 

420 started_at=self._executor.started_at, 

421 updated_at="", 

422 status=final_status, 

423 continuation_prompt=self._continuation_prompt, 

424 accumulated_ms=result.duration_ms, 

425 ) 

426 self.persistence.save_state(final_state) 

427 

428 return result 

429 

430 def resume(self) -> ExecutionResult | None: 

431 """Resume from saved state, or None if no resumable state. 

432 

433 Resumable states are: "running" and "awaiting_continuation". 

434 

435 Returns: 

436 ExecutionResult if resumed and completed, None if no resumable state 

437 """ 

438 state = self.persistence.load_state() 

439 if state is None: 

440 return None 

441 

442 if state.status not in ("running", "awaiting_continuation"): 

443 return None # Already completed/failed 

444 

445 # Restore executor state 

446 self._executor.current_state = state.current_state 

447 self._executor.iteration = state.iteration 

448 self._executor.captured = state.captured 

449 self._executor.prev_result = state.prev_result 

450 self._executor.started_at = state.started_at 

451 self._last_result = state.last_result 

452 self._executor._retry_counts = dict(state.retry_counts) 

453 

454 # Restore accumulated elapsed time so duration_ms and ${loop.elapsed_ms} reflect 

455 # the full loop lifetime (all segments), not just the resumed segment. 

456 # FSMExecutor.run() will reset start_time_ms to _now_ms(), so we use elapsed_offset_ms 

457 # to carry forward the time already spent before this resume. 

458 self._executor.elapsed_offset_ms = state.accumulated_ms 

459 

460 # Clear any pending signals from previous run 

461 self._executor._pending_handoff = None 

462 self._executor._pending_error = None 

463 

464 # Emit resume event with continuation context if available 

465 resume_event: dict[str, Any] = { 

466 "event": "loop_resume", 

467 "ts": _iso_now(), 

468 "loop": self.fsm.name, 

469 "from_state": state.current_state, 

470 "iteration": state.iteration, 

471 } 

472 if state.status == "awaiting_continuation" and state.continuation_prompt: 

473 resume_event["from_handoff"] = True 

474 resume_event["continuation_prompt"] = state.continuation_prompt 

475 self.persistence.append_event(resume_event) 

476 

477 # Continue execution (don't clear previous events) 

478 return self.run(clear_previous=False) 

479 

480 

481def list_running_loops(loops_dir: Path | None = None) -> list[LoopState]: 

482 """List all loops with saved state. 

483 

484 Args: 

485 loops_dir: Base directory for loops (default: .loops) 

486 

487 Returns: 

488 List of LoopState objects for all loops with state files 

489 """ 

490 base_dir = loops_dir or Path(".loops") 

491 running_dir = base_dir / RUNNING_DIR 

492 

493 if not running_dir.exists(): 

494 return [] 

495 

496 states: list[LoopState] = [] 

497 for state_file in running_dir.glob("*.state.json"): 

498 try: 

499 data = json.loads(state_file.read_text()) 

500 states.append(LoopState.from_dict(data)) 

501 except (json.JSONDecodeError, KeyError): 

502 continue # Skip malformed files 

503 

504 return states 

505 

506 

507def list_run_history(loop_name: str, loops_dir: Path | None = None) -> list[LoopState]: 

508 """List archived runs for a loop, newest first. 

509 

510 Reads state files from .loops/.history/<loop_name>/*/state.json and returns 

511 them sorted by started_at descending (most recent run first). 

512 

513 Args: 

514 loop_name: Name of the loop 

515 loops_dir: Base directory for loops (default: .loops) 

516 

517 Returns: 

518 List of LoopState objects for all archived runs, newest first. 

519 Returns an empty list if no history exists. 

520 """ 

521 base_dir = loops_dir or Path(".loops") 

522 history_loop_dir = base_dir / HISTORY_DIR / loop_name 

523 

524 if not history_loop_dir.exists(): 

525 return [] 

526 

527 states: list[LoopState] = [] 

528 for state_file in history_loop_dir.glob("*/state.json"): 

529 try: 

530 data = json.loads(state_file.read_text()) 

531 states.append(LoopState.from_dict(data)) 

532 except (json.JSONDecodeError, KeyError): 

533 continue 

534 

535 states.sort(key=lambda s: s.started_at, reverse=True) 

536 return states 

537 

538 

539def get_archived_events( 

540 loop_name: str, run_id: str, loops_dir: Path | None = None 

541) -> list[dict[str, Any]]: 

542 """Read events for a specific archived run. 

543 

544 Args: 

545 loop_name: Name of the loop 

546 run_id: The run directory name (compact timestamp) 

547 loops_dir: Base directory for loops (default: .loops) 

548 

549 Returns: 

550 List of event dictionaries, empty if not found. 

551 """ 

552 base_dir = loops_dir or Path(".loops") 

553 events_file = base_dir / HISTORY_DIR / loop_name / run_id / "events.jsonl" 

554 

555 if not events_file.exists(): 

556 return [] 

557 

558 events: list[dict[str, Any]] = [] 

559 with open(events_file, encoding="utf-8") as f: 

560 for line in f: 

561 line = line.strip() 

562 if line: 

563 try: 

564 events.append(json.loads(line)) 

565 except json.JSONDecodeError: 

566 continue 

567 return events 

568 

569 

570def get_loop_history(loop_name: str, loops_dir: Path | None = None) -> list[dict[str, Any]]: 

571 """Get event history for a loop. 

572 

573 Args: 

574 loop_name: Name of the loop 

575 loops_dir: Base directory for loops (default: .loops) 

576 

577 Returns: 

578 List of event dictionaries 

579 """ 

580 persistence = StatePersistence(loop_name, loops_dir) 

581 return persistence.read_events()