|
| 1 | +# Forensic Features: Trace Persistence and Replay |
| 2 | + |
| 3 | +## Overview |
| 4 | + |
| 5 | +Extend Bond's "Forensic Runtime" capabilities beyond real-time streaming to include trace persistence and replay. This enables: |
| 6 | +- **Audit**: Review what an agent did hours/days ago |
| 7 | +- **Debug**: Replay failed runs step-by-step |
| 8 | +- **Compare**: Analyze different executions side-by-side |
| 9 | + |
| 10 | +## Scope |
| 11 | + |
| 12 | +### In Scope |
| 13 | +- **Trace Capture**: Record all 8 StreamHandlers callback events with metadata |
| 14 | +- **Storage Backend**: Pluggable backend interface with JSON file implementation |
| 15 | +- **Replay API**: SDK method to iterate through stored events |
| 16 | +- **Handler Factory**: `create_capture_handlers()` for easy capture setup |
| 17 | + |
| 18 | +### Out of Scope (Future) |
| 19 | +- Protobuf serialization (start with JSON for debugging) |
| 20 | +- Remote storage backends (S3, database) |
| 21 | +- Cross-trace querying and analytics |
| 22 | +- Real-time trace streaming to external systems |
| 23 | +- Automatic cleanup/retention policies |
| 24 | +- UI replay interface (API only in this phase) |
| 25 | + |
| 26 | +## Approach |
| 27 | + |
| 28 | +### Phase 1: Event Model |
| 29 | + |
| 30 | +Define a unified event structure that normalizes all 8 callback types: |
| 31 | + |
| 32 | +```python |
| 33 | +@dataclass(frozen=True) |
| 34 | +class TraceEvent: |
| 35 | + trace_id: str # UUID for this trace |
| 36 | + sequence: int # Ordering within trace |
| 37 | + timestamp: float # time.monotonic() for ordering |
| 38 | + wall_time: datetime # Human-readable timestamp |
| 39 | + event_type: str # "block_start", "text_delta", etc. |
| 40 | + payload: dict[str, Any] # Event-specific data |
| 41 | +``` |
| 42 | + |
| 43 | +Event types map to StreamHandlers: |
| 44 | +| Callback | event_type | payload keys | |
| 45 | +|----------|------------|--------------| |
| 46 | +| on_block_start | "block_start" | kind, index | |
| 47 | +| on_block_end | "block_end" | kind, index | |
| 48 | +| on_text_delta | "text_delta" | text | |
| 49 | +| on_thinking_delta | "thinking_delta" | text | |
| 50 | +| on_tool_call_delta | "tool_call_delta" | name, args | |
| 51 | +| on_tool_execute | "tool_execute" | id, name, args | |
| 52 | +| on_tool_result | "tool_result" | id, name, result | |
| 53 | +| on_complete | "complete" | data | |
| 54 | + |
| 55 | +### Phase 2: Storage Backend Protocol |
| 56 | + |
| 57 | +```python |
| 58 | +@runtime_checkable |
| 59 | +class TraceStorageProtocol(Protocol): |
| 60 | + async def save_event(self, event: TraceEvent) -> None: |
| 61 | + """Append event to trace.""" |
| 62 | + ... |
| 63 | + |
| 64 | + async def finalize_trace(self, trace_id: str) -> None: |
| 65 | + """Mark trace as complete.""" |
| 66 | + ... |
| 67 | + |
| 68 | + async def load_trace(self, trace_id: str) -> AsyncIterator[TraceEvent]: |
| 69 | + """Load events for replay.""" |
| 70 | + ... |
| 71 | + |
| 72 | + async def list_traces(self, limit: int = 100) -> list[TraceMeta]: |
| 73 | + """List available traces.""" |
| 74 | + ... |
| 75 | +``` |
| 76 | + |
| 77 | +Initial implementation: `JSONFileTraceStore` writing to `.bond/traces/{trace_id}.json` |
| 78 | + |
| 79 | +### Phase 3: Capture Handler Factory |
| 80 | + |
| 81 | +```python |
| 82 | +def create_capture_handlers( |
| 83 | + storage: TraceStorageProtocol, |
| 84 | + trace_id: str | None = None, # Auto-generate if None |
| 85 | +) -> tuple[StreamHandlers, str]: |
| 86 | + """Create handlers that capture events to storage. |
| 87 | +
|
| 88 | + Returns: |
| 89 | + (handlers, trace_id) - handlers for agent.ask(), and trace ID for later replay |
| 90 | + """ |
| 91 | +``` |
| 92 | + |
| 93 | +### Phase 4: Replay API |
| 94 | + |
| 95 | +```python |
| 96 | +class TraceReplayer: |
| 97 | + def __init__(self, storage: TraceStorageProtocol, trace_id: str): |
| 98 | + ... |
| 99 | + |
| 100 | + async def __aiter__(self) -> AsyncIterator[TraceEvent]: |
| 101 | + """Iterate through all events.""" |
| 102 | + ... |
| 103 | + |
| 104 | + async def step(self) -> TraceEvent | None: |
| 105 | + """Get next event (for manual stepping).""" |
| 106 | + ... |
| 107 | + |
| 108 | + @property |
| 109 | + def current_position(self) -> int: |
| 110 | + """Current event index.""" |
| 111 | + ... |
| 112 | +``` |
| 113 | + |
| 114 | +## Key Files |
| 115 | + |
| 116 | +| File | Purpose | |
| 117 | +|------|---------| |
| 118 | +| `src/bond/trace/__init__.py` | NEW - Module exports | |
| 119 | +| `src/bond/trace/_models.py` | NEW - TraceEvent, TraceMeta models | |
| 120 | +| `src/bond/trace/_protocols.py` | NEW - TraceStorageProtocol | |
| 121 | +| `src/bond/trace/backends/json_file.py` | NEW - JSON file storage | |
| 122 | +| `src/bond/trace/capture.py` | NEW - create_capture_handlers | |
| 123 | +| `src/bond/trace/replay.py` | NEW - TraceReplayer class | |
| 124 | +| `src/bond/utils.py` | UPDATE - Add capture handler factory | |
| 125 | +| `tests/unit/trace/` | NEW - Test directory | |
| 126 | + |
| 127 | +## Reuse Points |
| 128 | + |
| 129 | +- **Event structure**: Inspired by `create_websocket_handlers()` JSON format (`src/bond/utils.py:34-86`) |
| 130 | +- **Protocol pattern**: Follow `src/bond/tools/memory/_protocols.py` style |
| 131 | +- **Storage pattern**: Similar to `AgentMemoryProtocol` but for events |
| 132 | + |
| 133 | +## Quick Commands |
| 134 | + |
| 135 | +```bash |
| 136 | +# Run trace tests |
| 137 | +uv run pytest tests/unit/trace/ -v |
| 138 | + |
| 139 | +# Type check |
| 140 | +uv run mypy src/bond/trace/ |
| 141 | + |
| 142 | +# Example usage (after implementation) |
| 143 | +python -c " |
| 144 | +from bond.trace import JSONFileTraceStore, create_capture_handlers, TraceReplayer |
| 145 | +store = JSONFileTraceStore() |
| 146 | +handlers, trace_id = create_capture_handlers(store) |
| 147 | +print(f'Trace ID: {trace_id}') |
| 148 | +" |
| 149 | +``` |
| 150 | + |
| 151 | +## Acceptance |
| 152 | + |
| 153 | +- [ ] `TraceEvent` model captures all 8 callback types |
| 154 | +- [ ] `TraceStorageProtocol` defines storage interface |
| 155 | +- [ ] `JSONFileTraceStore` implements protocol with file-based storage |
| 156 | +- [ ] `create_capture_handlers()` returns working StreamHandlers |
| 157 | +- [ ] `TraceReplayer` can iterate through stored traces |
| 158 | +- [ ] All tests pass with >80% coverage on trace module |
| 159 | +- [ ] `mypy` and `ruff` pass |
| 160 | +- [ ] Documentation added to architecture page |
| 161 | + |
| 162 | +## Open Questions |
| 163 | + |
| 164 | +1. **Trace directory**: Use `.bond/traces/` or configurable path? |
| 165 | +2. **Large tool results**: Truncate at what size? 1MB? 10MB? |
| 166 | +3. **Crash handling**: How to mark incomplete traces? Separate "status" field? |
| 167 | +4. **Event ordering**: Use monotonic clock + sequence number for guaranteed order? |
| 168 | + |
| 169 | +## References |
| 170 | + |
| 171 | +- WebSocket handler pattern: `src/bond/utils.py:20-118` |
| 172 | +- StreamHandlers dataclass: `src/bond/agent.py:28-73` |
| 173 | +- Event sourcing StoredEvent: https://eventsourcing.readthedocs.io/ |
| 174 | +- OTel trace format: https://opentelemetry.io/docs/specs/semconv/gen-ai/ |
0 commit comments