Skip to content

event_bus

event_bus

Async pub/sub event bus for the Marianne daemon.

Routes ObserverEvents from the baton and observer to downstream consumers (SSE dashboard, learning hub, future webhooks).

Architecture invariant 5 (load-bearing): the EventBus never blocks publishers. A slow or hung subscriber must never stall the baton/observer that publishes events. EventBus events are observability — unlike the baton's execution inbox (where dropping an event strands a sheet), dropping an event here under overload is acceptable.

To honour that invariant in practice (not just in the letter of a non-blocking publish), this bus isolates subscribers from each other and from the publisher:

  • _pending is a bounded queue. publish() uses put_nowait and, on overflow, evicts the oldest in-flight event before enqueuing the new one (drop-oldest backpressure — slow consumers lose old events, per architecture.yaml), so a publisher can never block and memory can never grow without bound.
  • The single drain loop only filters and enqueues events into each subscriber's own bounded deque (drop-oldest preserves recency for live streams) — it never awaits a subscriber callback.
  • Each subscriber owns a worker task that runs its callback under a per-callback timeout. A slow/hung callback blocks only that subscriber.
  • A subscriber is auto-evicted after _MAX_CONSECUTIVE_FAILURES consecutive callback exceptions, callback timeouts, or filter exceptions — preventing the subscriber dict from leaking dead SSE clients.
  • shutdown() is time-bounded: it cancels the workers and drops any remaining observability events rather than awaiting a hung callback (which would force SIGKILL and risk state corruption).

Classes

EventBus

EventBus(*, max_queue_size=1000, max_pending_size=_DEFAULT_PENDING_MAXSIZE, callback_timeout=_DEFAULT_CALLBACK_TIMEOUT, shutdown_timeout=_DEFAULT_SHUTDOWN_TIMEOUT)

Async pub/sub event bus with per-subscriber isolation.

Subscribers receive events via callbacks executed in their own worker task. A bounded central queue plus per-subscriber bounded deques guarantee that a slow or hung subscriber can neither block the publisher nor stall other subscribers.

Usage::

bus = EventBus(max_queue_size=1000)
await bus.start()

sub_id = bus.subscribe(callback=my_handler)
sub_id = bus.subscribe(
    callback=my_handler,
    event_filter=lambda e: e["event"].startswith("sheet."),
)

await bus.publish(event)

bus.unsubscribe(sub_id)
await bus.shutdown()
Source code in src/marianne/daemon/event_bus.py
def __init__(
    self,
    *,
    max_queue_size: int = 1000,
    max_pending_size: int = _DEFAULT_PENDING_MAXSIZE,
    callback_timeout: float = _DEFAULT_CALLBACK_TIMEOUT,
    shutdown_timeout: float = _DEFAULT_SHUTDOWN_TIMEOUT,
) -> None:
    # max_queue_size comes from Pydantic-validated ObserverConfig — trust
    # that boundary rather than re-validate here. The internal-only tuning
    # params below are guarded because maxsize=0 silently makes the queue
    # unbounded (re-introducing #220) and timeout<=0 breaks asyncio.wait_for.
    if max_pending_size < 1:
        raise ValueError(f"max_pending_size must be >= 1, got {max_pending_size}")
    if callback_timeout <= 0:
        raise ValueError(f"callback_timeout must be > 0, got {callback_timeout}")
    if shutdown_timeout <= 0:
        raise ValueError(f"shutdown_timeout must be > 0, got {shutdown_timeout}")

    self._max_queue_size = max_queue_size
    self._callback_timeout = callback_timeout
    self._shutdown_timeout = shutdown_timeout
    self._subscribers: dict[str, _Subscriber] = {}
    self._drain_task: asyncio.Task[None] | None = None
    self._pending: asyncio.Queue[ObserverEvent] = asyncio.Queue(
        maxsize=max_pending_size
    )
    self._pending_dropped: int = 0
    self._high_water_logged = False
    self._running = False
Attributes
subscriber_count property
subscriber_count

Number of active subscribers.

Methods:
start async
start()

Start the background drain loop and any pending subscriber workers.

Source code in src/marianne/daemon/event_bus.py
async def start(self) -> None:
    """Start the background drain loop and any pending subscriber workers."""
    if self._running:
        return
    self._running = True
    self._drain_task = asyncio.create_task(
        self._drain_loop(), name="event-bus-drain"
    )
    # Start workers for subscribers registered before start().
    for sub_id, sub in self._subscribers.items():
        if sub.task is None:
            self._start_worker(sub_id, sub)
publish async
publish(event)

Publish an event to all matching subscribers.

