From fc7577d48d848567080aae4663f3b9583f57e0ff Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 23 Oct 2026 13:36:34 +0200 Subject: [PATCH 1/4] feat(api): add a head route decorator to RestApiBase RestApiBase offered get/post/put/patch/delete but no head, so a service that wanted a HEAD route (a cheap existence check before a GET) had to write its own decorator. head() tags the method like the other verbs; _wire_routes() already dispatches to APIRouter.head unchanged. Closes #63 Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 3 +++ README.md | 2 +- src/blueprint/agent_generator/claude_docs/CLAUDE.md | 2 +- .../claude_docs/skills/add-component/SKILL.md | 2 +- src/blueprint/agent_generator/docs/reference/api.md | 1 + src/blueprint/agents/io/api/rest_api_base.py | 12 +++++++++++- tests/unit/agents/io/api/test_rest_api_base.py | 13 +++++++++++-- 7 files changed, 29 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fbe268e..cb6b5e34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -367,6 +367,9 @@ Full migration path, including the one decision to get right before the first de behaviour except `scheduler_mode`, which is required — see **Breaking**. - `pyyaml>=6.0` is now a declared dependency (it reads the group file). Already present in every environment via `uvicorn[standard]`, so no installed set changes. +- **`@RestApiBase.head(path, **kwargs)`** registers a HEAD route, like the other verb decorators + (#63). A service that needed one, for a cheap existence check before a GET, had to write its own + decorator. ### Changed diff --git a/README.md b/README.md index 61d90d2d..cb6d3f3c 100644 --- a/README.md +++ b/README.md @@ -149,7 +149,7 @@ Two things about that chain are worth knowing up front: |-----------|-----------|---------| | **Event Handler** | `EventHandlerBase` | Route CloudEvents (priority chain) and translate each into one service call; returns a result, `HandlerResult.skipped(reason)` or `None` | | **Service** | `ServiceBase` | All business logic, including whether an event needs work; runs the agents | -| **REST API** | `RestApiBase` | Define HTTP endpoints with `@get()`, `@post()`, `@put()`, `@delete()`, `@patch()` decorators | +| **REST API** | `RestApiBase` | Define HTTP endpoints with `@get()`, `@post()`, `@put()`, `@delete()`, `@patch()`, `@head()` decorators | | **Agent** | `AgentRuntime` | Run LLM agents with structured outputs, tool calling, and prompt management | | **Scheduler** | `SchedulerBase` | Execute cron-based background tasks with auto-registered trigger endpoints | diff --git a/src/blueprint/agent_generator/claude_docs/CLAUDE.md b/src/blueprint/agent_generator/claude_docs/CLAUDE.md index 57039147..720ef6b9 100644 --- a/src/blueprint/agent_generator/claude_docs/CLAUDE.md +++ b/src/blueprint/agent_generator/claude_docs/CLAUDE.md @@ -178,7 +178,7 @@ class OrderApi(RestApiBase): return await self._service.create(payload) ``` -Route decorators: `@RestApiBase.get()`, `.post()`, `.put()`, `.delete()`, `.patch()`. +Route decorators: `@RestApiBase.get()`, `.post()`, `.put()`, `.delete()`, `.patch()`, `.head()`. **Creating CloudEvents from REST payloads** — use `create_cloud_event()` when an API endpoint needs to feed a payload into the event processing pipeline: diff --git a/src/blueprint/agent_generator/claude_docs/skills/add-component/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/add-component/SKILL.md index 1d19cb3c..524d3567 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/add-component/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/add-component/SKILL.md @@ -62,7 +62,7 @@ After scaffolding, implement the component logic: - Resolve agent/cache dependencies in `on_startup()` ### RestApi -- Use `@RestApiBase.get/post/put/delete/patch()` decorators +- Use `@RestApiBase.get/post/put/delete/patch/head()` decorators - Use Pydantic models for request/response types - Resolve services in `on_startup()` diff --git a/src/blueprint/agent_generator/docs/reference/api.md b/src/blueprint/agent_generator/docs/reference/api.md index 8d446624..2fa57e54 100644 --- a/src/blueprint/agent_generator/docs/reference/api.md +++ b/src/blueprint/agent_generator/docs/reference/api.md @@ -262,6 +262,7 @@ Use these to decorate methods on your subclass: | `@RestApiBase.put(path, **kwargs)` | Register a PUT endpoint. | | `@RestApiBase.delete(path, **kwargs)` | Register a DELETE endpoint. | | `@RestApiBase.patch(path, **kwargs)` | Register a PATCH endpoint. | +| `@RestApiBase.head(path, **kwargs)` | Register a HEAD endpoint, e.g. a cheap existence check before a GET. | `**kwargs` are forwarded to the underlying FastAPI route registration. diff --git a/src/blueprint/agents/io/api/rest_api_base.py b/src/blueprint/agents/io/api/rest_api_base.py index 08595bc8..a8b60f16 100644 --- a/src/blueprint/agents/io/api/rest_api_base.py +++ b/src/blueprint/agents/io/api/rest_api_base.py @@ -59,7 +59,7 @@ class RestApiBase(IOBase, ABC): Routes are registered by decorating methods with the class-level HTTP verb helpers (``RestApiBase.get``, ``RestApiBase.post``, ``RestApiBase.put``, - ``RestApiBase.delete``, ``RestApiBase.patch``). The base class wires those + ``RestApiBase.delete``, ``RestApiBase.patch``, ``RestApiBase.head``). The base class wires those decorated methods onto ``self.router`` during ``__init__``, so subclasses never need to call ``_wire_routes()`` or touch the router directly. """ @@ -189,6 +189,16 @@ def decorator(func: Callable[..., Any]) -> Callable[..., Any]: return decorator + @staticmethod + def head(path: str, **kwargs: Any) -> Callable[[Callable[..., Any]], Callable[..., Any]]: + """Decorator: register a HEAD route on the instance router.""" + + def decorator(func: Callable[..., Any]) -> Callable[..., Any]: + func._route = ("head", path, kwargs) # type: ignore[attr-defined] + return func + + return decorator + def _wire_routes(self) -> None: """Discover and register all decorated route methods on self.router.""" diff --git a/tests/unit/agents/io/api/test_rest_api_base.py b/tests/unit/agents/io/api/test_rest_api_base.py index 9d1f60f8..42b03fca 100644 --- a/tests/unit/agents/io/api/test_rest_api_base.py +++ b/tests/unit/agents/io/api/test_rest_api_base.py @@ -49,6 +49,10 @@ async def delete_item(self) -> None: async def patch_item(self) -> dict: return {} + @RestApiBase.head("/items/{id}") + async def item_exists(self) -> None: + pass + # --------------------------------------------------------------------------- # Route decorator tests @@ -82,6 +86,11 @@ def test_patch_decorator_attaches_route_attr(self) -> None: assert verb == "patch" assert path == "/items/{id}" + def test_head_decorator_attaches_route_attr(self) -> None: + verb, path, _ = _RoutedApi.item_exists._route + assert verb == "head" + assert path == "/items/{id}" + def test_decorator_stores_kwargs(self) -> None: @RestApiBase.get("/tagged", tags=["foo"], summary="bar") async def tagged_fn(self): @@ -105,10 +114,10 @@ def test_router_has_routes_after_init(self, mock_config: MagicMock) -> None: api = _RoutedApi() assert len(api.router.routes) > 0 - def test_all_five_verbs_are_registered(self, mock_config: MagicMock) -> None: + def test_all_six_verbs_are_registered(self, mock_config: MagicMock) -> None: api = _RoutedApi() flat = {m for route in api.router.routes if hasattr(route, "methods") for m in route.methods} - assert {"GET", "POST", "PUT", "DELETE", "PATCH"}.issubset(flat) + assert {"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"}.issubset(flat) def test_no_routes_when_no_decorated_methods(self, mock_config: MagicMock) -> None: api = _MinimalApi() From 93482240dd273e2227c482c69d35203bbfc87fd9 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 23 Oct 2026 13:38:51 +0200 Subject: [PATCH 2/4] test(sessions): cover agent_token stripping in SessionsBus and SessionsApiClient The agent_token read strips surrounding whitespace at three sites, but only SessionKeyProvider had tests for it. Add the same two cases (padded token, whitespace-only token) for SessionsBus and SessionsApiClient; the client test also checks the Authorization header itself. Separate the changelog title from the first section with a blank line. Closes #107 Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 1 + .../io/api/eventing/test_sessions_bus.py | 23 +++++++++++++++++++ .../services/sessions/test_api_client.py | 21 +++++++++++++++++ 3 files changed, 45 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb6b5e34..14ffb085 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,5 @@ # Changelog + ## [Unreleased] **Multi-agent grouping.** How many agents share a process becomes a *deployment* parameter rather diff --git a/tests/unit/agents/io/api/eventing/test_sessions_bus.py b/tests/unit/agents/io/api/eventing/test_sessions_bus.py index f9fc4d63..9868fb2f 100644 --- a/tests/unit/agents/io/api/eventing/test_sessions_bus.py +++ b/tests/unit/agents/io/api/eventing/test_sessions_bus.py @@ -136,6 +136,29 @@ async def test_agent_token_none_when_absent(self, sessions_bus: SessionsBus, moc assert sessions_bus._agent_token is None sessions_bus._sse_task.cancel() + async def test_agent_token_stripped_on_read(self, sessions_bus: SessionsBus, mock_config: MagicMock, mock_registry: MagicMock) -> None: + # A token mounted from a secret file usually ends in a newline, which is not valid in a header. + mock_config.get.return_value = {**_make_sessions_config(), "agent_token": " agent-jwt\n"} + mock_registry.get_service.return_value = MagicMock() + + with patch.object(sessions_bus, "_consume_sse_stream", new=AsyncMock()): + await sessions_bus.on_startup() + + assert sessions_bus._agent_token == "agent-jwt" + sessions_bus._sse_task.cancel() + + async def test_whitespace_only_agent_token_treated_as_absent( + self, sessions_bus: SessionsBus, mock_config: MagicMock, mock_registry: MagicMock + ) -> None: + mock_config.get.return_value = {**_make_sessions_config(), "agent_token": " \n"} + mock_registry.get_service.return_value = MagicMock() + + with patch.object(sessions_bus, "_consume_sse_stream", new=AsyncMock()): + await sessions_bus.on_startup() + + assert sessions_bus._agent_token is None + sessions_bus._sse_task.cancel() + # --------------------------------------------------------------------------- # on_shutdown diff --git a/tests/unit/agents/services/sessions/test_api_client.py b/tests/unit/agents/services/sessions/test_api_client.py index 3ceac1be..8ed7102a 100644 --- a/tests/unit/agents/services/sessions/test_api_client.py +++ b/tests/unit/agents/services/sessions/test_api_client.py @@ -74,6 +74,27 @@ async def test_no_bearer_header_when_token_absent( assert "Authorization" not in headers assert api_client._agent_token is None + async def test_bearer_header_uses_stripped_token( + self, api_client: SessionsApiClient, mock_config: MagicMock, sessions_config: dict + ) -> None: + # A token mounted from a secret file usually ends in a newline, which is not valid in a header. + mock_config.get.return_value = {**sessions_config, "agent_token": " agent-jwt\n"} + with patch(_PATCH_TARGET) as mock_cls: + await api_client.on_startup() + headers = mock_cls.call_args[1]["headers"] + assert headers["Authorization"] == "Bearer agent-jwt" + assert api_client._agent_token == "agent-jwt" + + async def test_whitespace_only_token_sends_no_bearer( + self, api_client: SessionsApiClient, mock_config: MagicMock, sessions_config: dict + ) -> None: + mock_config.get.return_value = {**sessions_config, "agent_token": " \n"} + with patch(_PATCH_TARGET) as mock_cls: + await api_client.on_startup() + headers = mock_cls.call_args[1]["headers"] + assert "Authorization" not in headers + assert api_client._agent_token is None + # --------------------------------------------------------------------------- # on_shutdown From c5eb46d16b6cffc2d0e4a10d81efed1b69aa6612 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 23 Oct 2026 13:49:21 +0200 Subject: [PATCH 3/4] fix(api): list the routes on the / service page again Since FastAPI 0.137, include_router() leaves a lazy wrapper in app.routes instead of the routes themselves. RootApi filtered app.routes for APIRoute, so every route of an included router -- all routes the framework mounts -- was missing and the table rendered empty. Build the table from app.openapi() instead, the public view of the same routes on every supported FastAPI version. Operations on one path with the same summary still share a row. Routes with include_in_schema=False are no longer listed. The tests now use a real application with an included router instead of a mocked app.routes, which could not see the bug. Closes #42 Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 6 ++ src/blueprint/agents/io/api/utilities/root.py | 37 +++++++--- .../unit/agents/io/api/utilities/test_root.py | 70 +++++++++++++++---- 3 files changed, 92 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 14ffb085..f00c872d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -405,6 +405,12 @@ Full migration path, including the one decision to get right before the first de ### Fixed +- **The `/` service page lists the routes again** (#42). Since FastAPI 0.137, `include_router()` + leaves a wrapper in `app.routes` instead of the routes, and the page found none of them: every + route the framework mounts comes from an included router, so the table was empty. It is now built + from the OpenAPI schema, which works on every supported FastAPI version. A route declared with + `include_in_schema=False` is no longer listed, and an operation without a summary shows the one + FastAPI generates from the function name, as Swagger UI does. - **`asbs validate` no longer fails an image build on an unset `nats_url`.** Outside development it reported one as an issue, and an image that validates while it is built has no `nats_url` yet: the deployment injects it when the container starts. It is a notice now, as `event_bus` is; the diff --git a/src/blueprint/agents/io/api/utilities/root.py b/src/blueprint/agents/io/api/utilities/root.py index abf258de..bbded143 100644 --- a/src/blueprint/agents/io/api/utilities/root.py +++ b/src/blueprint/agents/io/api/utilities/root.py @@ -6,10 +6,12 @@ from fastapi import FastAPI from fastapi.responses import HTMLResponse -from fastapi.routing import APIRoute from ..rest_api_base import RestApiBase +_HTTP_METHODS = frozenset({"GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD", "PATCH", "TRACE"}) +"""Keys of an OpenAPI path item that are operations; the others (``parameters``, ...) are not.""" + class RootApi(RestApiBase): """Exposes a root endpoint listing service metadata and all registered routes.""" @@ -42,17 +44,13 @@ async def root(self) -> Any: doc_links = " | ".join(f'{label}' for label, url in [("Swagger UI", docs_url), ("ReDoc", redoc_url)] if url) rows = [] - for route in self._app.routes: - if not isinstance(route, APIRoute): - continue - route_methods = route.methods or set() + for path, route_methods, summary in self._operations(): methods = ", ".join(sorted(route_methods)) - summary = route.summary or "" if "GET" in route_methods: - path_cell = f'{route.path}' + path_cell = f'{path}' else: - anchor = route.path.replace("/", "-").strip("-") - path_cell = f'{route.path}' if docs_url else route.path + anchor = path.replace("/", "-").strip("-") + path_cell = f'{path}' if docs_url else path rows.append(f"{methods}{path_cell}{summary}") rows_html = "\n".join(rows) @@ -87,3 +85,24 @@ async def root(self) -> Any: """ return self._html_cache + + def _operations(self) -> list[tuple[str, set[str], str]]: + """Return ``(path, methods, summary)`` for every documented operation, in schema order. + + Read from the OpenAPI schema rather than from ``app.routes``: since FastAPI 0.137, + ``include_router()`` leaves a lazy wrapper in ``app.routes`` instead of the routes + themselves, so every route of an included router -- which is every route this framework + mounts -- was missing from the table (#42). The schema is FastAPI's public view of the same + routes, under every version this package supports. It omits routes declared with + ``include_in_schema=False``, which the table therefore no longer lists either. + + Operations on one path with the same summary share a row, as one route declared with + several methods always did. + """ + rows: dict[tuple[str, str], set[str]] = {} + for path, operations in self._app.openapi().get("paths", {}).items(): + for method, operation in operations.items(): + if method.upper() not in _HTTP_METHODS: + continue + rows.setdefault((path, operation.get("summary") or ""), set()).add(method.upper()) + return [(path, methods, summary) for (path, summary), methods in rows.items()] diff --git a/tests/unit/agents/io/api/utilities/test_root.py b/tests/unit/agents/io/api/utilities/test_root.py index dbec322d..ddc04baa 100644 --- a/tests/unit/agents/io/api/utilities/test_root.py +++ b/tests/unit/agents/io/api/utilities/test_root.py @@ -3,7 +3,8 @@ from unittest.mock import MagicMock import pytest -from fastapi.routing import APIRoute +from fastapi import APIRouter, FastAPI +from starlette.responses import PlainTextResponse from blueprint.agents.io.api.utilities.root import RootApi @@ -13,18 +14,22 @@ async def _endpoint() -> None: - """Minimal async callable for building test APIRoute objects.""" + """Minimal async callable for building test routes.""" -_GET_ROUTE = APIRoute("/items", _endpoint, methods=["GET"], summary="List items") -_POST_ROUTE = APIRoute("/data", _endpoint, methods=["POST"], summary="Create data") +_GET_ROUTE = ("/items", ["GET"], "List items") +_POST_ROUTE = ("/data", ["POST"], "Create data") -def _make_app(*, docs_url: str | None = "/docs", redoc_url: str | None = "/redoc", routes: list | None = None) -> MagicMock: - app = MagicMock() - app.docs_url = docs_url - app.redoc_url = redoc_url - app.routes = routes if routes is not None else [] +def _make_app( + *, docs_url: str | None = "/docs", redoc_url: str | None = "/redoc", routes: list[tuple[str, list[str], str]] | None = None +) -> FastAPI: + """A real application whose routes come from an included router, as AppBuilder mounts them.""" + app = FastAPI(docs_url=docs_url, redoc_url=redoc_url) + router = APIRouter() + for path, methods, summary in routes or []: + router.add_api_route(path, _endpoint, methods=methods, summary=summary) + app.include_router(router) return app @@ -85,11 +90,39 @@ async def test_redoc_link_omitted_when_redoc_url_is_none(self, mock_config: Magi class TestRouteRendering: async def test_non_api_route_objects_are_skipped(self, mock_config: MagicMock, mock_registry: MagicMock) -> None: mock_config.get.return_value = "x" - api = RootApi(app=_make_app(routes=[MagicMock()])) # not an APIRoute + app = _make_app() + app.add_route("/plain", lambda request: PlainTextResponse("x")) # a Starlette route, not an APIRoute + api = RootApi(app=app) html = await api.root() tbody = html.split("")[1].split("")[0] assert "" not in tbody + async def test_routes_of_a_prefixed_included_router_are_listed(self, mock_config: MagicMock, mock_registry: MagicMock) -> None: + # #42: since FastAPI 0.137 app.routes holds a wrapper for an included router, not its routes. + mock_config.get.return_value = "x" + app = FastAPI() + inner = APIRouter(prefix="/reports") + inner.add_api_route("/daily", _endpoint, methods=["GET"], summary="Daily report") + nested = APIRouter() + nested.add_api_route("/rebuild", _endpoint, methods=["POST"], summary="Rebuild") + inner.include_router(nested, prefix="/admin") + app.include_router(inner, prefix="/api/agent") + api = RootApi(app=app) + html = await api.root() + assert '/api/agent/reports/daily' in html + assert "/api/agent/reports/admin/rebuild" in html + assert "Daily report" in html + assert "Rebuild" in html + + async def test_route_hidden_from_schema_is_not_listed(self, mock_config: MagicMock, mock_registry: MagicMock) -> None: + mock_config.get.return_value = "x" + app = _make_app(routes=[_GET_ROUTE]) + app.add_api_route("/internal", _endpoint, methods=["GET"], include_in_schema=False) + api = RootApi(app=app) + html = await api.root() + assert "/items" in html + assert "/internal" not in html + async def test_get_route_renders_direct_href_link(self, mock_config: MagicMock, mock_registry: MagicMock) -> None: mock_config.get.return_value = "x" api = RootApi(app=_make_app(routes=[_GET_ROUTE])) @@ -117,13 +150,26 @@ async def test_route_summary_appears_in_table_row(self, mock_config: MagicMock, html = await api.root() assert "List items" in html + # One route serving GET and POST appears twice in the schema, and FastAPI derives both + # operation IDs from the route's first method only, so it warns that they collide. That is + # FastAPI's behaviour for any such route (RestApiBase's decorators never declare one), not + # something this test is about. + @pytest.mark.filterwarnings("ignore:Duplicate Operation ID") async def test_methods_appear_sorted_in_table_row(self, mock_config: MagicMock, mock_registry: MagicMock) -> None: - route = APIRoute("/multi", _endpoint, methods=["POST", "GET"], summary="Multi") mock_config.get.return_value = "x" - api = RootApi(app=_make_app(routes=[route])) + api = RootApi(app=_make_app(routes=[("/multi", ["POST", "GET"], "Multi")])) html = await api.root() assert "GET, POST" in html # sorted order + async def test_two_routes_on_one_path_get_two_rows(self, mock_config: MagicMock, mock_registry: MagicMock) -> None: + mock_config.get.return_value = "x" + api = RootApi(app=_make_app(routes=[("/items", ["GET"], "List items"), ("/items", ["POST"], "Create an item")])) + html = await api.root() + tbody = html.split("")[1].split("")[0] + assert tbody.count("") == 2 + assert "GET" in tbody + assert "POST" in tbody + # --------------------------------------------------------------------------- # Caching From 7b864dd5534343fe4ee573f135162bc328bd6866 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 23 Oct 2026 15:06:03 +0200 Subject: [PATCH 4/4] fix(eventing): skip a handler's event where no publishing service exists A publishing service is registered only beside an event-bus client. With event_bus = "sessions", or no event bus, a handler returning an event_type made process_event() raise after the handler had finished, and every successful sessions job was logged as an unexpected ERROR. Look the publisher up through _publisher_for(), which returns None when neither the agent nor the root has one; the event is then skipped, with a WARNING once per agent and DEBUG afterwards. Absence is checked before the registry lookup rather than by catching its ValueError, so two publishing services at one level still fail the delivery. Closes #40 Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 6 ++ .../eventing/event_processing_service.py | 42 +++++++++++- .../eventing/test_event_processing_service.py | 67 +++++++++++++++++++ 3 files changed, 114 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f00c872d..eed62ccf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -405,6 +405,12 @@ Full migration path, including the one decision to get right before the first de ### Fixed +- **A handler that returns an `event_type` no longer fails its delivery where nothing can publish + it** (#40). A publishing service exists only beside an event-bus client, so with + `event_bus = "sessions"`, or without an event bus, the lookup raised after the handler had + finished, and every successful job was logged as `Unexpected error processing job` at ERROR. The + event is now skipped: a WARNING names the agent and the `event_type` once, later ones log at + DEBUG, and the delivery counts as processed. Two publishing services at one level still fail it. - **The `/` service page lists the routes again** (#42). Since FastAPI 0.137, `include_router()` leaves a wrapper in `app.routes` instead of the routes, and the page found none of them: every route the framework mounts comes from an included router, so the table was empty. It is now built diff --git a/src/blueprint/agents/services/eventing/event_processing_service.py b/src/blueprint/agents/services/eventing/event_processing_service.py index 0f2a8561..7078ae13 100644 --- a/src/blueprint/agents/services/eventing/event_processing_service.py +++ b/src/blueprint/agents/services/eventing/event_processing_service.py @@ -59,6 +59,9 @@ def __init__(self) -> None: # every application that exists today -- behaves exactly as it did. self._handler_chains: dict[str, HandlerChain] = {ROOT_NAMESPACE: HandlerChain()} self._correlation_context = self.registry.correlation_context + # Agents already warned that their handlers' events have nowhere to go: once per agent, + # because in sessions mode every successful job would repeat it. + self._unpublished_warned: set[str] = set() async def on_startup(self) -> None: """Start one handler chain per namespace that has handlers registered in it. @@ -194,7 +197,10 @@ async def process_event( # unscoped lookup this used to be: with one publishing service per # namespace (P6) that finds several and refuses to choose, so a grouped # process would fail on the first handler that returns an event_type. - publisher = self.registry.get_component(EventPublishingService, namespace=namespace) + publisher = self._publisher_for(namespace) + if publisher is None: + self._log_unpublished(namespace, result.event_type) + continue await publisher.publish_handler_event( event_type=result.event_type, data=result.data, @@ -260,6 +266,40 @@ async def process_rest_request( # Private helpers # ------------------------------------------------------------------ + def _publisher_for(self, namespace: str) -> EventPublishingService | None: + """Return the agent's publishing service, else the root's, or ``None`` when neither exists. + + A publishing service exists only beside an event-bus client. A process without one -- + ``event_bus = "sessions"``, or no event bus at all -- has none, and a handler that returns + an ``event_type`` there has nothing to publish on (#40). Absence is checked here rather + than by catching the registry's ``ValueError``, because that error also reports two + publishing services at one level, and ambiguity must still fail the delivery. + """ + own = self.registry.get_components_by_type(EventPublishingService, namespace) + if not own and not self.registry.get_components_by_type(EventPublishingService, ROOT_NAMESPACE): + return None + publisher: EventPublishingService = self.registry.get_component(EventPublishingService, namespace=namespace) + return publisher + + def _log_unpublished(self, namespace: str, event_type: str) -> None: + """Say that a handler's event is not published: WARNING once per agent, DEBUG after that. + + The handler's own work is done by now; only the follow-up event is dropped. Before #40 the + lookup raised instead and the transport logged the delivery as failed after it had + succeeded -- an ERROR on every successful sessions job. + """ + agent = namespace or ROOT_LABEL + if namespace in self._unpublished_warned: + logger.debug("Not publishing event_type '%s' for agent '%s': no event publishing service", event_type, agent) + return + self._unpublished_warned.add(namespace) + logger.warning( + "Agent '%s' returned event_type '%s', but it has no event-bus client to publish on, so handler events are not " + "published. Logged once per agent.", + agent, + event_type, + ) + @staticmethod def _extract_handler_results(handler_result: Any) -> list[HandlerResult]: """Normalize handler output to a list of HandlerResult objects.""" diff --git a/tests/unit/agents/services/eventing/test_event_processing_service.py b/tests/unit/agents/services/eventing/test_event_processing_service.py index 32d2bed2..c4fcf0a3 100644 --- a/tests/unit/agents/services/eventing/test_event_processing_service.py +++ b/tests/unit/agents/services/eventing/test_event_processing_service.py @@ -1,6 +1,7 @@ """Unit tests for EventProcessingService.""" import asyncio +import logging import traceback from pathlib import Path from unittest.mock import AsyncMock, MagicMock @@ -8,11 +9,14 @@ import pytest from pydantic import ValidationError +from blueprint.agents.component.component import Component from blueprint.agents.component.namespace import ROOT_NAMESPACE +from blueprint.agents.component.registry import Registry from blueprint.agents.handler.handler_chain import DUPLICATE_CONTEXT_KEY, IDEMPOTENCY_CACHE_NAMESPACE from blueprint.agents.models.events import GenericCloudEvent, HandlerResult from blueprint.agents.models.result import ProcessingStatus from blueprint.agents.services.eventing.event_processing_service import EventProcessingService +from blueprint.agents.services.eventing.event_publishing_service import EventPublishingService from blueprint.agents.services.infrastructure.cache_service import DiskCacheService from tests.unit.agents.handler.conftest import StubHandler @@ -278,6 +282,69 @@ async def test_each_result_is_published_with_its_position( assert [call.kwargs["index"] for call in publisher.publish_handler_event.await_args_list] == [0, 1] +class TestNoPublishingService: + """#40 -- a process without an event-bus client (sessions mode) has no publishing service. + + A real Registry, not the mocked one: the question is what the registry holds, and a MagicMock + answers every lookup with something. + """ + + @staticmethod + def _publisher(namespace: str = ROOT_NAMESPACE) -> MagicMock: + publisher = MagicMock(spec=EventPublishingService) + publisher.namespace = namespace + publisher.publish_handler_event = AsyncMock() + return publisher + + @staticmethod + def _wire( + service: EventProcessingService, monkeypatch: pytest.MonkeyPatch, publishers: list[MagicMock], namespace: str = ROOT_NAMESPACE + ) -> MagicMock: + registry = Registry(object) + for position, publisher in enumerate(publishers): + registry.add_component(f"publisher-{position}", publisher) + monkeypatch.setattr(Component, "shared_registry", registry) + chain = MagicMock() + chain.process = AsyncMock(return_value=HandlerResult(event_type="classification.completed", data={})) + chain.release = AsyncMock() + service._handler_chains[namespace] = chain + return chain + + async def test_the_delivery_succeeds_and_nothing_is_published( + self, event_processing_service: EventProcessingService, monkeypatch: pytest.MonkeyPatch + ) -> None: + chain = self._wire(event_processing_service, monkeypatch, publishers=[]) + result = await event_processing_service.process_event(GenericCloudEvent(id="e1", type="t", source="s")) + assert result.status is ProcessingStatus.PROCESSED + chain.release.assert_not_awaited() + + async def test_it_warns_once_per_agent_and_then_logs_at_debug( + self, event_processing_service: EventProcessingService, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture + ) -> None: + self._wire(event_processing_service, monkeypatch, publishers=[]) + with caplog.at_level(logging.DEBUG, logger="blueprint.agents.services.eventing.event_processing_service"): + for event_id in ("e1", "e2"): + await event_processing_service.process_event(GenericCloudEvent(id=event_id, type="t", source="s")) + about_it = [record for record in caplog.records if "classification.completed" in record.getMessage()] + assert [record.levelno for record in about_it] == [logging.WARNING, logging.DEBUG] + + async def test_an_agent_without_its_own_publisher_uses_the_root_one( + self, event_processing_service: EventProcessingService, monkeypatch: pytest.MonkeyPatch + ) -> None: + root_publisher = self._publisher() + self._wire(event_processing_service, monkeypatch, publishers=[root_publisher], namespace="orders") + await event_processing_service.process_event(GenericCloudEvent(id="e1", type="t", source="s"), namespace="orders") + root_publisher.publish_handler_event.assert_awaited_once() + + async def test_two_publishers_at_one_level_still_fail_the_delivery( + self, event_processing_service: EventProcessingService, monkeypatch: pytest.MonkeyPatch + ) -> None: + chain = self._wire(event_processing_service, monkeypatch, publishers=[self._publisher(), self._publisher()]) + with pytest.raises(ValueError, match="ambiguous"): + await event_processing_service.process_event(GenericCloudEvent(id="e1", type="t", source="s")) + chain.release.assert_awaited_once() + + class TestASkippedRun: """``HandlerResult.skipped``: acknowledged as SKIPPED, nothing published."""