Coverage for little_loops / fsm / persistence.py: 97%
162 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-04 01:17 -0600
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-04 01:17 -0600
1"""State persistence and event streaming for FSM loops.
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
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"""
17from __future__ import annotations
19import json
20import time
21from dataclasses import dataclass
22from datetime import UTC, datetime
23from pathlib import Path
24from typing import Any
26from little_loops.fsm.executor import EventCallback, ExecutionResult, FSMExecutor
27from little_loops.fsm.schema import FSMLoop
29RUNNING_DIR = ".running"
32def _iso_now() -> str:
33 """Return current time as ISO 8601 string."""
34 return datetime.now(UTC).isoformat()
37def _now_ms() -> int:
38 """Return current time in milliseconds."""
39 return int(time.time() * 1000)
42@dataclass
43class LoopState:
44 """Persistent state for an FSM loop execution.
46 This captures all runtime state needed to resume a loop:
47 - Current state and iteration
48 - Captured variables and previous result
49 - Last evaluation result
50 - Timestamps and status
52 Attributes:
53 loop_name: Name of the loop
54 current_state: Current FSM state name
55 iteration: Current iteration count (1-based)
56 captured: Captured action outputs by variable name
57 prev_result: Previous state's result (output, exit_code, state)
58 last_result: Last evaluation result (verdict, details)
59 started_at: ISO timestamp when loop started
60 updated_at: ISO timestamp when state was last saved
61 status: Execution status (running, completed, failed, interrupted, awaiting_continuation)
62 continuation_prompt: Continuation context from handoff signal (if status is awaiting_continuation)
63 accumulated_ms: Total milliseconds elapsed across all segments up to this save (used to restore
64 elapsed time correctly after resume, so duration_ms and ${loop.elapsed_ms} reflect the
65 full loop lifetime rather than only the most recent segment)
66 """
68 loop_name: str
69 current_state: str
70 iteration: int
71 captured: dict[str, dict[str, Any]]
72 prev_result: dict[str, Any] | None
73 last_result: dict[str, Any] | None
74 started_at: str
75 updated_at: str
76 status: str # "running", "completed", "failed", "interrupted", "awaiting_continuation"
77 continuation_prompt: str | None = None
78 accumulated_ms: int = 0 # total elapsed ms across all segments (for resume offset)
80 def to_dict(self) -> dict[str, Any]:
81 """Convert to dictionary for JSON serialization."""
82 result = {
83 "loop_name": self.loop_name,
84 "current_state": self.current_state,
85 "iteration": self.iteration,
86 "captured": self.captured,
87 "prev_result": self.prev_result,
88 "last_result": self.last_result,
89 "started_at": self.started_at,
90 "updated_at": self.updated_at,
91 "status": self.status,
92 "accumulated_ms": self.accumulated_ms,
93 }
94 if self.continuation_prompt is not None:
95 result["continuation_prompt"] = self.continuation_prompt
96 return result
98 @classmethod
99 def from_dict(cls, data: dict[str, Any]) -> LoopState:
100 """Create LoopState from dictionary.
102 Args:
103 data: Dictionary with loop state fields
105 Returns:
106 LoopState instance
107 """
108 return cls(
109 loop_name=data["loop_name"],
110 current_state=data["current_state"],
111 iteration=data["iteration"],
112 captured=data.get("captured", {}),
113 prev_result=data.get("prev_result"),
114 last_result=data.get("last_result"),
115 started_at=data["started_at"],
116 updated_at=data.get("updated_at", ""),
117 status=data["status"],
118 continuation_prompt=data.get("continuation_prompt"),
119 accumulated_ms=data.get("accumulated_ms", 0),
120 )
123class StatePersistence:
124 """Manage loop state persistence and event streaming.
126 Handles file I/O for:
127 - State file: JSON file with current execution state
128 - Events file: JSONL file with execution events (append-only)
130 Files are stored in .loops/.running/<loop_name>.*
131 """
133 def __init__(self, loop_name: str, loops_dir: Path | None = None) -> None:
134 """Initialize persistence for a loop.
136 Args:
137 loop_name: Name of the loop
138 loops_dir: Base directory for loops (default: .loops)
139 """
140 self.loop_name = loop_name
141 self.loops_dir = loops_dir or Path(".loops")
142 self.running_dir = self.loops_dir / RUNNING_DIR
143 self.state_file = self.running_dir / f"{loop_name}.state.json"
144 self.events_file = self.running_dir / f"{loop_name}.events.jsonl"
146 def initialize(self) -> None:
147 """Create running directory if needed."""
148 self.running_dir.mkdir(parents=True, exist_ok=True)
150 def save_state(self, state: LoopState) -> None:
151 """Save current state to file.
153 Updates the updated_at timestamp before saving.
155 Args:
156 state: LoopState to save
157 """
158 state.updated_at = _iso_now()
159 self.state_file.write_text(json.dumps(state.to_dict(), indent=2))
161 def load_state(self) -> LoopState | None:
162 """Load state from file, or None if not exists.
164 Returns:
165 LoopState if file exists and is valid, None otherwise
166 """
167 if not self.state_file.exists():
168 return None
169 try:
170 data = json.loads(self.state_file.read_text())
171 return LoopState.from_dict(data)
172 except (json.JSONDecodeError, KeyError):
173 return None
175 def clear_state(self) -> None:
176 """Remove state file."""
177 if self.state_file.exists():
178 self.state_file.unlink()
180 def append_event(self, event: dict[str, Any]) -> None:
181 """Append event to JSONL file.
183 Args:
184 event: Event dictionary to append
185 """
186 with open(self.events_file, "a", encoding="utf-8") as f:
187 f.write(json.dumps(event) + "\n")
189 def read_events(self) -> list[dict[str, Any]]:
190 """Read all events from file.
192 Returns:
193 List of event dictionaries, empty if file doesn't exist
194 """
195 if not self.events_file.exists():
196 return []
197 events: list[dict[str, Any]] = []
198 with open(self.events_file, encoding="utf-8") as f:
199 for line in f:
200 line = line.strip()
201 if line:
202 try:
203 events.append(json.loads(line))
204 except json.JSONDecodeError:
205 continue # Skip malformed lines
206 return events
208 def clear_events(self) -> None:
209 """Remove events file."""
210 if self.events_file.exists():
211 self.events_file.unlink()
213 def clear_all(self) -> None:
214 """Clear both state and events files (for new run)."""
215 self.clear_state()
216 self.clear_events()
219class PersistentExecutor:
220 """FSM Executor with state persistence and event streaming.
222 Wraps FSMExecutor to:
223 - Save state after each state transition
224 - Append events to JSONL file as they occur
225 - Support resuming from saved state
226 - Support graceful shutdown via signal handling
227 """
229 def __init__(
230 self,
231 fsm: FSMLoop,
232 persistence: StatePersistence | None = None,
233 loops_dir: Path | None = None,
234 **executor_kwargs: Any,
235 ) -> None:
236 """Initialize persistent executor.
238 Args:
239 fsm: FSM loop definition
240 persistence: Optional pre-configured persistence (for testing)
241 loops_dir: Base directory for loops (default: .loops)
242 **executor_kwargs: Additional kwargs for FSMExecutor
243 """
244 from little_loops.fsm.handoff_handler import HandoffBehavior, HandoffHandler
245 from little_loops.fsm.signal_detector import SignalDetector
247 self.fsm = fsm
248 self.persistence = persistence or StatePersistence(fsm.name, loops_dir or Path(".loops"))
249 self.persistence.initialize()
251 # Create signal detector and handler based on FSM config
252 signal_detector = SignalDetector()
253 handoff_handler = HandoffHandler(HandoffBehavior(fsm.on_handoff))
255 # Create base executor with event callback that persists
256 self._executor = FSMExecutor(
257 fsm,
258 event_callback=self._handle_event,
259 signal_detector=signal_detector,
260 handoff_handler=handoff_handler,
261 **executor_kwargs,
262 )
263 self._last_result: dict[str, Any] | None = None
264 self._continuation_prompt: str | None = None
265 self._on_event: EventCallback | None = None
267 def request_shutdown(self) -> None:
268 """Request graceful shutdown of the executor.
270 Delegates to the underlying FSMExecutor's request_shutdown method.
271 The loop will exit cleanly after the current state completes,
272 saving state as "interrupted" so it can be resumed later.
273 """
274 self._executor.request_shutdown()
276 def _handle_event(self, event: dict[str, Any]) -> None:
277 """Handle event: persist to file and save state.
279 Args:
280 event: Event dictionary from executor
281 """
282 self.persistence.append_event(event)
284 # Save state after state transitions
285 event_type = event.get("event")
286 if event_type in ("state_enter", "route", "loop_complete"):
287 self._save_state()
289 # Track evaluation results for state persistence
290 if event_type == "evaluate":
291 self._last_result = {
292 "verdict": event.get("verdict"),
293 "details": {
294 k: v for k, v in event.items() if k not in ("event", "ts", "type", "verdict")
295 },
296 }
298 # Track handoff events for continuation prompt
299 if event_type == "handoff_detected":
300 self._continuation_prompt = event.get("continuation")
302 # Delegate to secondary observer (e.g. progress display)
303 if self._on_event is not None:
304 self._on_event(event)
306 def _save_state(self) -> None:
307 """Save current executor state to file."""
308 status = "running"
309 if self._executor.current_state:
310 state_config = self.fsm.states.get(self._executor.current_state)
311 if state_config and state_config.terminal:
312 status = "completed"
314 state = LoopState(
315 loop_name=self.fsm.name,
316 current_state=self._executor.current_state,
317 iteration=self._executor.iteration,
318 captured=self._executor.captured,
319 prev_result=self._executor.prev_result,
320 last_result=self._last_result,
321 started_at=self._executor.started_at,
322 updated_at="", # Will be set by save_state
323 status=status,
324 accumulated_ms=_now_ms() - self._executor.start_time_ms + self._executor.elapsed_offset_ms,
325 )
326 self.persistence.save_state(state)
328 def run(self, clear_previous: bool = True) -> ExecutionResult:
329 """Run the FSM with persistence.
331 Args:
332 clear_previous: If True, clear previous state/events before running
334 Returns:
335 ExecutionResult from the execution
336 """
337 if clear_previous:
338 self.persistence.clear_all()
340 result = self._executor.run()
342 # Update final state
343 final_status = "completed" if result.terminated_by == "terminal" else "failed"
344 if result.terminated_by in ("max_iterations", "signal"):
345 final_status = "interrupted"
346 if result.terminated_by == "handoff":
347 final_status = "awaiting_continuation"
349 final_state = LoopState(
350 loop_name=self.fsm.name,
351 current_state=result.final_state,
352 iteration=result.iterations,
353 captured=result.captured,
354 prev_result=self._executor.prev_result,
355 last_result=self._last_result,
356 started_at=self._executor.started_at,
357 updated_at="",
358 status=final_status,
359 continuation_prompt=self._continuation_prompt,
360 accumulated_ms=result.duration_ms,
361 )
362 self.persistence.save_state(final_state)
364 return result
366 def resume(self) -> ExecutionResult | None:
367 """Resume from saved state, or None if no resumable state.
369 Resumable states are: "running" and "awaiting_continuation".
371 Returns:
372 ExecutionResult if resumed and completed, None if no resumable state
373 """
374 state = self.persistence.load_state()
375 if state is None:
376 return None
378 if state.status not in ("running", "awaiting_continuation"):
379 return None # Already completed/failed
381 # Restore executor state
382 self._executor.current_state = state.current_state
383 self._executor.iteration = state.iteration
384 self._executor.captured = state.captured
385 self._executor.prev_result = state.prev_result
386 self._executor.started_at = state.started_at
387 self._last_result = state.last_result
389 # Restore accumulated elapsed time so duration_ms and ${loop.elapsed_ms} reflect
390 # the full loop lifetime (all segments), not just the resumed segment.
391 # FSMExecutor.run() will reset start_time_ms to _now_ms(), so we use elapsed_offset_ms
392 # to carry forward the time already spent before this resume.
393 self._executor.elapsed_offset_ms = state.accumulated_ms
395 # Clear any pending handoff from previous run
396 self._executor._pending_handoff = None
398 # Emit resume event with continuation context if available
399 resume_event: dict[str, Any] = {
400 "event": "loop_resume",
401 "ts": _iso_now(),
402 "loop": self.fsm.name,
403 "from_state": state.current_state,
404 "iteration": state.iteration,
405 }
406 if state.status == "awaiting_continuation" and state.continuation_prompt:
407 resume_event["from_handoff"] = True
408 resume_event["continuation_prompt"] = state.continuation_prompt
409 self.persistence.append_event(resume_event)
411 # Continue execution (don't clear previous events)
412 return self.run(clear_previous=False)
415def list_running_loops(loops_dir: Path | None = None) -> list[LoopState]:
416 """List all loops with saved state.
418 Args:
419 loops_dir: Base directory for loops (default: .loops)
421 Returns:
422 List of LoopState objects for all loops with state files
423 """
424 base_dir = loops_dir or Path(".loops")
425 running_dir = base_dir / RUNNING_DIR
427 if not running_dir.exists():
428 return []
430 states: list[LoopState] = []
431 for state_file in running_dir.glob("*.state.json"):
432 try:
433 data = json.loads(state_file.read_text())
434 states.append(LoopState.from_dict(data))
435 except (json.JSONDecodeError, KeyError):
436 continue # Skip malformed files
438 return states
441def get_loop_history(loop_name: str, loops_dir: Path | None = None) -> list[dict[str, Any]]:
442 """Get event history for a loop.
444 Args:
445 loop_name: Name of the loop
446 loops_dir: Base directory for loops (default: .loops)
448 Returns:
449 List of event dictionaries
450 """
451 persistence = StatePersistence(loop_name, loops_dir)
452 return persistence.read_events()