Non-blocking for the publisher (invariant 5). On a full central queue, the oldest event is dropped to make room — matching the EventBus's spec'd "drop-oldest backpressure: slow consumers lose old events" (architecture.yaml) and the per-subscriber deques. The get_nowait()+put_nowait() pair is atomic here: there is no await between them, so the single-threaded drain loop cannot interleave (and the queue is full, so no getter is waiting).

Source code in src/marianne/daemon/event_bus.py
async def publish(self, event: ObserverEvent) -> None:
    """Publish an event to all matching subscribers.

    Non-blocking for the publisher (invariant 5). On a full central queue,
    the *oldest* event is dropped to make room — matching the EventBus's
    spec'd "drop-oldest backpressure: slow consumers lose old events"
    (architecture.yaml) and the per-subscriber deques. The
    ``get_nowait()``+``put_nowait()`` pair is atomic here: there is no
    ``await`` between them, so the single-threaded drain loop cannot
    interleave (and the queue is full, so no getter is waiting).
    """
    if not self._running:
        return
    try:
        self._pending.put_nowait(event)
    except asyncio.QueueFull:
        # Drop the oldest in-flight event, then enqueue the new one.
        with contextlib.suppress(asyncio.QueueEmpty):
            self._pending.get_nowait()
        with contextlib.suppress(asyncio.QueueFull):
            self._pending.put_nowait(event)
        self._pending_dropped += 1
        if self._pending_dropped % _DROP_LOG_INTERVAL == 1:
            _logger.warning(
                "event_bus.pending_full",
                total_dropped=self._pending_dropped,
                pending_size=self._pending.qsize(),
                event_type=event.get("event"),
            )
subscribe
subscribe(callback, *, event_filter=None)

Register a subscriber.

Parameters:

Name Type Description Default
callback EventCallback

Async or sync callable receiving an ObserverEvent. Sync callbacks MUST be non-blocking (they run in the event loop); async callbacks are bounded by callback_timeout.

required
event_filter EventFilter

Optional predicate. If provided, the subscriber only receives events where it returns True.

None

Returns:

Type Description
str

Subscription ID for later unsubscribe.

Source code in src/marianne/daemon/event_bus.py
def subscribe(
    self,
    callback: EventCallback,
    *,
    event_filter: EventFilter = None,
) -> str:
    """Register a subscriber.

    Args:
        callback: Async or sync callable receiving an ObserverEvent. Sync
            callbacks MUST be non-blocking (they run in the event loop);
            async callbacks are bounded by ``callback_timeout``.
        event_filter: Optional predicate. If provided, the subscriber only
            receives events where it returns True.

    Returns:
        Subscription ID for later unsubscribe.
    """
    sub_id = str(uuid.uuid4())
    sub = _Subscriber(
        callback=callback,
        event_filter=event_filter,
        queue=deque(maxlen=self._max_queue_size),
    )
    self._subscribers[sub_id] = sub
    if self._running:
        self._start_worker(sub_id, sub)
    _logger.info("event_bus.subscribed", sub_id=sub_id)
    return sub_id
unsubscribe
unsubscribe(sub_id)

Remove a subscriber and cancel its worker.

Returns:

Type Description
bool

True if the subscriber existed and was removed.

Source code in src/marianne/daemon/event_bus.py
def unsubscribe(self, sub_id: str) -> bool:
    """Remove a subscriber and cancel its worker.

    Returns:
        True if the subscriber existed and was removed.
    """
    sub = self._subscribers.pop(sub_id, None)
    if sub is None:
        return False
    sub.closing = True
    if sub.task is not None and sub.task is not asyncio.current_task():
        sub.task.cancel()
    _logger.info("event_bus.unsubscribed", sub_id=sub_id)
    return True
shutdown async
shutdown()

Stop the bus within a bounded time, dropping remaining events.

Observability events are droppable; shutdown must never await a hung subscriber callback (which would force SIGKILL).

Source code in src/marianne/daemon/event_bus.py
async def shutdown(self) -> None:
    """Stop the bus within a bounded time, dropping remaining events.

    Observability events are droppable; shutdown must never await a hung
    subscriber callback (which would force SIGKILL).
    """
    self._running = False

    if self._drain_task is not None:
        self._drain_task.cancel()
        try:
            await self._drain_task
        except asyncio.CancelledError:
            pass
        self._drain_task = None

    # Cancel all subscriber workers, bounded by shutdown_timeout.
    tasks: list[asyncio.Task[None]] = []
    for sub in self._subscribers.values():
        sub.closing = True
        if sub.task is not None:
            sub.task.cancel()
            tasks.append(sub.task)
    if tasks:
        await asyncio.wait(tasks, timeout=self._shutdown_timeout)

    dropped = self._pending.qsize()
    self._subscribers.clear()

    _logger.info(
        "event_bus.shutdown",
        dropped_pending=dropped,
        total_dropped=self._pending_dropped,
    )

Functions: