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

256 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-04-02 13:00 -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 os 

27import shutil 

28import tempfile 

29import time 

30from dataclasses import dataclass, field 

31from datetime import UTC, datetime 

32from pathlib import Path 

33from typing import Any 

34 

35from little_loops.events import EventBus 

36from little_loops.fsm.concurrency import _process_alive 

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

38from little_loops.fsm.schema import FSMLoop 

39 

40RUNNING_DIR = ".running" 

41HISTORY_DIR = ".history" 

42 

43logger = logging.getLogger(__name__) 

44 

45 

46def _iso_now() -> str: 

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

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

49 

50 

51def _now_ms() -> int: 

52 """Return current time in milliseconds.""" 

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

54 

55 

56@dataclass 

57class LoopState: 

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

59 

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

61 - Current state and iteration 

62 - Captured variables and previous result 

63 - Last evaluation result 

64 - Timestamps and status 

65 

66 Attributes: 

67 loop_name: Name of the loop 

68 current_state: Current FSM state name 

69 iteration: Current iteration count (1-based) 

70 captured: Captured action outputs by variable name 

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

72 last_result: Last evaluation result (verdict, details) 

73 started_at: ISO timestamp when loop started 

74 updated_at: ISO timestamp when state was last saved 

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

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

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

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

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

80 """ 

81 

82 loop_name: str 

83 current_state: str 

84 iteration: int 

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

86 prev_result: dict[str, Any] | None 

87 last_result: dict[str, Any] | None 

88 started_at: str 

89 updated_at: str 

90 status: ( 

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

92 ) 

93 continuation_prompt: str | None = None 

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

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

96 active_sub_loop: str | None = None # name of currently executing sub-loop (observability) 

97 

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

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

100 result = { 

101 "loop_name": self.loop_name, 

102 "current_state": self.current_state, 

103 "iteration": self.iteration, 

104 "captured": self.captured, 

105 "prev_result": self.prev_result, 

106 "last_result": self.last_result, 

107 "started_at": self.started_at, 

108 "updated_at": self.updated_at, 

109 "status": self.status, 

110 "accumulated_ms": self.accumulated_ms, 

111 } 

112 if self.continuation_prompt is not None: 

113 result["continuation_prompt"] = self.continuation_prompt 

114 if self.retry_counts: 

115 result["retry_counts"] = self.retry_counts 

116 if self.active_sub_loop is not None: 

117 result["active_sub_loop"] = self.active_sub_loop 

118 return result 

119 

120 @classmethod 

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

122 """Create LoopState from dictionary. 

123 

124 Args: 

125 data: Dictionary with loop state fields 

126 

127 Returns: 

128 LoopState instance 

129 """ 

130 return cls( 

131 loop_name=data["loop_name"], 

132 current_state=data["current_state"], 

133 iteration=data["iteration"], 

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

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

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

137 started_at=data["started_at"], 

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

139 status=data["status"], 

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

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

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

143 active_sub_loop=data.get("active_sub_loop"), 

144 ) 

145 

146 

147class StatePersistence: 

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

149 

150 Handles file I/O for: 

151 - State file: JSON file with current execution state 

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

153 

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

155 """ 

156 

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

158 """Initialize persistence for a loop. 

159 

160 Args: 

161 loop_name: Name of the loop 

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

163 """ 

164 self.loop_name = loop_name 

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

166 self.running_dir = self.loops_dir / RUNNING_DIR 

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

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

169 

170 def initialize(self) -> None: 

171 """Create running directory if needed.""" 

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

173 

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

175 """Save current state to file using an atomic write. 

176 

177 Updates the updated_at timestamp before saving. Writes to a temporary 

178 file first, then renames it over the target to avoid leaving a corrupt 

179 or empty state file if the process is killed mid-write. 

180 

181 Args: 

182 state: LoopState to save 

183 """ 

184 state.updated_at = _iso_now() 

185 data = json.dumps(state.to_dict(), indent=2) 

186 tmp_fd, tmp_path = tempfile.mkstemp(dir=self.state_file.parent, suffix=".tmp") 

187 try: 

188 with os.fdopen(tmp_fd, "w") as f: 

189 f.write(data) 

190 os.replace(tmp_path, self.state_file) 

191 except Exception: 

192 os.unlink(tmp_path) 

193 raise 

194 

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

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

197 

198 Returns: 

199 LoopState if file exists and is valid, None otherwise 

200 """ 

201 if not self.state_file.exists(): 

202 return None 

203 try: 

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

205 except json.JSONDecodeError: 

206 return None 

207 try: 

208 return LoopState.from_dict(data) 

209 except KeyError as e: 

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

211 return None 

212 

213 def clear_state(self) -> None: 

214 """Remove state file.""" 

215 if self.state_file.exists(): 

216 self.state_file.unlink() 

217 

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

219 """Append event to JSONL file. 

220 

221 Args: 

