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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
event_bus.py — Async pub/sub event bus with backpressure, replay, and lane isolation.
|
| 3 |
+
|
| 4 |
+
Features:
|
| 5 |
+
- Multiple subscribers (async generators)
|
| 6 |
+
- Bounded queues with backpressure (slow consumer doesn't kill producer)
|
| 7 |
+
- Terminal events (run.finished, run.error) are NEVER dropped
|
| 8 |
+
- Per-lane sequence tracking for parallel execution
|
| 9 |
+
- Event replay from history for late subscribers
|
| 10 |
+
- Thread-safe for mixed sync/async usage
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import asyncio
|
| 15 |
+
import logging
|
| 16 |
+
import threading
|
| 17 |
+
import time
|
| 18 |
+
from collections import defaultdict
|
| 19 |
+
from typing import Any, AsyncIterator, Callable
|
| 20 |
+
|
| 21 |
+
from purpose_agent.runtime.events import PAEvent, EventKind, Visibility, TERMINAL_KINDS
|
| 22 |
+
|
| 23 |
+
logger = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class EventBus:
|
| 27 |
+
"""
|
| 28 |
+
Async event bus for the Purpose Agent runtime.
|
| 29 |
+
|
| 30 |
+
Usage:
|
| 31 |
+
bus = EventBus(max_queue_size=1000)
|
| 32 |
+
|
| 33 |
+
# Subscribe
|
| 34 |
+
async for event in bus.subscribe(visibility=Visibility.PUBLIC):
|
| 35 |
+
print(event.kind, event.payload)
|
| 36 |
+
|
| 37 |
+
# Publish (can be called from sync or async context)
|
| 38 |
+
bus.emit(event)
|
| 39 |
+
|
| 40 |
+
# Replay (for late subscribers or crash recovery)
|
| 41 |
+
events = bus.replay(run_id="abc123")
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(self, max_queue_size: int = 1000, max_history: int = 10000):
|
| 45 |
+
self._subscribers: list[asyncio.Queue] = []
|
| 46 |
+
self._subscriber_filters: list[dict[str, Any]] = []
|
| 47 |
+
self._max_queue_size = max_queue_size
|
| 48 |
+
self._history: list[PAEvent] = []
|
| 49 |
+
self._max_history = max_history
|
| 50 |
+
self._lane_seqs: dict[str, int] = defaultdict(int)
|
| 51 |
+
self._lock = threading.Lock()
|
| 52 |
+
self._closed = False
|
| 53 |
+
|
| 54 |
+
def emit(self, event: PAEvent) -> None:
|
| 55 |
+
"""
|
| 56 |
+
Publish an event to all subscribers.
|
| 57 |
+
|
| 58 |
+
Terminal events are force-delivered even if queue is full.
|
| 59 |
+
Non-terminal events are dropped if subscriber is too slow (backpressure).
|
| 60 |
+
"""
|
| 61 |
+
if self._closed:
|
| 62 |
+
return
|
| 63 |
+
|
| 64 |
+
# Safety check: reject events with raw chain-of-thought
|
| 65 |
+
if event.has_hidden_cot():
|
| 66 |
+
logger.warning(
|
| 67 |
+
f"EventBus: REJECTED event {event.span_id} — contains hidden chain-of-thought. "
|
| 68 |
+
f"Use EventKind.REASONING_SUMMARY with safe payload instead."
|
| 69 |
+
)
|
| 70 |
+
return
|
| 71 |
+
|
| 72 |
+
with self._lock:
|
| 73 |
+
# Track history for replay
|
| 74 |
+
if len(self._history) >= self._max_history:
|
| 75 |
+
self._history = self._history[-self._max_history // 2:]
|
| 76 |
+
self._history.append(event)
|
| 77 |
+
|
| 78 |
+
# Deliver to subscribers
|
| 79 |
+
for i, queue in enumerate(self._subscribers):
|
| 80 |
+
filters = self._subscriber_filters[i]
|
| 81 |
+
if not self._matches_filter(event, filters):
|
| 82 |
+
continue
|
| 83 |
+
|
| 84 |
+
if event.is_terminal:
|
| 85 |
+
# Terminal events are NEVER dropped — block until delivered
|
| 86 |
+
try:
|
| 87 |
+
queue.put_nowait(event)
|
| 88 |
+
except asyncio.QueueFull:
|
| 89 |
+
# Force: remove oldest non-terminal to make room
|
| 90 |
+
try:
|
| 91 |
+
queue.get_nowait()
|
| 92 |
+
queue.put_nowait(event)
|
| 93 |
+
except (asyncio.QueueEmpty, asyncio.QueueFull):
|
| 94 |
+
pass
|
| 95 |
+
else:
|
| 96 |
+
# Non-terminal: drop if full (backpressure)
|
| 97 |
+
try:
|
| 98 |
+
queue.put_nowait(event)
|
| 99 |
+
except asyncio.QueueFull:
|
| 100 |
+
logger.debug(f"EventBus: backpressure — dropped {event.kind.value} for subscriber {i}")
|
| 101 |
+
|
| 102 |
+
def emit_sync(self, event: PAEvent) -> None:
|
| 103 |
+
"""Alias for emit() — usable from synchronous code."""
|
| 104 |
+
self.emit(event)
|
| 105 |
+
|
| 106 |
+
async def subscribe(
|
| 107 |
+
self,
|
| 108 |
+
visibility: Visibility | None = None,
|
| 109 |
+
lane_id: str | None = None,
|
| 110 |
+
kinds: set[EventKind] | None = None,
|
| 111 |
+
run_id: str | None = None,
|
| 112 |
+
) -> AsyncIterator[PAEvent]:
|
| 113 |
+
"""
|
| 114 |
+
Subscribe to events matching the given filters.
|
| 115 |
+
|
| 116 |
+
Yields PAEvents as they arrive. Stops when bus is closed.
|
| 117 |
+
"""
|
| 118 |
+
queue: asyncio.Queue = asyncio.Queue(maxsize=self._max_queue_size)
|
| 119 |
+
filters = {
|
| 120 |
+
"visibility": visibility,
|
| 121 |
+
"lane_id": lane_id,
|
| 122 |
+
"kinds": kinds,
|
| 123 |
+
"run_id": run_id,
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
self._subscribers.append(queue)
|
| 127 |
+
self._subscriber_filters.append(filters)
|
| 128 |
+
idx = len(self._subscribers) - 1
|
| 129 |
+
|
| 130 |
+
try:
|
| 131 |
+
while not self._closed:
|
| 132 |
+
try:
|
| 133 |
+
event = await asyncio.wait_for(queue.get(), timeout=0.5)
|
| 134 |
+
yield event
|
| 135 |
+
if event.kind in (EventKind.RUN_FINISHED, EventKind.RUN_ERROR):
|
| 136 |
+
break
|
| 137 |
+
except asyncio.TimeoutError:
|
| 138 |
+
continue
|
| 139 |
+
finally:
|
| 140 |
+
# Cleanup
|
| 141 |
+
if idx < len(self._subscribers):
|
| 142 |
+
self._subscribers[idx] = asyncio.Queue() # Orphan the queue
|
| 143 |
+
|
| 144 |
+
def replay(
|
| 145 |
+
self,
|
| 146 |
+
run_id: str | None = None,
|
| 147 |
+
lane_id: str | None = None,
|
| 148 |
+
since_seq: int = 0,
|
| 149 |
+
) -> list[PAEvent]:
|
| 150 |
+
"""
|
| 151 |
+
Replay events from history.
|
| 152 |
+
|
| 153 |
+
Useful for:
|
| 154 |
+
- Late subscribers catching up
|
| 155 |
+
- Crash recovery
|
| 156 |
+
- Debugging
|
| 157 |
+
"""
|
| 158 |
+
with self._lock:
|
| 159 |
+
events = list(self._history)
|
| 160 |
+
|
| 161 |
+
if run_id:
|
| 162 |
+
events = [e for e in events if e.run_id == run_id]
|
| 163 |
+
if lane_id:
|
| 164 |
+
events = [e for e in events if e.lane_id == lane_id]
|
| 165 |
+
if since_seq > 0:
|
| 166 |
+
events = [e for e in events if e.seq > since_seq]
|
| 167 |
+
|
| 168 |
+
return events
|
| 169 |
+
|
| 170 |
+
def next_seq(self, lane_id: str = "main") -> int:
|
| 171 |
+
"""Get and increment the next sequence number for a lane."""
|
| 172 |
+
with self._lock:
|
| 173 |
+
self._lane_seqs[lane_id] += 1
|
| 174 |
+
return self._lane_seqs[lane_id]
|
| 175 |
+
|
| 176 |
+
def close(self) -> None:
|
| 177 |
+
"""Close the bus — no more events will be accepted."""
|
| 178 |
+
self._closed = True
|
| 179 |
+
|
| 180 |
+
@property
|
| 181 |
+
def history_size(self) -> int:
|
| 182 |
+
return len(self._history)
|
| 183 |
+
|
| 184 |
+
@property
|
| 185 |
+
def subscriber_count(self) -> int:
|
| 186 |
+
return len(self._subscribers)
|
| 187 |
+
|
| 188 |
+
@staticmethod
|
| 189 |
+
def _matches_filter(event: PAEvent, filters: dict[str, Any]) -> bool:
|
| 190 |
+
"""Check if an event matches subscriber filters."""
|
| 191 |
+
if filters.get("visibility") and event.visibility != filters["visibility"]:
|
| 192 |
+
# Allow public events to pass through internal/debug filters
|
| 193 |
+
if event.visibility.value > filters["visibility"].value:
|
| 194 |
+
return False
|
| 195 |
+
if filters.get("lane_id") and event.lane_id != filters["lane_id"]:
|
| 196 |
+
return False
|
| 197 |
+
if filters.get("kinds") and event.kind not in filters["kinds"]:
|
| 198 |
+
return False
|
| 199 |
+
if filters.get("run_id") and event.run_id != filters["run_id"]:
|
| 200 |
+
return False
|
| 201 |
+
return True
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def parallel_merge(lane_events: dict[str, list[PAEvent]]) -> list[PAEvent]:
|
| 205 |
+
"""
|
| 206 |
+
Merge events from multiple parallel lanes into a single deterministic stream.
|
| 207 |
+
|
| 208 |
+
Ordering: events are interleaved by timestamp, with lane_id as tiebreaker.
|
| 209 |
+
Each lane's sequence numbers remain monotonic.
|
| 210 |
+
|
| 211 |
+
Usage:
|
| 212 |
+
merged = parallel_merge({
|
| 213 |
+
"lane_a": [event1, event2],
|
| 214 |
+
"lane_b": [event3, event4],
|
| 215 |
+
})
|
| 216 |
+
"""
|
| 217 |
+
all_events = []
|
| 218 |
+
for lane_id, events in lane_events.items():
|
| 219 |
+
for event in events:
|
| 220 |
+
all_events.append(event)
|
| 221 |
+
|
| 222 |
+
# Sort by timestamp, then lane_id for determinism
|
| 223 |
+
all_events.sort(key=lambda e: (e.ts, e.lane_id, e.seq))
|
| 224 |
+
|
| 225 |
+
# Verify lane-local monotonicity
|
| 226 |
+
lane_last_seq: dict[str, int] = {}
|
| 227 |
+
for event in all_events:
|
| 228 |
+
last = lane_last_seq.get(event.lane_id, -1)
|
| 229 |
+
if event.seq < last:
|
| 230 |
+
logger.warning(
|
| 231 |
+
f"parallel_merge: non-monotonic seq in lane {event.lane_id}: "
|
| 232 |
+
f"got {event.seq} after {last}"
|
| 233 |
+
)
|
| 234 |
+
lane_last_seq[event.lane_id] = event.seq
|
| 235 |
+
|
| 236 |
+
return all_events
|