Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 0 additions & 14 deletions .github/actions/setup-python-env/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,11 @@ runs:
uses: astral-sh/setup-uv@v6

- name: Set up Python ${{ inputs.python-version }}
id: setup-python
uses: actions/setup-python@v5
with:
python-version: ${{ inputs.python-version }}

- name: Cache virtual environment
uses: actions/cache@v4
id: cache-venv
with:
path: .venv
# Key on the resolved patch version (e.g. 3.13.14), not just "3.13".
# A venv's bin/ scripts hard-code the interpreter path; when the runner
# bumps its 3.13.x patch the old cached interpreter disappears and the
# restored scripts fail with "cannot execute: required file not found".
key: venv-${{ runner.os }}-py${{ steps.setup-python.outputs.python-version }}-${{ hashFiles('pyproject.toml') }}

- name: Create venv and install dependencies
# Always run: idempotent with uv, and it repairs a restored venv whose
# interpreter path drifted. On a clean cache hit this is a fast no-op.
shell: bash
run: |
uv venv .venv
Expand Down
51 changes: 51 additions & 0 deletions docs/concepts/event-processing.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,57 @@ default_pubsub_name = "default"
"document.summarized" = "documents.processed"
```

## Broker Startup Resilience

By default the framework does not require the broker to be reachable when the service starts. The broker connection and topic subscriptions are established in a background task so the application enters a live state immediately, even if the NATS server or Dapr sidecar is temporarily unavailable.

### Startup sequence

1. `AppBuilder.build()` completes and the FastAPI application starts.
2. `/health/live` returns `200` immediately — the process is alive.
3. The eventing component attempts to connect and subscribe in the background.
4. Until the connection succeeds, `/health/ready` returns `503` because the underlying client health check reports `unhealthy`.
5. Once the broker is reachable and all subscriptions are established, `/health/ready` returns `200`.

This behaviour is particularly useful in Kubernetes where Dapr sidecars or NATS may become available a few seconds after the application container starts.

### Configuration

```toml
# Retry indefinitely (default) — suitable for Kubernetes where the broker
# eventually becomes available.
event_client_max_retries = -1
event_client_retry_delay = 5.0