222 event: Event dictionary to append 

223 """ 

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

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

226 

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

228 """Read all events from file. 

229 

230 Returns: 

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

232 """ 

233 if not self.events_file.exists(): 

234 return [] 

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

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

237 for line in f: 

238 line = line.strip() 

239 if line: 

240 try: 

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

242 except json.JSONDecodeError: 

243 continue # Skip malformed lines 

244 return events 

245 

246 def clear_events(self) -> None: 

247 """Remove events file.""" 

248 if self.events_file.exists(): 

249 self.events_file.unlink() 

250 

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

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

253 

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

255 both state.json and events.jsonl into: 

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

257 

258 where run_id is a compact ISO timestamp derived from started_at 

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

260 

261 Returns: 

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

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

264 """ 

265 has_state = self.state_file.exists() 

266 has_events = self.events_file.exists() 

267 if not has_state and not has_events: 

268 return None 

269 

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

271 state = self.load_state() 

272 if state is not None and state.started_at: 

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

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

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

276 else: 

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

278 

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

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

281 

282 if has_state: 

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

284 if has_events: 

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

286 

287 return archive_dir 

288 

289 def clear_all(self) -> None: 

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

291 self.archive_run() 

292 self.clear_state() 

293 self.clear_events() 

294 

295 

296class PersistentExecutor: 

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

298 

299 Wraps FSMExecutor to: 

300 - Save state after each state transition 

301 - Append events to JSONL file as they occur 

302 - Support resuming from saved state 

303 - Support graceful shutdown via signal handling 

304 """ 

305 

306 def __init__( 

307 self, 

308 fsm: FSMLoop, 

309 persistence: StatePersistence | None = None, 

310 loops_dir: Path | None = None, 

311 **executor_kwargs: Any, 

312 ) -> None: 

313 """Initialize persistent executor. 

314 

315 Args: 

316 fsm: FSM loop definition 

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

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

319 **executor_kwargs: Additional kwargs for FSMExecutor 

320 """ 

321 from little_loops.fsm.handoff_handler import HandoffBehavior, HandoffHandler 

322 from little_loops.fsm.signal_detector import SignalDetector 

323 

324 self.fsm = fsm 

325 self.loops_dir = loops_dir 

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

327 self.persistence.initialize() 

328 

329 # Create signal detector and handler based on FSM config 

330 signal_detector = SignalDetector() 

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

332 

333 # Create base executor with event callback that persists 

334 self._executor = FSMExecutor( 

335 fsm, 

336 event_callback=self._handle_event, 

337 signal_detector=signal_detector, 

338 handoff_handler=handoff_handler, 

339 loops_dir=self.loops_dir, 

340 **executor_kwargs, 

341 ) 

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

343 self._continuation_prompt: str | None = None 

344 self.event_bus = EventBus() 

345 

346 @property 

347 def _on_event(self) -> EventCallback | None: 

348 """Backward-compatible access to the first observer on the event bus.""" 

349 return self.event_bus._observers[0] if self.event_bus._observers else None 

350 

351 @_on_event.setter 

352 def _on_event(self, callback: EventCallback | None) -> None: 

353 """Backward-compatible setter: replaces all observers with this one.""" 

354 self.event_bus._observers.clear() 

355 if callback is not None: 

356 self.event_bus.register(callback) 

357 

358 def request_shutdown(self) -> None: 

359 """Request graceful shutdown of the executor. 

360 

361 Delegates to the underlying FSMExecutor's request_shutdown method. 

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

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

364 """ 

365 self._executor.request_shutdown() 

366 

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

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

369 

370 Args: 

371 event: Event dictionary from executor 

372 """ 

373 self.persistence.append_event(event) 

374 

375 # Save state after state transitions 

376 event_type = event.get("event") 

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

378 self._save_state() 

379 

380 # Track evaluation results for state persistence 

381 if event_type == "evaluate": 

382 self._last_result = { 

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

384 "details": { 

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

386 }, 

387 } 

388 

389 # Track handoff events for continuation prompt 

390 if event_type == "handoff_detected": 

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

392 

393 # Delegate to registered observers (e.g. progress display, extensions) 

394 self.event_bus.emit(event) 

395 

396 def _save_state(self) -> None: 

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

398 status = "running" 

399 if self._executor.current_state: 

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

401 if state_config and state_config.terminal: 

402 status = "completed" 

403 

404 state = LoopState( 

405 loop_name=self.fsm.name, 

406 current_state=self._executor.current_state, 

407 iteration=self._executor.iteration, 

408 captured=self._executor.captured, 

409 prev_result=self._executor.prev_result, 

410 last_result=self._last_result, 

411 started_at=self._executor.started_at, 

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

413 status=status, 

414 accumulated_ms=_now_ms() 

415 - self._executor.start_time_ms 

416 + self._executor.elapsed_offset_ms, 

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

418 ) 