# Fail fast after 3 attempts — useful for local development to surface
# misconfiguration quickly.
event_client_max_retries = 3
event_client_retry_delay = 2.0
```

| Key | Default | Behaviour |
|-----|---------|-----------|
| `event_client_max_retries` | `-1` | `-1` = retry indefinitely. `0` = single attempt. `N` = N retries after the first failure. |
| `event_client_retry_delay` | `5.0` | Seconds between attempts. |

When all retries are exhausted (i.e. `event_client_max_retries >= 0` and the limit is reached), the error is logged at `ERROR` level with a full traceback. The application remains live but permanently not-ready.

### Kubernetes probe recommendations

Because the broker connection is asynchronous, tune the readiness probe to allow enough time for the broker to start:

```yaml
readinessProbe:
httpGet:
path: /health/ready
port: 8000
initialDelaySeconds: 10
periodSeconds: 10
failureThreshold: 12 # tolerate up to ~2 minutes of broker unavailability
```

---

## Sessions Transport

When `event_bus = "sessions"`, `AppBuilder.build()` wires three components automatically:
Expand Down
2 changes: 2 additions & 0 deletions docs/guides/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,8 @@ Returns a readiness check indicating the application and its dependencies are re

Use this for the Kubernetes readiness probe. If this endpoint fails, the pod is removed from the service load balancer until it recovers.

> **Event broker startup**: the broker connection (NATS / Dapr) is established asynchronously after startup. `/health/ready` returns `503` until the broker is reachable and all topic subscriptions are active. Set `failureThreshold` high enough to tolerate the broker's own startup time — see [Broker Startup Resilience](../concepts/event-processing.md#broker-startup-resilience).

### /health/detailed

Returns component-level health status for debugging and monitoring.
Expand Down
4 changes: 4 additions & 0 deletions docs/reference/configuration-keys.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ Settings for the event bus transport layer.
|-----|------|---------|-------------|
| `event_bus` | `str` | `""` | Event bus implementation. Set to `"dapr"` for Dapr pub/sub or `"nats"` for NATS. Empty string disables the event bus. |
| `nats_url` | `str` | `"nats://localhost:4222"` | NATS server URL. Only used when `event_bus = "nats"`. |
| `event_client_max_retries` | `int` | `-1` | Number of reconnection attempts if the broker is unavailable at startup. `-1` retries indefinitely until the broker becomes reachable. `0` makes a single attempt and logs a permanent error on failure. |
| `event_client_retry_delay` | `float` | `5.0` | Seconds to wait between reconnection attempts. |

---

Expand Down Expand Up @@ -125,6 +127,8 @@ log_format = "text"
# Event Bus
event_bus = "nats"
nats_url = "nats://localhost:4222"
event_client_max_retries = -1 # retry indefinitely
event_client_retry_delay = 5.0 # seconds between attempts

# Prompts
prompt_directory = "prompts"
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "avs-blueprint-agents"
version = "0.6.3"
version = "0.6.4"
description = "Microservice blueprint for creating agents"
authors = [
{ name = "Blueprint Team", email = "patrick.maue@bechtle.com" },
Expand Down
2 changes: 1 addition & 1 deletion src/blueprint/agents/clients/ai/openai_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ async def close(self) -> None:
await self._client.close()
self._client = None

async def subscribe(self, topic: str, callback: Callable[[CloudEvent[Any]], Awaitable[None]]) -> None:
async def subscribe(self, topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]]) -> None:
logger.warning("OpenAI client does not support subscriptions")

async def publish(self, topic: str, event: CloudEvent[Any], routing_key: str | None = None) -> None:
Expand Down
2 changes: 1 addition & 1 deletion src/blueprint/agents/clients/ai/vllm_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ async def close(self) -> None:
await self._client.close()
self._client = None

async def subscribe(self, topic: str, callback: Callable[[CloudEvent[Any]], Awaitable[None]]) -> None:
async def subscribe(self, topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]]) -> None:
logger.warning("VLLM client does not support subscriptions")

async def publish(self, topic: str, event: CloudEvent[Any], routing_key: str | None = None) -> None:
Expand Down
9 changes: 7 additions & 2 deletions src/blueprint/agents/clients/client_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,13 @@ async def close(self) -> None:
raise NotImplementedError

@abstractmethod
async def subscribe(self, topic: str, callback: Callable[[CloudEvent[Any]], Awaitable[None]]) -> None:
"""Subscribe to a topic with a callback for incoming events."""
async def subscribe(self, topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]]) -> None:
"""Register all topic→callback mappings and begin the managed connection + subscription cycle.

Implementations must be non-blocking: store the mapping and start a
background retry task, then return immediately. The ``subscriptions_ready``
property reports whether the cycle has completed successfully.
"""
raise NotImplementedError

@abstractmethod
Expand Down
125 changes: 114 additions & 11 deletions src/blueprint/agents/clients/io/dapr_client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Dapr client implementation for eventing."""

import asyncio
import contextlib
import json
import logging
from collections.abc import Awaitable, Callable
Expand All @@ -19,7 +21,63 @@


class DaprClient(IOClientBase):
"""Dapr client for publishing CloudEvents via Dapr pub/sub."""
"""Dapr client for publishing CloudEvents via Dapr pub/sub.

Managed subscription lifecycle
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Dapr subscriptions are declarative: the Dapr sidecar calls
``GET /dapr/subscribe`` to discover topics and then pushes matching
events to ``POST /events/{topic}``. No programmatic subscribe call to
the broker is required.

``subscribe(topic_callbacks)`` stores the callback mapping for use by
``DaprEventing.publish()`` and starts a background retry task that
pings the sidecar until it responds. ``subscriptions_ready`` becomes
``True`` once the sidecar is confirmed reachable; ``health_check()``
additionally pings the sidecar on every call so runtime availability is
always reflected.

Config keys
~~~~~~~~~~~
``event_client_max_retries`` (int, default -1): retries after first
failure; ``-1`` = indefinite, ``0`` = single attempt.
``event_client_retry_delay`` (float, default 5.0): seconds between retries.
"""

def __init__(self) -> None:
super().__init__()
self._topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = {}
self._subscriptions_ready: bool = False
self._subscriptions_managed: bool = False
self._retry_task: asyncio.Task[None] | None = None

# ------------------------------------------------------------------
# Public state
# ------------------------------------------------------------------

@property
def subscriptions_ready(self) -> bool:
"""``True`` once the sidecar was confirmed reachable at startup."""
return self._subscriptions_ready

# ------------------------------------------------------------------
# Managed subscription API
# ------------------------------------------------------------------

async def subscribe(self, topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]]) -> None:
"""Store topic→callback mappings and start the background sidecar-ping retry task.

Returns immediately; sidecar reachability check happens in the background.
"""
self._topic_callbacks = topic_callbacks
self._subscriptions_managed = True
self._subscriptions_ready = False
self._retry_task = asyncio.ensure_future(self._start_with_retry())
self._retry_task.add_done_callback(self._on_retry_done)

# ------------------------------------------------------------------
# Connection
# ------------------------------------------------------------------

def _is_connected(self) -> bool:
return self._client is not None
Expand All @@ -28,23 +86,23 @@ async def connect(self) -> None:
"""Initialize the HTTP client for Dapr communication."""
if self._client is not None:
return

self._client = httpx.AsyncClient()
logger.info("Initialized Dapr client at %s", self.config.get("dapr_url", "http://localhost:3500"))

async def close(self) -> None:
"""Close the HTTP client."""
"""Cancel the retry task and close the HTTP client."""
if self._retry_task and not self._retry_task.done():
self._retry_task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await self._retry_task

if self._client is not None:
await self._client.aclose()
self._client = None

async def subscribe(self, topic: str, callback: Callable[[CloudEvent[Any]], Awaitable[None]]) -> None:
"""Subscribe to a topic.

Note: Dapr subscriptions are typically configured declaratively,
not programmatically. This method is a no-op.
"""
logger.warning("Dapr subscriptions should be configured declaratively, not via client")
# ------------------------------------------------------------------
# Publish
# ------------------------------------------------------------------

async def publish(
self,
Expand Down Expand Up @@ -72,12 +130,19 @@ async def publish(
logger.error("Failed to publish event to Dapr topic '%s': %s", topic, str(e))
raise

# ------------------------------------------------------------------
# Health
# ------------------------------------------------------------------

async def health_check(self) -> ComponentHealth:
"""Check Dapr sidecar availability."""
"""Return healthy only when subscriptions are established and sidecar is reachable."""
if not self.config.get("health_check_dapr", True):
logger.debug("Dapr health check is disabled")
return ComponentHealth(status="healthy", message="Dapr health check disabled")

if self._subscriptions_managed and not self._subscriptions_ready:
return ComponentHealth(status="unhealthy", message="subscriptions not yet established")

dapr_url = self.config.get("dapr_url", "http://localhost:3500")
try:
client = await self.client
Expand All @@ -93,3 +158,41 @@ async def health_check(self) -> ComponentHealth:
except Exception as e:
logger.error("Unexpected error during Dapr health check: %s", e, exc_info=True)
return ComponentHealth(status="unhealthy", message=f"Health check error: {e}")

# ------------------------------------------------------------------
# Internal — retry loop
# ------------------------------------------------------------------

async def _start_with_retry(self) -> None:
max_retries: int = self.config.get("event_client_max_retries", -1)
delay: float = float(self.config.get("event_client_retry_delay", 5.0))
attempt = 0
while True:
try:
await self._connect_and_subscribe()
self._subscriptions_ready = True
logger.info("DaprClient connected and sidecar reachable")
return
except Exception as e:
attempt += 1
self._subscriptions_ready = False
if max_retries != -1 and attempt > max_retries:
raise
logger.warning("DaprClient attempt %d failed, retrying in %.1fs: %s", attempt, delay, e)
await asyncio.sleep(delay)

def _on_retry_done(self, task: asyncio.Task[None]) -> None:
if task.cancelled():
return
exc = task.exception()
if exc is not None:
logger.error("DaprClient permanently failed after exhausting retries: %s", exc, exc_info=exc)

async def _connect_and_subscribe(self) -> None:
"""Connect the HTTP client and verify the Dapr sidecar is reachable."""
await self.connect()
if self.config.get("health_check_dapr", True):
dapr_url = self.config.get("dapr_url", "http://localhost:3500")
client = await self.client
response = await client.get(f"{dapr_url}/v1.0/healthz")
response.raise_for_status()
Loading
Loading