419 self.persistence.save_state(state) 

420 

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

422 """Run the FSM with persistence. 

423 

424 Args: 

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

426 

427 Returns: 

428 ExecutionResult from the execution 

429 """ 

430 if clear_previous: 

431 self.persistence.clear_all() 

432 

433 result = self._executor.run() 

434 

435 # Update final state 

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

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

438 final_status = "interrupted" 

439 if result.terminated_by == "handoff": 

440 final_status = "awaiting_continuation" 

441 if result.terminated_by == "timeout": 

442 final_status = "timed_out" 

443 

444 final_state = LoopState( 

445 loop_name=self.fsm.name, 

446 current_state=result.final_state, 

447 iteration=result.iterations, 

448 captured=result.captured, 

449 prev_result=self._executor.prev_result, 

450 last_result=self._last_result, 

451 started_at=self._executor.started_at, 

452 updated_at="", 

453 status=final_status, 

454 continuation_prompt=self._continuation_prompt, 

455 accumulated_ms=result.duration_ms, 

456 ) 

457 self.persistence.save_state(final_state) 

458 

459 return result 

460 

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

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

463 

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

465 

466 Returns: 

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

468 """ 

469 state = self.persistence.load_state() 

470 if state is None: 

471 return None 

472 

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

474 return None # Already completed/failed 

475 

476 # Restore executor state 

477 self._executor.current_state = state.current_state 

478 self._executor.iteration = state.iteration 

479 self._executor.captured = state.captured 

480 self._executor.prev_result = state.prev_result 

481 self._executor.started_at = state.started_at 

482 self._last_result = state.last_result 

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

484 

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

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

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

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

489 self._executor.elapsed_offset_ms = state.accumulated_ms 

490 

491 # Clear any pending signals from previous run 

492 self._executor._pending_handoff = None 

493 self._executor._pending_error = None 

494 

495 # Emit resume event with continuation context if available 

496 resume_event: dict[str, Any] = { 

497 "event": "loop_resume", 

498 "ts": _iso_now(), 

499 "loop": self.fsm.name, 

500 "from_state": state.current_state, 

501 "iteration": state.iteration, 

502 } 

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

504 resume_event["from_handoff"] = True 

505 resume_event["continuation_prompt"] = state.continuation_prompt 

506 self.persistence.append_event(resume_event) 

507 

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

509 return self.run(clear_previous=False) 

510 

511 

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

513 """List all loops with saved state. 

514 

515 Args: 

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

517 

518 Returns: 

519 List of LoopState objects for all loops with state files 

520 """ 

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

522 running_dir = base_dir / RUNNING_DIR 

523 

524 if not running_dir.exists(): 

525 return [] 

526 

527 states: list[LoopState] = [] 

528 for state_file in running_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 # Skip malformed files 

534 

535 # Include loops that have a PID file but no state file yet (still starting up) 

536 known_names = {s.loop_name for s in states} 

537 for pid_file in running_dir.glob("*.pid"): 

538 if pid_file.stem in known_names: 

539 continue # state file already covers this loop 

540 try: 

541 pid = int(pid_file.read_text().strip()) 

542 except (ValueError, OSError): 

543 continue 

544 if _process_alive(pid): 

545 states.append( 

546 LoopState( 

547 loop_name=pid_file.stem, 

548 current_state="(initializing)", 

549 iteration=0, 

550 captured={}, 

551 prev_result=None, 

552 last_result=None, 

553 started_at="", 

554 updated_at="", 

555 status="starting", 

556 ) 

557 ) 

558 

559 return states 

560 

561 

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

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

564 

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

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

567 

568 Args: 

569 loop_name: Name of the loop 

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

571 

572 Returns: 

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

574 Returns an empty list if no history exists. 

575 """ 

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

577 history_loop_dir = base_dir / HISTORY_DIR / loop_name 

578 

579 if not history_loop_dir.exists(): 

580 return [] 

581 

582 states: list[LoopState] = [] 

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

584 try: 

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

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

587 except (json.JSONDecodeError, KeyError): 

588 continue 

589 

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

591 return states 

592 

593 

594def get_archived_events( 

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

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

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

598 

599 Args: 

600 loop_name: Name of the loop 

601 run_id: The run directory name (compact timestamp) 

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

603 

604 Returns: 

605 List of event dictionaries, empty if not found. 

606 """ 

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

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

609 

610 if not events_file.exists(): 

611 return [] 

612 

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

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

615 for line in f: 

616 line = line.strip() 

617 if line: 

618 try: 

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

620 except json.JSONDecodeError: 

621 continue 

622 return events 

623 

624 

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

626 """Get event history for a loop. 

627 

628 Args: 

629 loop_name: Name of the loop 

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

631 

632 Returns: 

633 List of event dictionaries 

634 """ 

635 persistence = StatePersistence(loop_name, loops_dir) 

636 return persistence.read_events()